Volatility Prism [JOAT]Volatility Prism
Introduction
Volatility Prism is an open-source dual Bollinger Band envelope system with percentile-based bandwidth squeeze detection and Stochastic RSI confirmation. It renders two independent envelopes — an inner band at a configurable standard deviation multiplier and an outer band at a wider multiplier — with gradient fills that color dynamically based on whether price is in a bullish or bearish position relative to the moving average basis. When the bandwidth compresses to a historically low percentile, a squeeze state is declared. When the squeeze releases, an expansion signal fires.
The problem Volatility Prism solves is that volatility states are cyclical: periods of compression (squeeze) reliably precede periods of expansion (breakout), and the direction of the breakout is where the opportunity lies. By combining a statistically-based squeeze detector — which uses percentile thresholds rather than fixed bandwidth levels — with Stochastic RSI extreme confirmation, Volatility Prism identifies both the compression state and the likely directional bias of the coming expansion simultaneously.
Core Concepts
1. Dual Bollinger Band Structure
Two separate Bollinger Band pairs share the same basis (SMA of the source) but use different standard deviation multipliers. The inner band (default 2.0x) is the primary envelope. The outer band (default 3.0x) defines the extreme extension zone. Price trading beyond the inner band but inside the outer band is in the elevated zone. Price trading beyond the outer band is in a statistical extreme:
basis = ta.sma(src, bbLen)
dev = ta.stdev(src, bbLen)
upper1 = basis + bbMult1 * dev // Inner upper
lower1 = basis - bbMult1 * dev // Inner lower
upper2 = basis + bbMult2 * dev // Outer upper
lower2 = basis - bbMult2 * dev // Outer lower
The trend bias is determined by whether the close is above or below the basis. When bullish, all envelope lines and fills render in the bullish color. When bearish, they render in the bearish color. This makes the trend state immediately visible from the envelope color alone.
2. Gradient Envelope Fills
Four gradient fills create the visual envelope structure. The inner fills gradient from a near-opaque shade at the band edge to a nearly transparent shade at the basis, creating a density effect that visually represents how far price is from the center. The outer fills extend this gradient into the extreme zone at reduced opacity, cleanly separating the normal, elevated, and extreme price zones:
fill(basisPlot, upper1Plot, upper1, basis, color.new(envCol, 85), color.new(envCol, 98), "Upper Inner Fill")
fill(upper1Plot, upper2Plot, upper2, upper1, color.new(envCol, 75), color.new(envCol, 88), "Upper Outer Fill")
3. Percentile-Based Bandwidth Squeeze Detection
The bandwidth (the width of the inner band as a percentage of the basis) is computed on each bar and added to a rolling history array of configurable length. The current bandwidth is compared to the percentile threshold of that history — if the current bandwidth is below the configured percentile (default 15th percentile), the squeeze state is active:
bandwidth = basis > 0 ? (upper1 - lower1) / basis * 100 : 0.0
// Sort history and find threshold at configured percentile
threshIdx = int(array.size(sorted) * sqzPctile / 100) - 1
sqzThreshold = array.get(sorted, threshIdx)
isSqueezing = bandwidth <= sqzThreshold
This approach adapts to the instrument and timeframe automatically — a 15th percentile squeeze on a low-volatility bond future and on a high-volatility crypto asset will both correctly identify when that specific instrument is in an unusually compressed state relative to its own history.
4. Stochastic RSI Extreme Confirmation
The Stochastic RSI (an oscillator that applies Stochastic logic to RSI values) provides momentum extreme confirmation. Overbought and oversold readings from the K and D lines confirm when band extremes coincide with momentum extremes, strengthening band rejection signals:
rsiVal = ta.rsi(src, rsiLen)
stochVal = ta.stoch(rsiVal, rsiVal, rsiVal, stochLen)
kLine = ta.sma(stochVal, smoothK)
dLine = ta.sma(kLine, smoothD)
stochOB = kLine > upperLim and dLine > upperLim // Overbought
stochOS = kLine < lowerLim and dLine < lowerLim // Oversold
5. Band Rejection Signals and Squeeze Breakout
Three signal types are generated. Bullish band rejection fires when price was below the inner lower band on the previous bar and closes back above it, with Stochastic RSI confirming oversold — a failed breakdown with momentum confirmation. Bearish band rejection fires on the symmetric condition above the inner upper band. Squeeze Breakout fires on the first bar that transitions from squeeze to non-squeeze state — the moment the bandwidth begins expanding:
bearRejection = close > upper1 and close <= upper1 and stochOB
bullRejection = close < lower1 and close >= lower1 and stochOS
sqzBreakout = isSqueezing and not isSqueezing
6. Band Price Labels at the Right Edge
All five band lines (U2, U1, MA, L1, L2) receive price labels at the right edge of the chart. These labels update every bar to show the current price of each level, eliminating the need to hover over lines or read the y-axis to determine band values:
if barstate.islast and showBandLbls
lblU2 := label.new(bar_index + 2, upper2,
"U2 " + str.tostring(upper2, format.mintick),
style=label.style_label_right, ...)
Features
Dual Bollinger Band envelopes: Inner and outer bands with independently configurable multipliers
Adaptive gradient fills: Four gradient fills (inner upper, inner lower, outer upper, outer lower) color dynamically with trend bias
Dynamic trend coloring: All envelope elements switch between bullish and bearish colors based on close vs. basis
Percentile-based squeeze detection: Bandwidth compared to a configurable percentile of its rolling history — adapts to any instrument's volatility profile
Configurable squeeze lookback: Rolling bandwidth history window from 20 to 500 bars
Squeeze background shading: Optional chart background shading during active squeeze state
Stochastic RSI confirmation: K and D line extreme zones confirm band rejection signal quality
Three signal types: Bull Rejection, Bear Rejection, and Squeeze Breakout markers with distinct shapes
Band price labels at right edge: Live price labels for all five band levels (U2, U1, MA, L1, L2) at bar_index + 2
Institutional dashboard (top right): 11-row table with Volatility state (SQUEEZE/EXPANDING), Bandwidth %, Trend, StochRSI state, K and D values, Basis price, and Envelope range
Fully configurable inputs: BB length, both multipliers, squeeze lookback and percentile, Stochastic RSI parameters, and all colors independently adjustable
Alerts: Bull Rejection, Bear Rejection, Squeeze Breakout, and Squeeze Entry alertconditions
Input Parameters
Bollinger Bands:
Source: Price source (default: close)
BB Length: MA and standard deviation period (default: 20)
Inner Mult: Standard deviation multiplier for inner bands (default: 2.0)
Outer Mult: Standard deviation multiplier for outer bands (default: 3.0)
Squeeze Detection:
Bandwidth Lookback: Rolling history window for percentile calculation (default: 120 bars)
Squeeze Percentile: Bandwidth percentile below which squeeze is active (default: 15th)
Stochastic RSI:
K Smoothing (default: 3), D Smoothing (default: 3)
RSI Length (default: 14), Stochastic Length (default: 14)
Overbought level (default: 80), Oversold level (default: 20)
Display:
Show Dashboard toggle
Squeeze Background toggle
Band Price Labels toggle
Bullish Envelope color, Bearish Envelope color, Basis Line color, Squeeze Background color
How to Use This Indicator
Step 1: Identify the Volatility State
The dashboard's Volatility row shows SQUEEZE (yellow) or EXPANDING (gray). When SQUEEZE is active, the chart background shades yellow. A squeeze state means bandwidth has compressed to a historically low percentile — the market is loading energy for a directional move.
Step 2: Watch for Squeeze Breakout Signals
The cross (x) marker appears at the first bar that exits a squeeze. This is the moment bandwidth begins expanding. The direction of the breakout bar (bullish or bearish candle) combined with the trend color of the envelope provides the directional lean for the expansion phase.
Step 3: Interpret Envelope Color for Trend Bias
When all envelope elements are teal, price is above the basis — bullish bias. When all elements are orange, price is below the basis — bearish bias. Use the envelope color as a continuous trend indicator overlaid directly on the price.
Step 4: React to Band Rejection Diamonds
Diamond markers at the band edge indicate price failed to sustain a move beyond the inner band and recovered inside, with Stochastic RSI confirming the extreme. These are mean-reversion entry signals — price rejected the statistical extreme with momentum confirmation.
Step 5: Reference Band Price Labels
The right-edge labels show the current price of each band level. Use these when planning take-profit targets (opposite band) or stop-loss placement (outer band beyond entry) without needing to manually read prices from band lines.
Indicator Limitations
The squeeze detector requires a minimum of sqzLen bars of bandwidth history to activate. On short charts or immediately after the indicator is applied, the squeeze state will not register until enough history is accumulated
The percentile-based squeeze threshold adapts to the lookback window. A longer lookback produces a more stable threshold; a shorter lookback adapts faster but may produce more frequent squeeze entries and exits
Band rejection signals require the close to recover inside the band on the bar immediately following the outside close. Multi-bar breakouts that recover more slowly are not detected as rejections
Squeeze Breakout markers fire on the first bar exiting a squeeze regardless of candle size or direction. They do not independently confirm the breakout direction — the envelope trend color and Stochastic RSI must be used to assess directional bias
Stochastic RSI is a double-transformed oscillator (RSI → Stochastic). It can reach and hold extreme levels for extended periods in strong trends, producing frequent overbought or oversold readings that reduce the specificity of band rejection confirmation
Originality Statement
Volatility Prism is original in its adaptive, percentile-based squeeze detection combined with a dual-envelope gradient structure and Stochastic RSI extreme confirmation with right-edge band price labels. This indicator is published because:
Using the rolling percentile of bandwidth history — rather than fixed bandwidth values or the classic Keltner Channel comparison method — for squeeze detection provides an instrument-adaptive and timeframe-adaptive threshold that requires no manual calibration
The dual-envelope structure (inner and outer bands) with four independent gradient fills that change color based on real-time trend bias creates a visually rich, information-dense chart overlay without adding separate indicator panes
The right-edge band price labels for all five band levels eliminate a common usability friction point in Bollinger Band analysis, where traders must hover over lines or estimate prices from the y-axis scale
The three-signal system (Bull Rejection, Bear Rejection, Squeeze Breakout) operating from two independent mechanisms (band geometry + Stochastic RSI for rejections, bandwidth percentile for breakout) provides distinct signal categories suited to different trading styles
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Bollinger Bands and Stochastic RSI readings are historical statistical tools. Squeeze states can persist for extended periods without producing a breakout, and breakouts can occur in either direction. Band rejection signals do not guarantee price will reverse from the band. Always use proper risk management. The author is not responsible for any trading losses resulting from the use of this indicator.
-Made with passion by jackofalltrades
Indicator

Indicator

Deviation Lens [JOAT]Deviation Lens
Introduction
Deviation Lens is an open-source multi-dimensional statistical displacement tool that applies Z-Score analysis simultaneously to three market dimensions: price level, close-to-close price change, and volume. Rather than using arbitrary overbought/oversold thresholds derived from historical maxima and minima, Deviation Lens computes exactly how many standard deviations each dimension is from its recent rolling mean. This provides a precise, adaptive, distribution-aware measure of how statistically extreme current market conditions are.
The core insight is that markets are mean-reverting systems over short time horizons. Statistical extremes — conditions where price, momentum, or volume are far from their recent averages — represent transient states. The further from the mean, the greater the statistical probability that conditions will normalize. Deviation Lens quantifies this probability directly, from 0% (at the mean) to 99.7% (at three standard deviations), and displays it as a live reversal probability for every bar.
Core Concepts
1. Three-Dimensional Z-Score Calculation
Three independent Z-Scores are computed on every bar:
The Price Z-Score measures how far the current close is from the rolling mean close in standard deviation units. This captures whether the current price level is statistically cheap or expensive relative to recent history.
The Change Z-Score measures how far the current bar's close-to-close price change is from the rolling mean change — quantifying momentum extremity rather than price level extremity.
The Volume Z-Score measures how far the current volume is from the rolling mean volume. High-volume Z-Score values identify bars where unusual institutional participation is statistically evident:
priceZ = priceStd > 0 ? (close - priceMean) / priceStd : 0.0
changeZ = changeStd > 0 ? (chg - changeMean) / changeStd : 0.0
volumeZ = volStd > 0 ? (volume - volMean) / volStd : 0.0
2. Reversal Probability Mapping
The absolute Z-Score is mapped to a reversal probability percentage based on the properties of the normal distribution. A Z-Score of 1.0 corresponds to 68.3% of values lying within one standard deviation — meaning only 31.7% of readings exceed this level, implying a 68.3% probability of mean reversion. A Z-Score of 2.0 corresponds to 95.4%, and 3.0 to 99.7%:
calcRevProb(float z) =>
float absZ = math.abs(z)
absZ >= 3.0 ? 99.7 : absZ >= 2.5 ? 98.8 : absZ >= 2.0 ? 95.4 : absZ >= 1.5 ? 86.6 : absZ >= 1.0 ? 68.3 : absZ >= 0.5 ? 38.3 : 0.0
This probability is displayed in the dashboard alongside the live Z-Score value, giving the trader both the raw statistical reading and its corresponding reversal likelihood.
3. Composite Z-Score and Zone Classification
The three individual Z-Scores are combined into a composite score using configurable weights for each dimension. The composite is then classified into a zone: EXTREME (above the configurable extreme threshold), ELEVATED, NEUTRAL, or the opposing directional equivalents. Zone classification determines the dashboard color coding and alert triggers:
composite = (priceZ * wPrice + changeZ * wChange + volumeZ * wVolume) / totalWeight
4. Divergence and Hidden Divergence Detection
Deviation Lens monitors for two divergence conditions. Standard divergence occurs when the Z-Score direction disagrees with the price direction — price makes a higher high but the Z-Score makes a lower high (bearish divergence), or price makes a lower low but the Z-Score makes a higher low (bullish divergence). Hidden divergence occurs when the Z-Score makes an extreme move while price action is relatively contained — a potential continuation pattern. Divergence events are labeled directly on the chart with bold, clearly sized labels:
bullDiv = close > close and priceZ < priceZ // Price up, Z down = bull div
bearDiv = close < close and priceZ > priceZ // Price down, Z up = bear div
Labels: BULL DIV, BEAR DIV (size.small), H.BULL, H.BEAR (size.tiny for hidden divergence).
5. Multi-Dimensional Dashboard
The institutional dashboard presents all three Z-Scores, the composite Z-Score, current zone classification, reversal probability, and divergence status simultaneously. The layout is designed so the most actionable information — Zone and Rev. Probability — is displayed at the largest text size, with supporting metrics at smaller sizes.
Features
Three independent Z-Scores: Price level, price change (momentum), and volume — each computed on its own rolling mean and standard deviation
Configurable Z-Score weights: The composite score uses adjustable per-dimension weights allowing emphasis on price, momentum, or volume depending on trading context
Live reversal probability: Probability percentage mapped directly from the Z-Score using normal distribution properties (68.3% at 1σ through 99.7% at 3σ)
Zone classification: Composite Z-Score classified as Extreme, Elevated, or Neutral in both directions with color-coded dashboard display
Divergence labels (BULL DIV / BEAR DIV): Z-Score vs price direction disagreement labeled on-chart at size.small
Hidden divergence labels (H.BULL / H.BEAR): Z-Score extreme with contained price action labeled at size.tiny
Configurable extreme and elevated thresholds: Both Z-Score thresholds independently adjustable
Institutional dashboard (top right): 14-row table with Price Z, Change Z, Volume Z, Composite Z, Zone, Reversal Probability, and divergence status
Adaptive thresholds: All calculations normalize to the rolling lookback period, adapting to current instrument and timeframe volatility
Alerts: Separate alertconditions for extreme bull and extreme bear composite Z-Score readings
Input Parameters
Z-Score Settings:
Z-Score Length: Rolling window for all three Z-Score calculations (default: 20)
Extreme Threshold: Z-Score magnitude classified as Extreme zone (default: 2.0)
Elevated Threshold: Z-Score magnitude classified as Elevated zone (default: 1.0)
Dimension Weights:
Price Weight: Relative weight of the price Z-Score in composite (default: 1.0)
Change Weight: Relative weight of the momentum Z-Score in composite (default: 1.0)
Volume Weight: Relative weight of the volume Z-Score in composite (default: 0.5)
Divergence:
Divergence Lookback: Bars back for divergence comparison (default: 5)
Show Divergence Labels toggle
Display:
Show Dashboard toggle
Bull and Bear color inputs
How to Use This Indicator
Step 1: Read the Composite Zone
The Zone row in the dashboard shows the current composite Z-Score classification. EXTREME readings at the top of the scale indicate the highest statistical probability of mean reversion. NEUTRAL readings indicate current conditions are close to the mean and have low statistical directional edge from this tool alone.
Step 2: Check Reversal Probability
The Rev. Probability row translates the Z-Score magnitude directly into a percentage. A reading above 95% means the current composite Z-Score is in the outer 5% of its historical distribution — a statistical extreme that has preceded mean reversion 95% of the time in the measured period.
Step 3: Assess Each Dimension Independently
The three individual Z-Score rows reveal which dimension is driving the composite. A high composite driven entirely by volume Z-Score is a different setup than one driven by price Z-Score. Understanding which dimension is extreme helps filter entries: a price Z-Score extreme without supporting momentum or volume Z-Score extremes may be a lower-conviction reading.
Step 4: React to Divergence Labels
BULL DIV and BEAR DIV labels appear when Z-Score momentum diverges from price direction. These signal that the statistical driver of a move is weakening even as price continues. H.BULL and H.BEAR hidden divergence labels flag potential continuation setups where Z-Score is extreme but price is not.
Step 5: Combine with Structural Context
Deviation Lens produces the highest value when its extreme readings coincide with a structural confluence point — an order block, session low, or structure level. A 99.7% reversal probability at a tested support zone is a higher-conviction setup than the same reading in open air.
Indicator Limitations
All Z-Scores are computed relative to the rolling lookback window. The lookback defines what "normal" means. A very short lookback will produce extreme readings frequently; a very long lookback will rarely reach the extreme threshold. Calibration to the instrument and timeframe is required
The reversal probability percentages are derived from the normal distribution assumption. Price change and volume distributions are not perfectly normal — they exhibit fat tails and skew. The probabilities are approximations, not precise statistical guarantees
The composite Z-Score uses equal weights by default. Changing dimension weights significantly alters which market conditions produce extreme readings. Weight adjustments should be based on the specific instrument's characteristics
Divergence detection uses a simple lookback comparison, not a peak-detection algorithm. In choppy markets, divergence labels may appear frequently without providing actionable signals
Originality Statement
Deviation Lens is original in its simultaneous, weighted multi-dimensional Z-Score framework that maps composite statistical extremity directly to a reversal probability percentage. This indicator is published because:
Applying Z-Score analysis to three independent market dimensions simultaneously — price level, momentum (close-to-close change), and volume — rather than a single oscillator provides a richer statistical picture of current market extremity than any single-dimension Z-Score tool
The direct mapping of Z-Score magnitude to reversal probability percentages using normal distribution properties gives traders an immediately interpretable statistic rather than a raw number requiring subjective interpretation
The composite weighted Z-Score system, where each dimension's contribution to the overall reading is configurable, allows the indicator to be tuned toward price-mean-reversion strategies, momentum exhaustion strategies, or volume anomaly detection depending on the trader's methodology
The combined detection of standard divergence and hidden divergence between the Z-Score and price direction provides trend continuation and reversal signals from the same framework
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Z-Score readings and reversal probability percentages are statistical tools based on historical distributions and do not guarantee any future price behavior. The normal distribution assumption applied to price and volume data is an approximation. Always use proper risk management. The author is not responsible for any trading losses resulting from the use of this indicator.
-Made with passion by jackofalltrades
Indicator

Displacement Forge [JOAT]Displacement Forge
Introduction
Displacement Forge is an open-source order block detection engine built on Z-Score impulse analysis. It identifies statistically significant price displacements — moves that exceed a configurable standard deviation threshold relative to recent price change history — and marks the candle immediately preceding each displacement as an Order Block Zone. Order blocks represent the price ranges from which institutional order flow originates. Price regularly returns to these zones to fill remaining orders, and Displacement Forge identifies and tracks each one, monitors for zone reactions, and records cumulative rejection statistics.
The problem order block analysis solves is entry precision. A trend bias tells you direction. An order block tells you at what price the institutions that created that trend loaded their positions. Returning to those prices to enter alongside institutional flow — rather than chasing moves already in progress — is the conceptual foundation Displacement Forge is built on. The Z-Score gate ensures only statistically significant displacements qualify, filtering out small impulses caused by normal market noise.
Core Concepts
1. Z-Score Displacement Detection
Rather than using fixed ATR multiples to define a "significant" move, Displacement Forge computes the Z-Score of each bar's price change relative to the rolling distribution of recent price changes. The Z-Score measures how many standard deviations the current move is from the recent mean:
priceChg = close - close
avgChg = ta.sma(priceChg, zscoreLen)
stdChg = ta.stdev(priceChg, zscoreLen)
zscore = stdChg > 0 ? (priceChg - avgChg) / stdChg : 0.0
A positive Z-Score above the threshold with a bullish candle close and a higher close than recent highs — filtered by an EMA and VWAP trend context — constitutes a bullish displacement impulse. A negative Z-Score below the negative threshold with a bearish close and lower-than-recent lows in the opposing trend context constitutes a bearish displacement impulse.
2. Order Block Zone Identification
When a displacement impulse is detected, the indicator looks backward through the impulse lookback window for the last candle in the opposite direction — the candle just before the institutional move began. That candle's high and low define the order block zone. This captures the price range where institutional orders were being placed before the displacement candle consumed available liquidity:
if bullImpulse
for i = 1 to impulseLook
if close < open // Last bearish candle before the impulse
obLow := low
obHigh := high
break
Each zone is drawn as a box on the chart using the pre-impulse candle's range. Bull order blocks are drawn with a bullish tint (price expected to react bullishly when revisited). Bear order blocks with a bearish tint.
3. EMA and VWAP Trend Filter
Two independent trend filters gate displacement qualification. The EMA filter (200-period by default, configurable) requires bull displacements to occur above the EMA and bear displacements below it. The VWAP filter adds an intraday fair-value gate — bull displacements require price to be above the current VWAP, bear displacements require price to be below. Both filters can be independently enabled or disabled:
bullImpulse = zscore > threshold and close > open
and close > ta.highest(close, impulseLook)
and (not useEma or close > ema200)
and (not useVwap or close > ta.vwap)
4. Zone Reaction Detection and Rejection Counting
Active order block zones are continuously monitored for price reactions. A bullish reaction occurs when the candle low touches or enters the bull zone range with a bullish close. A bearish reaction occurs when the high touches or enters the bear zone range with a bearish close. Each confirmed reaction increments the independent bull and bear rejection counters displayed in the dashboard:
if ob.isBull and low <= ob.top and low >= ob.bottom and close > open
bullReactionDetected := true
totalBullRejections += 1
5. Zone Lifespan and Active Zone Management
Each zone carries an age counter that increments bar by bar. Zones exceeding the maximum age (configurable) are automatically removed as inactive. The active zone count and total tested zone count are tracked and displayed in the dashboard, giving a running picture of how many zones are currently relevant versus how many have been tested and absorbed.
Features
Z-Score impulse gate: Displacement qualification based on standard deviations from the rolling price-change distribution, not arbitrary fixed thresholds
Order block zone boxes: Pre-impulse candle ranges drawn as colored boxes on the chart for both bull and bear impulses
EMA trend filter: Configurable EMA length gates displacement direction relative to long-term trend
VWAP trend filter: Intraday VWAP provides a fair-value gate alongside the EMA for dual confirmation
Zone reaction monitoring: Active zones continuously checked for price reactions with independent bull and bear rejection counters
Zone age management: Configurable maximum zone age with automatic removal of expired zones
Active and tested zone counts: Dashboard tracks how many zones are live versus how many have been tested
Bull and bear rejection totals: Cumulative counts of all confirmed zone reactions by direction
Displacement markers: Labeled arrows at each confirmed displacement bar (BULL DISP, BEAR DISP) with size and style differentiation
Divergence detection: Z-Score divergence against price direction labeled (BULL DIV, BEAR DIV) and hidden divergence (H.BULL, H.BEAR)
Institutional dashboard (top right): 13-row table with Z-Score, displacement state, OB reactions, active zone count, tested zone count, EMA and VWAP filter status
Fully configurable: Z-Score length and threshold, impulse lookback, EMA length, VWAP toggle, zone max age, and zone visibility independently adjustable
Alerts: Separate alertconditions for bullish and bearish displacement impulses
Input Parameters
Displacement Detection:
Z-Score Length: Rolling window for mean and standard deviation calculation (default: 20)
Z-Score Threshold: Standard deviation threshold for displacement qualification (default: 1.5)
Impulse Lookback: Bars back to search for the pre-impulse order block candle (default: 5)
Trend Filters:
EMA Length: Trend EMA period (default: 200)
Use EMA Filter toggle (default: enabled)
Use VWAP Filter toggle (default: enabled)
Zone Management:
Max Zone Age (Bars): Maximum bar lifespan of active zones before automatic removal (default: 100)
Show OB Zones toggle
Display:
Show Dashboard toggle
Show Divergence Labels toggle
Bullish and Bearish color inputs
How to Use This Indicator
Step 1: Identify the Current Z-Score and Displacement State
The dashboard shows the live Z-Score value and displacement state (BULL IMPULSE, BEAR IMPULSE, or NEUTRAL). Use the Z-Score value as a real-time gauge of how statistically extreme the current price move is relative to recent history.
Step 2: Locate Active Order Block Zones
After any displacement, a colored box marks the pre-impulse candle range. These zones are the areas where institutional orders were accumulated before the move. The dashboard's Active Zones row shows how many live zones are currently on the chart.
Step 3: Wait for Price to Return to a Zone
When price retraces after a displacement and enters an active zone, watch for a reaction candle. A bullish close from within a bull zone or a bearish close from within a bear zone constitutes a zone reaction and increments the dashboard's rejection counter.
Step 4: Apply EMA and VWAP Context
The EMA filter status (ABOVE/BELOW) and VWAP filter status in the dashboard confirm whether the trend context supports the zone direction. An active bull zone with price above both the EMA and VWAP provides a higher-context long reaction than the same zone in a downtrend.
Step 5: Observe Divergence Labels
BULL DIV and BEAR DIV labels appear when the Z-Score diverges from price direction — Z-Score momentum and price momentum disagree. H.BULL and H.BEAR mark hidden divergence. These are secondary signals that may precede displacement reversals.
Indicator Limitations
The Z-Score is computed relative to the rolling price-change distribution of the configured lookback period. During regime changes or low-liquidity periods, the distribution can shift and cause the threshold to misfire
Order block identification looks backward from the displacement bar. The pre-impulse candle selection is algorithmic — it finds the last opposite-direction candle within the lookback. In some impulse structures this may not match the manually identified order block
Zone reaction detection requires the candle to touch the zone range in the same bar that a directional close occurs. Multi-bar zone entry sequences are not separately tracked
The VWAP calculation resets at daily boundaries. On instruments that trade across midnight or on continuous futures contracts, the VWAP reset behavior may differ from expectations
This indicator identifies order block zones and reactions. It does not generate trade entry signals, and zone reactions do not guarantee price continuation from the zone
Originality Statement
Displacement Forge is original in its application of Z-Score analysis to price change distribution as the gate for order block qualification, combined with a dual trend filter and automatic zone reaction monitoring with cumulative statistics. This indicator is published because:
Using the rolling Z-Score of bar-by-bar price changes — rather than raw ATR multiples — to define what constitutes a statistically significant displacement provides an adaptive, distribution-aware threshold that adjusts to current volatility rather than using fixed values
The pre-impulse candle lookback logic that identifies the order block as the last opposite-direction candle before the displacement provides a specific, repeatable rule for zone placement that eliminates the ambiguity of manual order block selection
The dual trend filter combining a configurable EMA with VWAP — both independently togglable — provides layered directional context that single-MA systems do not offer
Tracking cumulative bull and bear rejection counts alongside active and tested zone counts provides ongoing statistical feedback on how the order block zones are performing across the chart history
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Order block zones are identified using statistical and structural criteria but do not guarantee any particular price reaction when revisited. Z-Score thresholds are parameters that require adjustment to match specific instruments and timeframes. Past zone reactions do not guarantee future reactions. Always use proper risk management. The author is not responsible for any trading losses resulting from the use of this indicator.
-Made with passion by jackofalltrades
Indicator

Liquidity Fracture [JOAT]Liquidity Fracture
Introduction
Liquidity Fracture is an open-source stop-hunt and liquidity sweep detection engine that identifies, classifies, and visualizes four distinct types of liquidity events in real time. The four types are: Swing Cluster Zones where retail stop orders accumulate, Wick Rejection Traps where engineered wick candles are designed to trigger stops, Sweep Events where price spikes through a level and recovers inside, and Volume Reversal Zones where institutional footprints appear as high-volume directional rejections.
The problem liquidity analysis solves is that the most reliable entry locations are not at obvious support and resistance levels — they are just beyond them, at the price points where the greatest concentration of stop-loss orders sit. When institutional order flow needs to fill large positions, it engineers moves into those stop clusters to provide the liquidity required. Liquidity Fracture maps those clusters, labels the sweep events when they occur, and records volume-backed reversal zones where the institutional absorption is visible in the data.
Core Concepts
1. Four Zone Types and Their Rationale
Each zone type targets a different category of liquidity event:
Swing Cluster Zones mark recent pivot highs and lows — the locations where the majority of retail stop-loss orders are placed. Price regularly engineers moves into these clusters to trigger stops before reversing. These zones are drawn as boxes above pivot highs (sell-side liquidity above) and below pivot lows (buy-side liquidity below).
Wick Rejection Traps identify candles where the wick-to-body ratio exceeds a configurable threshold. A candle with a dominant upper wick closing near its lows is an engineered candle designed to trigger buy stops above the high before rejecting. The wick ratio determines whether a candle qualifies as a trap:
wickUp = high - math.max(open, close)
bodySize = math.abs(close - open)
isWickTrap = wickUp / (high - low) > wickThreshold
Sweep Events capture the core liquidity hunt pattern: price wicks through a tracked zone level and closes back inside. The sweep label fires at the closing bar of the event with a styled label indicating the direction (SWEEP up or down).
Volume Reversal Zones identify bars where volume exceeds a configurable multiple of the 20-bar average volume, price reversal is confirmed by a close in the opposite half of the candle, and the move represents a statistically significant displacement. These are the bars where institutional absorption of the sweep is most likely visible.
2. Zone Distance and Deduplication
To prevent the chart from becoming cluttered with overlapping zones at the same price level, a minimum zone distance filter measured in ATR multiples prevents new zones from being drawn within that distance of an existing zone of the same type:
minDist = atr * minZoneDist
// New zone only drawn if > minDist from any existing zone
The maximum zones per type setting caps how many of each zone type can exist simultaneously. When the cap is reached, the oldest zone is automatically removed as new ones are added.
3. Heatmap Intensity
Each zone carries a heat intensity value based on how many times price has revisited it without sweeping through. Zones that price has respected multiple times increase in visual intensity — a darker, more opaque zone represents a higher-tested liquidity cluster that has proved significant. This provides immediate visual ranking of zone importance without requiring the trader to manually assess each zone.
4. Sweep Event Detection and Labeling
A sweep is detected when price penetrates a zone's boundary and closes back inside during the same bar. The sweep label appears directly at the sweep bar using styled labels (SWEEP) with directional styling — label pointing up for bullish sweep (price wicked below a low zone and closed above it), label pointing down for bearish sweep (price wicked above a high zone and closed below it):
bullSweep = low < zoneBottom and close > zoneBottom
bearSweep = high > zoneTop and close < zoneTop
5. Zone Type Labels
Each box drawn on the chart receives a text label in its upper corner identifying its zone type: SWING HI, SWING LO, WICK TRAP, or VOL REV. This allows traders to immediately understand what category of liquidity event they are looking at without needing to remember color assignments.
Features
Four liquidity zone types: Swing Cluster Zones, Wick Rejection Traps, Sweep Events, and Volume Reversal Zones — each independently togglable
Styled sweep labels: SWEEP labels with directional pointing arrows at the exact bar where the wick-and-close confirmation occurs
Zone type text labels: Every box labeled with its zone type (SWING HI, SWING LO, WICK TRAP, VOL REV) in the upper corner
Heatmap intensity: Zone color opacity increases with each price revisit, visually ranking zone significance
ATR-based zone distance filter: Minimum ATR distance between zones of the same type prevents overlapping or duplicate zones
Volume spike detection: Configurable volume multiplier threshold for Volume Reversal Zone qualification
Wick ratio threshold: Configurable wick-to-candle-range fraction for Wick Rejection Trap qualification
Maximum zones per type: Cap on simultaneous zones per category with automatic oldest-zone removal
Zone base transparency: Configurable transparency for all zone fills simultaneously
Institutional dashboard (top right): Sweep count, active zone counts by type, ATR, and volume ratio
Fully configurable colors: Each zone type has its own independent color input
Sweep alerts: Separate alertconditions for bullish and bearish sweep events
Input Parameters
Detection:
Swing Lookback: Left/right pivot bars for swing zone detection (default: 20)
Swing Threshold %: Minimum price move % for swing qualification (default: 2.0)
Volume Spike Multiplier: Multiple of average volume required for Volume Reversal Zone (default: 2.0)
Wick Ratio Threshold: Wick-to-range fraction for Wick Trap qualification (default: 0.6)
ATR Length: ATR period for buffer and distance calculations (default: 14)
ATR Buffer Multiplier: Zone size extension as ATR multiple (default: 0.5)
Max Zones Per Type: Maximum simultaneous zones of each type (default: 5)
Min Zone Distance (ATR): Minimum ATR distance between same-type zones (default: 2.0)
Display:
Individual zone type toggles: Swing Cluster Zones, Wick Rejection Traps, Sweep Events, Volume Reversal Zones
Heatmap Intensity toggle
Show Zone Labels toggle
Show Dashboard toggle
Zone Base Transparency: 30-92 (default: 75)
How to Use This Indicator
Step 1: Identify Active Liquidity Clusters
Swing Cluster Zones (red above, green below) mark where the nearest stop clusters sit. The most saturated (darkest) zones have been tested most frequently and represent the highest-concentration liquidity pools. These are the primary targets for engineered price moves.
Step 2: Watch for Wick Trap Formations
Wick Rejection Trap zones appear when a candle forms with a disproportionately large wick. These candles are the mechanism by which stops are triggered — the wick penetrates the stop cluster while the close retreats. A Wick Trap zone followed by a Sweep event on the same level is a high-probability combination.
Step 3: React to Sweep Labels
When a SWEEP label appears, a stop cluster has been penetrated and price has recovered inside in a single bar. This is the liquidity hunt completion pattern. A bullish sweep (below a low zone, close above) suggests buy-side liquidity was provided and a reversal is possible. Confirm with volume.
Step 4: Use Volume Reversal Zones as Confirmation
Volume Reversal Zones mark where institutional absorption is most likely visible. A sweep into a cluster followed by a Volume Reversal Zone on the recovery bar provides the highest-confidence combination this indicator can produce.
Step 5: Assess Zone Freshness
Freshly created zones (lighter color) have not been tested. Heavily revisited zones (darker) have withstood multiple price touches. Focus attention on the darkest zones — they represent the most significant concentration of resting orders.
Indicator Limitations
Swing zone detection uses pivot logic with a right-bar offset. Zones are confirmed several bars after the actual pivot, creating a slight lag in zone creation
The volume spike filter relies on exchange-reported volume. On synthetic instruments, indices, or assets with thin or unreliable volume reporting, Volume Reversal Zones will not be accurate
Zone distance filtering prevents duplicate zones, but in volatile, fast-moving markets, zones can form rapidly and crowd the chart before the maximum zone cap removes old ones
Sweep detection requires the close to recover inside the zone on the same bar as the wick penetration. Multi-bar sweeps (where recovery takes multiple bars) are not detected as sweep events — the level simply becomes the new zone boundary
This indicator identifies liquidity events. It does not provide directional entry signals or determine the probability that a reversal after a sweep will be sustained
Originality Statement
Liquidity Fracture is original in its simultaneous, unified detection and visualization of four distinct liquidity event types within a single indicator with a unified heatmap intensity system. This indicator is published because:
The classification of four independent liquidity event types (swing cluster, wick trap, sweep, volume reversal) — each with its own detection logic, independent toggle, and color — into a single, unified zone management system is uncommon in published open-source Pine Script
The heatmap intensity system that increases zone visual weight with each price revisit provides automatic, data-driven zone importance ranking without any manual assessment
The zone deduplication system using ATR-based minimum distance prevents the false signal accumulation that occurs in naive pivot-based zone indicators that draw every pivot regardless of proximity
The zone type labeling system (SWING HI, SWING LO, WICK TRAP, VOL REV) inside each box allows instant identification of event type without relying solely on color memory
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Liquidity zone detection and sweep signals are based on historical price and volume patterns. The identification of a sweep event does not guarantee a reversal, and zone levels can be violated without producing the expected reaction. Always use proper risk management. The author is not responsible for any trading losses resulting from the use of this indicator.
-Made with passion by jackofalltrades
Indicator

Market Phase Detector [JOAT]Market Phase Detector
Introduction
Market Phase Detector is an open-source market structure classification engine that continuously identifies whether price is operating in a Bullish Trend, Bearish Trend, or Range state. The classification uses three independent inputs that must align simultaneously before a regime is confirmed, making the output robust against single-factor noise and false positives that plague simpler trend detectors.
The problem Market Phase Detector solves is context. Trend-following entries during range conditions produce whipsaws. Mean-reversion entries during strong trending moves produce losses against the dominant flow. Knowing the regime before interpreting any other signal improves the relevance of every decision made from it. Market Phase Detector makes that determination automatically, updates it bar by bar, and visualizes both the current regime and every structural event that contributed to it — including labeled BOS and CHoCH events with horizontal level lines, live swing extension lines at the right edge, and an institutional-grade dashboard.
Core Concepts
1. Swing Detection and Pivot Tracking
Price structure is derived from pivot highs and lows confirmed using ta.pivothigh() and ta.pivotlow() with a configurable symmetric lookback. The lookback controls sensitivity — a value of 5 requires 5 bars on each side of the pivot to confirm it, producing only the most structurally significant swings. Each confirmed pivot updates the tracked level and resets its broken flag to allow new break detection on the next cycle:
pivHi = ta.pivothigh(high, swingLen, swingLen)
pivLo = ta.pivotlow(low, swingLen, swingLen)
if not na(pivHi)
topLevel := pivHi
topBroken := false
2. Break of Structure vs Change of Character
Two structural event types are distinguished and tracked independently. A Break of Structure (BOS) occurs when price closes through the previous swing extreme in the same direction as the current structural bias — confirming continuation. A Change of Character (CHoCH) occurs when price closes through the previous swing extreme against the current structural bias — signaling a potential regime flip:
bosBull = bullBreak and structureBias == 1
chochBull = bullBreak and structureBias != 1
Every event is labeled directly on the chart with a horizontal line at the break level and a text label (BOS +, BOS -, CHoCH +, CHoCH -). Running counts of each type are tracked and displayed in the dashboard.
3. Three-Factor Regime Gate
The regime classification evaluates all three inputs simultaneously before assigning a state. Structure bias is set by BOS and CHoCH events. The volatility gate compares current ATR to a moving average of ATR multiplied by a contraction threshold — when ATR falls below this level the market is classified as compressed and the regime defaults to Range regardless of structure or momentum. Momentum uses a smoothed rate-of-change that must confirm the structural direction:
if isLowVol
regime := 0 // Range — volatility gate overrides everything
else if strBias == 1 and roc > 0
regime := 1 // Bullish
else if strBias == -1 and roc < 0
regime := -1 // Bearish
else
regime := 0 // Inconclusive — range
A confidence score (1-3) counts how many of the three factors currently agree and is displayed in the dashboard, allowing the trader to distinguish a fully confirmed 3/3 regime from a weaker 2/3 reading.
4. Swing Level Extension Lines
The current unbroken swing high and swing low are extended as dotted horizontal lines to the right edge of the chart with price labels. These serve as the nearest structural reference levels — the next points where a BOS or CHoCH could occur. They are deleted and redrawn each bar using barstate.islast so they remain current without consuming the indicator's line budget:
if barstate.islast and showSwingExt
line.delete(swingHiLine)
swingHiLine := line.new(topBar, topLevel, bar_index + 4, topLevel,
color=color.new(#E65100, 45), style=line.style_dotted, width=2)
5. Regime Background Shading
The chart background is tinted according to the current regime — faint teal for Bullish, faint orange for Bearish, neutral gray for Range. This gives immediate context at a glance without adding visual noise to the price action.
Features
Three-state regime output: Bullish, Bearish, and Range states derived from structure, volatility, and momentum alignment
BOS and CHoCH event labels: Every structural break labeled on-chart with event type, direction, and horizontal level line
Independent BOS and CHoCH counters: Running totals of each structural event type in the dashboard
Swing level extension lines: Dotted right-edge lines at the current unbroken swing high and low with price labels
ATR-based volatility gate: Low-volatility contraction forces a Range classification regardless of structure or momentum
Smoothed momentum confirmation: Rate-of-change must align with structure before a trending regime is confirmed
Confidence scoring (1/3 to 3/3): Quantifies how many of the three classification factors are currently aligned
Regime background shading: Chart background tint reflects the current regime in real time
Institutional dashboard (top right): 15-row table with regime state, confidence, last break direction and age, BOS and CHoCH counts, swing levels, and ATR
Fully configurable colors: Bullish, bearish, and ranging tints plus structure line colors are independently adjustable
All signals confirmed bar only: No repainting — all structural events fire on barstate.isconfirmed
Input Parameters
Structure Detection:
Swing Lookback: Left/right bars required for pivot confirmation (default: 5)
ATR Period: ATR calculation length (default: 14)
Regime Classification:
Volatility MA Length: MA length for ATR comparison (default: 20)
Range Contraction Multiplier: ATR fraction below which the market is classified as ranging (default: 0.7)
Momentum Lookback: Rate-of-change lookback and EMA smoothing period (default: 10)
Display:
Regime Background Shading toggle
Show Dashboard toggle
Show Structure Lines toggle
Show Swing Level Extensions toggle
How to Use This Indicator
Step 1: Read the Current Regime
Check the REGIME row in the dashboard. BULLISH, BEARISH, or RANGE appears in its corresponding color. This is the primary output. Use it to establish directional bias before consulting any other signal source.
Step 2: Check Confidence Score
The Confidence row shows how many of the three inputs align (e.g., 2/3). A 3/3 reading means structure, volatility, and momentum all agree. A 2/3 reading means one factor is diverging. Weight directional decisions higher during full 3/3 alignment.
Step 3: Monitor CHoCH Events
Each CHoCH label marks a structural break against the current bias — a warning that the regime may be shifting. When a CHoCH appears, watch whether subsequent bars confirm a new opposing BOS or whether the previous regime resumes.
Step 4: Use Swing Extension Lines as Forward Reference
The dotted right-edge lines mark the current unbroken swing levels — the nearest structural break zones. Knowing how close price is to these levels frames where the next BOS or CHoCH could occur.
Step 5: Apply Regime as a Filter
Market Phase Detector is designed as a context layer, not a standalone signal generator. Apply the regime output as a filter to your existing tools: only take long signals when the regime is Bullish, only take short signals when Bearish, and step aside or apply mean-reversion logic when Range is active.
Indicator Limitations
Pivot detection confirms swingLen bars after the pivot forms, creating a natural offset between the candle where the swing occurred and when it is labeled. This is intentional non-repainting behavior
The volatility gate may temporarily classify a new trend as Range immediately after a volatility expansion if ATR has not yet risen above the threshold. This resolves within a few bars as ATR normalizes
In slow, grinding markets, momentum may repeatedly lag structure, resulting in extended Range readings during mild trends
Market Phase Detector classifies current market state. It does not predict future price direction or generate entry/exit signals
Originality Statement
Market Phase Detector is original in its three-factor gate requiring independent alignment of structure, volatility, and momentum before any regime is confirmed. This indicator is published because:
The combination of CHoCH and BOS structural logic, an ATR contraction gate, and a smoothed momentum filter into a single lightweight classifier that produces a confidence score is uncommon in published open-source Pine Script v6
Distinguishing BOS from CHoCH within the same indicator — with independent event counts and labeled historical events — provides structural context that standalone trend indicators do not offer
The confidence scoring system (1-3) quantifies the strength of the current regime reading across three independent analytical dimensions, not just a single oscillator value
Swing level extension lines provide live structural reference at the right edge of the chart without requiring the user to manually draw levels or add a separate pivot indicator
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Regime classifications are based on historical price data and do not guarantee any future market behavior. All three factors can produce inaccurate readings in atypical market conditions. Always use proper risk management. The author is not responsible for any trading losses resulting from the use of this indicator.
-Made with passion by jackofalltrades
Indicator

Confluence Engine Strategy [JOAT]Confluence Engine Strategy
Overview
Confluence Engine Strategy is a fully automated Pine Script v6 strategy that combines four independent signal layers into a single numeric confluence score (0–100) before executing any trade. Entries require genuine agreement between linear regression momentum, dual EMA trend regime, ATR volatility state, and higher-timeframe bias. All exits are ATR-proportional with configurable take-profit and stop-loss multiples, plus a bar-based timeout and a trend-flip emergency exit. Commission (0.05% per side) and slippage (2 ticks) are configured for realistic backtesting.
Why Require Confluence?
Single-condition strategies (e.g., "go long when RSI crosses 50") produce entries in every conceivable market environment — ranging, trending, low-volatility, high-volatility — most of which are statistically unfavourable for that signal type. Requiring multiple independent conditions to agree simultaneously filters the entry universe down to the high-probability subset where each individual indicator is operating in its most favourable context. The Confluence Engine makes this filtering explicit and auditable through a numeric score.
Signal Layer 1 — Linear Regression Crossover
The primary entry trigger mirrors the Regression Flux Candles logic: a 21-bar linear regression of close (LR close) crossing above/below an 8-bar SMA of itself. The LR approach de-noises price before computing the crossover, significantly reducing the whipsaw rate compared to raw close-based SMA crossovers.
Signal Layer 2 — Dual EMA Trend Regime
Two exponential moving averages (fast: 21-period, slow: 55-period) define the trend regime. Long entries are only considered when the fast EMA is above the slow EMA; short entries only when fast is below slow. This prevents the LR crossover from triggering counter-trend entries in established trends — one of the most common sources of false signals in momentum strategies.
Signal Layer 3 — ATR Volatility State
The current 14-bar ATR is compared to a 50-bar ATR. Entries are only accepted when the current ATR is above a configurable fraction of the slow ATR (default 0.7). This volatility gate blocks trades during compression phases — low-volatility periods where breakouts frequently fail. The strategy only participates when directional energy is present.
Signal Layer 4 — Higher-Timeframe Bias
A higher-timeframe linear regression direction is fetched via request.security() with lookahead_off. The HTF LR close vs. HTF LR open comparison gives a single bullish/bearish vote from the higher timeframe. Long entries receive a confluence bonus when the HTF agrees; short entries receive a bonus when the HTF is bearish. This aligns trade direction with the prevailing macro bias.
Confluence Score and Threshold
Each of the four layers contributes points to the confluence score:
- LR crossover in direction: +30
- Dual EMA alignment: +25
- ATR volatility expansion: +20
- HTF bias alignment: +25
Maximum score: 100. The minimum required score to execute an entry (default 60) filters out entries where fewer than three layers agree. This threshold is adjustable — lower it for more signals, raise it for higher selectivity.
Entry Logic
Long: LR crossover up AND the accumulated confluence score >= minimum AND the signal is on a confirmed bar AND warmup has elapsed AND no position is currently open AND no cooldown bars remain.
Short: LR crossover down AND confluence >= minimum AND same guards.
A configurable cooldown period (default 5 bars) prevents re-entering the same direction immediately after an exit, avoiding overtrading in choppy conditions.
Exit Logic — Four Exit Conditions
1. ATR Take-Profit: Long exits when close >= entry + ATR × TP multiplier (default 2.0). Short exits below entry - ATR × TP.
2. ATR Stop-Loss: Long exits when close <= entry - ATR × SL multiplier (default 1.2). Short exits above entry + ATR × SL.
3. Bar Timeout: If neither TP nor SL is hit within a configurable number of bars (default 20), the trade exits at market — preventing capital from being locked in stalled trades.
4. Trend Flip Exit: If the dual EMA regime flips against the trade direction (fast EMA crosses slow EMA), the trade exits immediately — recognising that the structural basis for the entry has been invalidated.
Strategy Properties
- Initial capital: $10,000
- Order size: 10% of equity per trade (sustainable risk allocation)
- Commission: 0.05% per side (representative of major exchange fees)
- Slippage: 2 ticks (accounts for spread and execution delay)
- Currency: USD
- Pyramiding: disabled (one position at a time)
These settings are designed to produce realistic backtesting results. Risk per trade is capped well below the 5–10% equity guideline. Commission and slippage are included to prevent overstating performance.
Inputs Reference
Signal Layers
- LR Length (21) — linear regression period
- Signal SMA Length (8) — crossover trigger SMA
- Fast EMA (21) / Slow EMA (55) — trend regime definition
- ATR Length (14) / ATR Slow Length (50) / ATR Threshold (0.70)
- HTF Timeframe — higher-timeframe bias source (default "D")
Confluence & Filters
- Min Confluence Score (60) — minimum sum of layer scores required for entry
- Cooldown Bars (5) — bars to wait after exit before re-entering
- Max Bars in Trade (20) — timeout exit
Risk Management
- TP ATR Multiple (2.0) — take-profit distance in ATR units
- SL ATR Multiple (1.2) — stop-loss distance in ATR units
How to Read the Results
Apply the strategy to a liquid instrument on a 1H or 4H chart with sufficient history to generate 100+ trades. Evaluate:
- Net profit relative to max drawdown (seek ratio > 2:1)
- Win rate in context of average win vs. average loss
- Profit factor (total gross profit / total gross loss, seek > 1.3)
- Number of trades (sufficient sample size for statistical inference)
Adjust the confluence minimum score to trade off signal frequency against quality: 50 produces more trades, 75 produces fewer but higher-quality entries.
Non-Repainting Design
All entries fire on strategy.entry() within barstate.isconfirmed blocks. HTF bias uses lookahead_off. No future bar data is accessed. Historical signals do not shift position.
Limitations
- The strategy is designed as a general-purpose framework. It is not optimised for any specific instrument or session. Optimal parameters vary significantly across markets and timeframes.
- ATR-based exits are approximate. In gap markets (equities overnight, weekend gaps on crypto), the stop-loss may be exceeded significantly before the exit executes.
- Backtesting results are computed on historical data only and do not account for execution quality, broker-specific fees, or market impact. Past backtesting performance does not guarantee future live results.
- The bar timeout exit may prematurely close positions that would have eventually reached TP. This is a deliberate conservative design choice to limit capital lock-up, not a flaw.
Disclaimer
This strategy is provided for educational and informational purposes only. Backtesting results presented in the strategy tester represent historical simulation and do not guarantee any future trading outcome. Past performance is not indicative of future results. Never risk capital you cannot afford to lose. Always use proper risk management and conduct independent analysis before making any trading decisions.
Made with passion by officialjackofalltrades
Strategy

Regression Flux Candles [JOAT]Regression Flux Candles
Overview
Regression Flux Candles renders a parallel candle series on top of price using linear regression applied independently to each of the four OHLC components. The result is a noise-filtered "flux candle" — a linearised representation of current price action that removes the erratic intrabar variation of raw candles and reveals the underlying trend direction with far greater clarity. A signal line (SMA of regression close) produces crossover buy/sell signals. Pivot-anchored support/resistance zones mark structural confluence areas. A six-timeframe MTF trend table provides session bias context.
The Linear Regression Candle Concept
Standard Japanese candlesticks display the raw open, high, low, and close of each bar — capturing every tick-driven fluctuation including news spikes, stop hunts, and market-maker manipulation. Linear regression candles replace each OHLC component with the endpoint of a linear regression line fitted over the last N bars:
- LR Open = ta.linreg(open, length, 0)
- LR High = ta.linreg(high, length, 0)
- LR Low = ta.linreg(low, length, 0)
- LR Close = ta.linreg(close, length, 0)
The regression fits a straight line through the last N values of each component and returns the value of that line at the current bar. The resulting candle series is significantly smoother than raw price and acts like a weighted moving average of price structure without introducing the directional lag of traditional MAs. Bullish flux candles (LR close >= LR open) render in teal; bearish in purple.
Signal Line and Crossover Logic
A simple moving average of the LR close (default 7-bar SMA) acts as a signal line. When the LR close crosses above the signal line, a potential buy signal is generated. When it crosses below, a potential sell signal is generated. Crossovers are filtered by:
- Volume filter: Volume must exceed the 20-bar volume SMA (configurable). This ensures signals occur during genuine participation, not thin-market noise.
- RSI filter: Buy signals are blocked when RSI(14) >= 70 (overbought); sell signals are blocked when RSI(14) <= 30 (oversold). This prevents buying into extended moves and selling into oversold conditions.
- Warmup gate: All signals are suppressed until max(LR_length * 3, EMA_length + 5) bars have elapsed. This prevents the statistical noise of early LR calculations from generating false signals.
- Confirmed-bar gate: Signals only fire on barstate.isconfirmed — the final tick of a closed bar — preventing any repainting.
Trend EMA
A 200-period EMA (configurable length) is plotted as a gold line representing the macro trend bias. Position of price relative to the 200 EMA serves as a context filter that traders can apply manually: long signals above the EMA are higher quality, short signals below it are higher quality.
Pivot S/R Zones
Swing pivot highs and lows (configurable left/right bars) generate semi-transparent S/R boxes:
- Resistance zones (from pivot highs): drawn in the bear colour with 89% transparency
- Support zones (from pivot lows): drawn in the bull colour with 89% transparency
Each zone extends forward by a configurable width in bars (default 40) from the pivot bar, or can be extended infinitely to the right. A maximum of 6 zones (configurable) are maintained; older zones are deleted as new ones form.
Daily Signal Counter
The dashboard tracks how many buy and sell signals have fired on the current trading day, resetting at each new daily session (detected via ta.change(time("D"))). This provides a quick intraday reference for signal frequency — useful for understanding whether a session is particularly active or quiet.
Multi-Timeframe Trend Table
Six independently configurable timeframes are assessed using the same linear regression logic: LR close >= LR open on each HTF = bullish; below = bearish. Each cell displays BULL or BEAR in its directional colour. An alignment counter shows how many of the six timeframes agree with the current LR direction. 5+ aligned = strong directional bias (teal); 1 or fewer = strong counter-trend warning (red); middle values show gold.
Inputs Reference
Regression Engine
- LR Length (11) — lookback for all four linear regression calculations
- Signal SMA Length (7) — SMA applied to LR close for crossover signal line
- Trend EMA Length (200) — macro bias reference line
Filters & Signals
- Volume Filter on Signals — require volume > volume SMA
- Volume SMA Length (20)
- RSI Filter on Signals — block overbought/oversold crossovers
- RSI Length (14)
S/R Zones
- Pivot Left/Right Bars (15/10) — pivot detection sensitivity
- Show S/R Zones
- Extend Zones to Right — infinite extension toggle
- Zone Width (40 bars) — forward extension length when not extending to right
- Max Zones to Show (6)
MTF Dashboard
- Show MTF Table
- TF 1–6 — six configurable timeframes (default: 1, 5, 15, 60, 240, D)
Visual
- Bull / Bear Candle Color — OHLC candle colours for flux candles
- Signal Line Color — signal SMA line colour
- EMA Color — trend EMA line colour
- Show Dashboard
How to Use
1. Apply to any liquid market. Use LR length of 9–15 for intraday charts; 20–30 for swing trading.
2. Watch for flux candle colour transitions: a sustained sequence of teal candles above the signal line confirms an uptrend; purple candles below confirm a downtrend.
3. BUY labels appear below the bar when LR close crosses above the signal line with volume and RSI conditions met. SELL labels appear above the bar on crossunders.
4. Prefer signals where the flux candle direction (teal/purple) aligns with the EMA bias AND the MTF table shows 4+ timeframes in agreement.
5. S/R zones from prior pivots serve as target levels and potential reversal points — align entries near these zones for improved risk/reward.
Non-Repainting Design
All signals require barstate.isconfirmed. MTF data uses lookahead_off. LR calculations use only confirmed historical bars (offset 0 is the current bar's regression endpoint based on past data). Signal labels never move after being stamped on a closed bar.
Limitations
- Linear regression candles reduce volatility information. In sharp, impulsive markets, the flux candle series will understate the actual price range. Raw candles should be viewed alongside the indicator for context.
- Short LR lengths (< 7) make the flux candles nearly identical to raw candles; very long lengths (> 30) introduce significant lag into the signal line crossovers.
- The volume and RSI filters may suppress signals during thin trading hours on forex pairs (e.g., Asian session on EUR/USD pairs). Disabling filters during these sessions is a valid adjustment.
- S/R zones are drawn from the pivot confirmation bar, not the pivot bar itself (due to the right-bar confirmation delay). Zone left edges are placed correctly but appear N bars after the actual pivot.
Disclaimer
This indicator is for educational and informational purposes only. Linear regression candles and crossover signals are technical analysis tools and do not predict future price movement. Always use proper risk management and conduct your own analysis.
Made with passion by officialjackofalltrades
Indicator

Adaptive Fibonacci Compass [JOAT]Adaptive Fibonacci Compass
Overview
Adaptive Fibonacci Compass is a dynamic, pivot-anchored Fibonacci retracement and extension system built in Pine Script v6. It continuously detects the most recent confirmed swing pivot pair, grades the pivot's ATR-normalised strength, checks for Break of Structure or Change of Character on the swing axis, then draws a live Fibonacci grid of seven standard levels (0, 0.236, 0.382, 0.5, 0.618, 0.786, 1.0) with fill-highlighted Optimal Trade Entry zones (OTE: 0.382–0.618 and 0.618–0.786) — all rendered at barstate.islast using the delete-before-create pattern for zero ghost-drawing artifacts.
Why Adaptive Fibonacci?
Static Fibonacci tools require manual anchor selection, which introduces subjectivity and results in different traders drawing the same move differently. Adaptive Fibonacci Compass removes this ambiguity by algorithmically detecting the pivot pair that defines the most recent significant swing and anchoring the grid there automatically. The grid updates whenever a new, stronger pivot forms — keeping the Fibonacci reference aligned with the current market structure without any manual intervention.
Pivot Detection and ATR Strength Grading
Swing pivots are detected using ta.pivothigh() and ta.pivotlow() with configurable left and right bar confirmation windows (default 10/10). When a new pivot forms, its ATR-normalised strength is computed:
Strength = (pivotHigh - pivotLow) / ATR(14)
This ratio grades the swing on a universal scale independent of price level or instrument. Pivots grading above a configurable minimum strength (default 1.5 ATR) are accepted as valid Fibonacci anchors. Smaller price structures that do not meet the threshold are ignored, preventing the grid from anchoring to noise.
BOS / CHoCH Detection on Pivot Axis
Each time a new pivot pair is accepted, the engine checks whether the new swing extreme exceeds the prior swing extreme of the same type:
- BOS Up: New swing high exceeds the previous swing high — structural expansion to the upside
- BOS Down: New swing low is below the previous swing low — structural expansion to the downside
- CHoCH: A swing extreme that forms against the prevailing structure — e.g., a new swing high forming when prior context was bearish
BOS and CHoCH labels are stamped at the pivot level to provide structural context for interpreting the Fibonacci grid.
Dynamic Fibonacci Grid (7 Levels)
The grid spans from the last confirmed swing low to the last confirmed swing high (for bullish pivots) or the reverse (for bearish pivots). Seven retracement levels are drawn as horizontal lines:
- 0.0 (swing origin) — white/neutral
- 0.236 — subtle grey
- 0.382 — teal (start of OTE zone)
- 0.5 — gold (midpoint)
- 0.618 — teal (end of deep OTE zone)
- 0.786 — purple
- 1.0 (swing extreme) — white/neutral
Each level label shows both the ratio and the exact price value.
Optimal Trade Entry (OTE) Fill Zones
Two fill zones are highlighted as semi-transparent boxes between specific Fibonacci levels, representing the confluence areas where institutional entries are statistically most concentrated:
- OTE 0.382–0.618: The standard OTE zone — the area of highest probability for pullback continuation trades
- OTE 0.618–0.786: The deep OTE zone — commonly used for higher-conviction reversal entries where the move has retraced deeply into the prior swing
Both zones are rendered with directional colour (teal for bullish swings, red for bearish swings) at 80–85% transparency.
Live Pivot Tracking and Grid Refresh
On every bar, the indicator tracks whether price is forming a new potential extreme beyond the current grid's anchor. When a new confirmed pivot qualifies (passes the ATR strength threshold), the previous grid is fully deleted (all lines, labels, and boxes) and rebuilt from the new anchor points. The delete-before-create pattern at barstate.islast ensures no duplicate or orphaned drawing objects accumulate over the session.
Inputs Reference
- Pivot Left Bars (10) — left confirmation bars for swing detection
- Pivot Right Bars (10) — right confirmation bars for swing detection
- Min ATR Strength (1.5) — minimum swing size in ATR units to accept as a valid anchor
- Show Fib Grid — toggles the full Fibonacci grid
- Show OTE Zones — toggles the 0.382–0.618 and 0.618–0.786 fill zones
- Show BOS / CHoCH Labels — toggles structural labels on pivot extremes
- Show Level Labels — toggles price and ratio annotations on each Fibonacci line
- Extend Lines (bars, default 30) — how far right the grid lines extend from the current bar
- Theme: Dark, Light, Auto
How to Use
1. Apply to any liquid market on any timeframe. The indicator needs at least (PivotLeft + PivotRight) * 3 bars to warm up.
2. The gold 0.5 level and teal 0.382/0.618 lines define the primary trade management area. In a confirmed uptrend, look for price to pull back into the OTE 0.382–0.618 zone with a bullish reaction for long entries.
3. The deep OTE 0.618–0.786 zone is valid for entries only in strong, high-momentum swings where the pullback is orderly and accompanied by decreasing volume.
4. Treat the 0.0 and 1.0 levels as structural extremes. A confirmed close beyond the 1.0 level triggers a new BOS and should cause the grid to reload on the next qualifying pivot.
5. Use BOS labels to confirm that the current Fibonacci swing direction aligns with the broader structural bias from a higher timeframe.
Non-Repainting Design
Pivots are only detected once the full right-bar confirmation period has elapsed. The grid is always anchored to confirmed historical pivots. No drawing is created based on the current in-progress bar. All grid refreshes occur at barstate.islast using confirmed pivot data.
Limitations
- The indicator anchors to the most recent qualifying pivot pair. In multi-week trends with no significant retracement, the grid may anchor to a very old pivot that is no longer contextually relevant.
- The minimum ATR strength filter helps but does not eliminate all noise pivots on highly volatile instruments. Increasing the threshold on crypto assets is recommended.
- Fibonacci levels are probabilistic reference zones, not guaranteed reversal or support/resistance levels. Confluence with other structure (OBs, PDH/PDL, volume profile POC) significantly increases their reliability.
- The grid does not account for higher-timeframe Fibonacci structures. Always check alignment with HTF pivots manually.
Disclaimer
This indicator is for educational and informational purposes only. Fibonacci retracements are historical price relationships and do not predict future market behaviour with certainty. Always use proper risk management and conduct your own analysis.
Made with passion by officialjackofalltrades
Indicator

Temporal Candle Grid [JOAT]Temporal Candle Grid
Overview
Temporal Candle Grid is a multi-timeframe structural confluence indicator that automatically pairs the current chart timeframe with a logical higher timeframe (HTF), fetches the HTF's open, high, low, and close series using non-repainting request.security() calls, and renders the resulting HTF candle geometry as a precision box overlay on the lower timeframe chart. Confirmation counters, buy-side/sell-side liquidity labels, and Fair Value Gap detection operate on confirmed bars only, giving traders a clean, lag-aware view of where HTF price structure begins and ends.
Intelligent Auto-Pairing
The indicator contains a timeframe pairing table that maps the current chart to a contextually appropriate higher timeframe without any manual configuration:
- 1m chart → 15m HTF
- 5m chart → 1H HTF
- 15m chart → 4H HTF
- 1H chart → Daily HTF
- 4H chart → Weekly HTF
- Daily chart → Monthly HTF
This auto-pairing logic ensures the HTF candle shown is always meaningfully larger than the current view — avoiding the degenerate case of pairing a 5m chart with a 10m HTF, which provides almost no additional information.
Users may override the auto-pair by specifying a custom HTF via input.
Non-Repainting HTF Data
Four separate request.security() calls retrieve HTF open, high, low, and close using:
- close offset on the HTF series (current-bar data from the HTF is never used)
- barmerge.lookahead_off
This combination guarantees that the HTF values shown were already fixed before the current bar opened — making the indicator safe for signal generation and alert use without lookahead contamination.
HTF Candle Box Rendering
The HTF candle is rendered as a transparent box spanning the full high-to-low range, with an inner body box (open-to-close) rendered in the candle direction colour (teal for bullish, red for bearish). At each HTF boundary (detected via ta.change() on the HTF open), the previous candle's boxes are finalised and new boxes begin drawing. This creates a visual grid of HTF candles overlaid on the lower timeframe, making the internal structure of each HTF bar immediately visible.
Confirmation Counter for HTF Range Breaks
Rather than signalling the moment price crosses an HTF boundary, the engine counts consecutive closes above the HTF high (for bullish breaks) or below the HTF low (for bearish breaks). A break is only confirmed after the count reaches a configurable threshold (default 2 consecutive closes). This eliminates wick-driven false breaks that resolve within the same HTF session.
Buy-Side / Sell-Side Liquidity Labels (BSL / SSL)
When a confirmed HTF high break occurs, the BSL (buy-side liquidity) level is marked with an upward label at the HTF high. When a confirmed HTF low break occurs, an SSL (sell-side liquidity) label is stamped at the HTF low. These labels persist and serve as reference levels for future pullbacks — common targets in institutional liquidity analysis.
Fair Value Gap Detection
Running on the current timeframe, the FVG engine identifies three-bar price gaps:
- Bullish FVG: Current bar's low is above the high from two bars ago — a gap in downside coverage indicating aggressive buying
- Bearish FVG: Current bar's high is below the low from two bars ago — a gap in upside coverage indicating aggressive selling
FVG boxes are drawn spanning the gap range and extend forward for 30 bars, rendering as reference zones for expected price return.
HTF Candle Projection
On the last bar (barstate.islast), the current in-progress HTF candle is projected forward as a semi-transparent dashed box, giving traders a visual reference for the current HTF session's range as it develops in real time.
Dashboard
A compact table at the bottom right displays:
- Current chart TF and detected HTF
- HTF candle direction (BULL / BEAR)
- Current break confirmation count
- Number of active BSL / SSL levels
- FVG status (open / filled) for the most recent gap
Inputs Reference
- Custom HTF Override — leave blank for auto-pair, enter a TF string (e.g., "60") to override
- Confirmation Bars Required (2) — consecutive closes beyond HTF range before break is confirmed
- Show HTF Candle Boxes — toggles the HTF overlay
- Show BSL / SSL Labels — toggles liquidity sweep labels
- Show FVG Boxes — toggles fair value gap boxes
- FVG Lookback (50) — how many bars back to scan for active FVGs
- Max BSL / SSL Labels (10) — prevents label accumulation over long sessions
- Theme: Dark, Light, Auto
How to Use
1. Apply on a 5m, 15m, or 1H chart. The indicator auto-detects the appropriate HTF.
2. The HTF candle boxes show the full range of each higher-timeframe session. Price tends to respect the HTF open, high, and low as decision levels.
3. Wait for the confirmation counter to reach the threshold before treating a HTF range break as confirmed.
4. BSL labels above prior HTF highs and SSL labels below prior HTF lows indicate pools of resting orders — common institutional sweep targets.
5. FVG boxes within the current HTF candle body often act as intra-session return targets.
Non-Repainting Design
All HTF data uses close with lookahead_off. Break signals require barstate.isconfirmed. FVG detection is based entirely on confirmed historical bars. The projection box at barstate.islast is explicitly marked as in-progress and does not generate signals.
Limitations
- Auto-pairing is based on standard timeframe relationships. Non-standard chart intervals (e.g., 3m, 7m) default to the nearest logical pair.
- The confirmation counter approach adds 1–2 bars of lag to break signals. This is intentional and necessary for non-repainting accuracy.
- On very fast-moving instruments, HTF candle boxes may be violated frequently, limiting their utility as structural references.
- FVG relevance degrades significantly on very high timeframes (Daily+) where gaps are rare and may take weeks to fill.
Disclaimer
This indicator is for educational and informational purposes only. Multi-timeframe structure analysis describes historical price behaviour and does not guarantee any specific future market outcome. Conduct your own analysis and use proper risk management at all times.
Made with passion by officialjackofalltrades
Indicator

Adaptive Friction Filter (AFF) [QuantAlgo]🟢 Overview
The Adaptive Friction Filter (AFF) identifies trending market conditions by applying a physics-inspired friction model to price movement. Rather than smoothing price through fixed averaging, it introduces a dynamic noise threshold derived from recent market volatility, which means price must generate enough force to overcome this threshold before the filter moves at all. Once breached, the filter closes the gap at a configurable rate, producing a step-like trend line that holds steady through noise and responds decisively to genuine directional moves. This allows traders to distinguish between meaningful trend continuation and low-conviction chop across any instrument or timeframe.
🟢 How It Works
The AFF's core methodology is built around a two-stage mechanism: a volatility-derived friction threshold that gates filter movement, and a catch-up scalar that governs how much of the gap the filter closes on each bar once that threshold is exceeded.
First, the friction threshold is computed as the simple moving average of absolute bar-to-bar price changes over the configured lookback window, scaled by the friction coefficient. This makes the threshold inherently self-adjusting; it widens during volatile conditions and contracts during quiet ones, without requiring any manual recalibration:
friction = ta.sma(math.abs(src - src ), lookback) * friction_mult
Next, the raw displacement between current price and the filter's last position is evaluated as force. The filter only advances if this force exceeds the friction threshold. When it does, the filter moves toward price by a fraction of the gap governed by the catch-up scalar, rather than closing the full distance immediately, producing a controlled and progressive response:
force = src - aff_line
aff_line := math.abs(force) > friction ? aff_line + force * catchup_scalar : aff_line
Trend direction is then resolved by comparing the current filter value to its prior bar value. The direction state persists when the filter is flat, so no transition is registered on bars where the filter does not move:
trend_dir := aff_line > aff_line ? 1 : aff_line < aff_line ? -1 : trend_dir
Finally, the filter is rendered as two overlapping plots at the same value: a step-line that traces the filter's path and a circle overlay positioned at each bar's filter value. The circles serve a visual purpose, reinforcing the current filter level at each step and making it easier to read the filter's position at a glance, particularly during flat periods where the step-line alone can be harder to track. Together they produce a dotted step appearance that improves legibility across different chart zoom levels and timeframes.
🟢 Signal Interpretation
▶ Bullish Trend (AFF Line Rising with Bullish Colour): When price generates enough upward force to exceed the friction threshold, the filter begins stepping higher and the line shifts to the bullish colour. The step-line rendering makes the transition visually clear; flat segments indicate bars where force was insufficient to move the filter, while upward steps reflect bars where it was. The bullish trend state persists until force in the downward direction is large enough to push the filter lower, at which point trend direction flips and the line shifts to the bearish colour.
▶ Bearish Trend (AFF Line Declining with Bearish Colour): When price generates enough downward force to exceed the friction threshold, the filter begins stepping lower and shifts to the bearish colour. As with the bullish state, the filter holds its last value on bars where force is insufficient to breach the threshold, and the direction state remains unchanged on those bars. A full reversal back to bullish requires upward force to exceed the friction threshold and push the filter higher, at which point trend direction flips and the colour transitions accordingly.
🟢 Features
▶ Preconfigured Presets: Three parameter sets cover a range of trading styles and timeframes. "Default" delivers balanced noise filtering for swing trading on 4-hour and daily charts. "Fast Response" lowers the friction threshold and accelerates the catch-up rate for intraday and scalping use on 5-minute to 1-hour charts, producing earlier filter movement in response to smaller price displacements. "Smooth Trend" raises the threshold and slows the catch-up rate for position trading on daily and weekly charts, requiring larger price displacements relative to the average noise level before the filter advances.
▶ Built-in Alerts: Three alert conditions support automated monitoring of trend transitions. "Bullish Trend Signal" fires on the first bar trend direction flips from bearish to bullish. "Bearish Trend Signal" fires on the first bar trend direction flips from bullish to bearish. "Any Trend Change" triggers on either transition for traders who want a single unified alert regardless of direction. All alerts include the exchange, ticker, and timeframe in the message for immediate context.
▶ Visual Customisation: Six colour presets, Classic, Aqua, Cosmic, Cyber, Neon, and Custom, provide coordinated bullish and bearish colour pairings suited to different chart themes and personal preferences. Selecting Custom exposes independent colour pickers for full manual control over both states. Optional bar colouring tints price candles with the active trend colour using a configurable transparency level, and optional background colouring extends the trend state tint across the full chart pane at a separately configurable transparency.
Indicator

Kinetic Hull Matrix [JOAT]Kinetic Hull Matrix
Overview
Kinetic Hull Matrix is an adaptive trend-following indicator centred on a Hull Moving Average cloud with ATR-proportional envelopes, a custom ADX engine, a 0–100 composite signal scoring system, and a multi-timeframe trend table — all rendered in a layered fill system that visually communicates trend strength and cloud penetration depth simultaneously. Retest signals fire when price touches the cloud boundary from within the trending direction, scored by four independent quality factors.
The Hull Moving Average — Why It Matters
The Hull Moving Average (HMA) was designed to reduce lag while maintaining smoothness. The calculation uses weighted moving averages at half-length and full-length, doubles the half-length result, subtracts the full-length result (creating a de-lagged series), then applies a final WMA at the square root of the length:
WMA(2 * WMA(src, n/2) - WMA(src, n), sqrt(n))
This produces a moving average that reacts significantly faster to price changes than a standard EMA or SMA of the same length, while filtering micro-noise through the final WMA pass. The result is a responsive midline that rarely produces whipsaws in trending markets.
ATR-Adaptive Cloud Architecture
The HMA midline is expanded into a four-layer cloud using the current ATR:
- Inner cloud (upper and lower bands): HullMid ± ATR × CloudMultiplier (default 1.0). This is the primary retest detection zone.
- Outer bands: HullMid ± ATR × CloudMultiplier × OuterMultiplier (default 1.618, the golden ratio). These define the statistical extreme of the cloud envelope.
The cloud dynamically widens during volatile markets and contracts during compression — naturally adapting to market conditions without manual parameter changes.
Four fill layers are rendered between the bands using trend-coloured gradients: bright teal in uptrends, muted red in downtrends, creating an intuitive visual heat map of trend energy.
Custom ADX Engine
Rather than relying on the built-in ta.dmi(), Kinetic Hull Matrix implements its own ADX from first principles:
1. Positive directional movement (plusDM) = max(high - high , 0) when high-to-high exceeds low-to-low
2. Negative directional movement (minusDM) = max(low - low, 0) when low-to-low exceeds high-to-high
3. Both are smoothed via ta.rma() over the ADX length, then divided by the RMA of true range to produce +DI and -DI
4. The directional index DX = abs(+DI - -DI) / (+DI + -DI) * 100, finally smoothed via ta.rma() to produce ADX
This gives a transparent, auditable ADX implementation. Values above 25 indicate a trending regime; below 25 indicates ranging conditions. The dashboard and scoring system both use this value.
Composite Signal Score (0–100)
A retest signal qualifies only when close price enters the inner cloud (touches upper cloud from above in a downtrend or lower cloud from below in an uptrend) while the candle closes back in the trend direction. The resulting signal is then scored:
- Proximity score (up to 50): How deeply price penetrated into the cloud. Deeper retests score higher.
- Volume score (up to 25): Current volume relative to its 20-bar SMA. Higher participation scores higher.
- RSI score (up to 15): RSI directional headroom — long signals score better when RSI has room below 55, short signals when RSI has room above 45.
- ADX score (up to 10): Raw ADX value × 0.4, capped at 10. Strong trends produce higher-quality retests.
Only signals meeting the configurable minimum score threshold (default 40) are displayed.
S/R Line Stamping
Each confirmed retest signal stamps a horizontal dotted line at the close price, extending 60 bars forward. These lines serve as dynamic support (for bull retests) and resistance (for bear retests). Lines are automatically invalidated and deleted if price closes through them by more than 0.5 ATR — the indicator only keeps lines that have not been structurally broken.
Multi-Timeframe Trend Table (Top Right)
Five user-configurable timeframes are assessed using the same dual-EMA logic (fast = HullLen/2, slow = HullLen). Each cell displays BULL or BEAR in the trend's colour. A "X/5 Bull" counter at the bottom summarises alignment. The table also shows current ADX value, RSI, and number of active S/R lines.
Inputs Reference
Hull Cloud
- Hull MA Length (21) — primary HMA period
- ATR Length (14) — period for ATR cloud width
- Cloud Width (1.0 ATR) — inner cloud half-width multiplier
- Outer Band Mult (1.618) — outer band golden-ratio expansion
- ADX Length (14) — custom ADX smoothing period
- Volume SMA Length (20) — reference for volume scoring
- RSI Length (14)
Retest Detection
- Min Signal Score (40) — minimum composite score to display signal
- Max S/R Lines (8) — maximum simultaneous S/R lines on chart
- S/R Break Buffer (0.5 ATR) — tolerance before a line is considered broken
- Show Score Label / Show S/R Lines
MTF Dashboard
- Show MTF Trend Table
- TF 1–5 — five independently configurable timeframes
Visual
- Theme: Dark, Light, Auto
How to Use
1. Apply to a liquid trending instrument. Allow warmup (roughly 3× Hull Length bars).
2. Identify the trend from cloud colour: teal fills = uptrend, red fills = downtrend.
3. Wait for price to dip into the inner cloud during an uptrend (or spike into it during a downtrend) and close back in the trend direction.
4. Check the score label — prefer grade 55+ (B or higher). Crosscheck with the MTF table: 4+ of 5 timeframes aligned significantly improves reliability.
5. The stamped S/R line from the retest level serves as a reference for re-entry if price pulls back again.
Non-Repainting Design
All retest signals are gated by barstate.isconfirmed. MTF data uses lookahead_off. S/R line management runs only on confirmed bars. No visual element shifts position after the bar closes.
Limitations
- In ranging, choppy markets, the cloud direction changes frequently and retest signals may have low predictive value. The ADX score component partially mitigates this, but consider increasing the minimum score threshold in low-trend environments.
- S/R lines accumulate during active trend periods. The max line count setting prevents chart clutter.
- MTF trend data requires request.security() calls per timeframe. On lower timeframes with very high bar counts, this may slightly affect indicator load time.
Disclaimer
This indicator is for educational and informational purposes only. No signal scoring system guarantees future performance. Always use proper risk management and conduct independent analysis before trading.
Made with passion by officialjackofalltrades
Indicator

Vortex Volume Spectrum [JOAT]Vortex Volume Spectrum
Overview
Vortex Volume Spectrum is a dynamic, proportional volume profile indicator built from scratch in Pine Script v6. It analyses how traded volume distributes across price levels within any configurable lookback window, identifies the Point of Control (POC) — the price level with the highest volume concentration — and draws the Value Area (the 70% of total volume nearest the POC) as a live-updating profile rendered directly on the chart using the box drawing API. Unlike fixed-range volume profiles offered by some platforms, this engine recalculates on every bar and is fully parametric.
Why Build a Volume Profile in Pine?
Volume profile is one of the most powerful market microstructure tools available, revealing where the majority of market participants transacted. Most PulseWire users rely on the built-in session profile which cannot be customised, scripted, or combined with other logic. Vortex Volume Spectrum gives Pine authors and traders a fully transparent, open-source volume distribution engine they can understand, modify, and build upon — with the visual quality of a professional charting suite.
Distribution Engine
The profile is built with a configurable number of price bins (default 30) spanning the high-to-low range of the lookback window. For each bin, the engine calculates the proportional contribution of each historical bar's volume using an overlap method:
Each bar contributes volume proportionally to the fraction of its high-to-low range that overlaps with each bin. A bar spanning multiple bins splits its volume across all overlapping bins by the fraction of overlap — preventing the unrealistic "winner takes all" binning used by simpler implementations.
This overlap-proportional distribution produces a smooth, accurate volume histogram that closely mirrors the actual traded price distribution.
POC Detection
After computing the full distribution array, the engine scans for the bin with the highest accumulated volume. This bin's midpoint is the Point of Control — the price level where the most volume traded during the lookback window. The POC is highlighted as the brightest horizontal line in the profile.
Value Area (70%) Calculation
Starting from the POC bin, the Value Area algorithm expands outward — one bin up and one bin down in alternating steps — absorbing bins into the Value Area until their cumulative volume equals or exceeds 70% of total profile volume. The result is a price range (Value Area High and Value Area Low) that contains the bulk of institutional activity. This range is where the majority of price acceptance occurred and serves as a reference for mean-reversion and breakout trading contexts.
Live Rendering at barstate.islast
The entire profile is rebuilt from scratch on each bar's final tick using the delete-before-create pattern: all existing profile boxes are deleted before redrawing. This ensures that the profile is always current without leaving ghost boxes on the chart. Each bin is drawn as a horizontal box scaled to its volume proportion relative to the maximum bin, using a gradient colour from muted (low volume) to bright teal (near-POC), with the POC bin rendered in gold.
Profile Elements
- Volume bins: Horizontal boxes scaled by proportional volume, coloured by intensity
- POC line: Gold horizontal line at the maximum-volume price level
- Value Area High / Low lines: Teal dashed lines marking the 70% value area boundary
- Volume Delta overlay: For each bar, buy volume (close > open) and sell volume (close < open) are tracked separately and displayed as a delta bar, showing the directional pressure within the profile window
Inputs Reference
- Profile Length (100) — number of bars included in the lookback window
- Number of Bins (30) — vertical resolution of the price distribution
- Profile Width (40 bars) — horizontal width of the rendered boxes
- Show POC Line — toggles the gold POC highlight
- Show Value Area — toggles the 70% Value Area High/Low lines
- Show Volume Delta — toggles the delta bar visualisation
- Profile Offset (0) — shifts the profile left or right from the current bar
- Theme: Dark / Light / Auto
How to Use
1. Add to any chart. The profile automatically spans the last N bars (configurable lookback).
2. The POC (gold line) is the most significant reference level — price tends to be attracted back to the POC when trading away from it.
3. The Value Area High and Low act as potential support/resistance zones. Breakouts above VAH with volume expansion are bullish continuation signals; breakouts below VAL signal bearish continuation.
4. If price is trading within the Value Area, expect range behaviour with mean reversion toward the POC.
5. Volume Delta bars help identify whether the current session's participation is predominantly buying or selling within the profiled window.
Non-Repainting Design
The profile always renders at barstate.islast using only confirmed historical bar data. No forward-looking data is accessed. The POC and Value Area lines represent historical distribution within the defined lookback and do not shift on historical bars.
Limitations
- Volume profiles are most meaningful on instruments with genuine, transparent volume (equities, futures, crypto on-chain exchanges). Forex tick volume is a proxy and may produce less reliable distribution shapes.
- Increasing the number of bins significantly increases the number of box objects drawn, approaching PulseWire's per-indicator box limit on very long lookbacks.
- The profile always represents the most recent N bars — it does not anchor to specific sessions or swing levels. Session-anchored profiles require different logic.
- Very low-volume bins at the extremes are accurate but may appear invisible at small chart scales.
Disclaimer
This indicator is provided for educational and informational purposes only. Volume profile is a descriptive market microstructure tool and does not predict future price movement. Always use proper risk management in conjunction with your own analysis.
Made with passion by officialjackofalltrades
Indicator

Phantom Structure Engine [JOAT]Phantom Structure Engine
Overview
Phantom Structure Engine is a comprehensive Smart Money Concepts (SMC) framework built entirely in Pine Script v6 using typed User-Defined Types and methods. It maps institutional price structure across five dimensions simultaneously: swing Break of Structure (BOS), Change of Character (CHoCH), Order Blocks (OB), Fair Value Gaps (FVG), Equal Highs/Lows (EQH/EQL), Liquidity Sweeps, and dynamic Premium/Discount/Equilibrium zones — all rendered with an institutional-grade dark visual palette and managed via object arrays.
Why a Unified SMC Framework?
SMC concepts are deeply interconnected. A BOS creates the context for a valid Order Block. A CHoCH signals a structural regime shift that invalidates existing OBs. A liquidity sweep above an EQH often precedes a reversal into a Discount zone. Displaying these concepts in isolation (as separate indicators) breaks the logical chain between them. Phantom Structure Engine fuses all layers into a single coherent visual, so each element is always read in its correct structural context.
Core Engine — Swing Structure
Two separate pivot engines run concurrently:
- Swing pivots (configurable left/right bars, default 10/10): define the major structure highs and lows used for BOS and CHoCH detection
- Internal pivots (default 3/3): track minor structure shifts for shorter-term intrabar analysis
BOS Detection with Confirmation Counter
Rather than firing on the first close beyond a swing level, the engine counts consecutive closes above the last swing high (or below the last swing low). A BOS only registers when the close count reaches or exceeds the configurable confirmation threshold (default 1, max 5). This suppresses false breaks caused by wicks and momentary spikes while remaining responsive.
- BOS (Break of Structure): Close beyond swing level, structure direction confirmed. Displayed as a horizontal line from the pivot bar to the break bar, with a BOS label.
- CHoCH (Change of Character): BOS that occurs against the prevailing structural direction (e.g., a bullish break when the prior confirmed direction was bearish). Displayed in gold with a dashed line and CHoCH label.
Order Block Detection
When a BOS or CHoCH fires, the engine scans backward (configurable lookback, default 10 bars) for the last opposing candle — a bearish candle before a bullish BOS, or a bullish candle before a bearish BOS. This candle becomes the Order Block zone.
Each OB is drawn with a two-layer box: a wide semi-transparent outer box and a tighter inner highlight. The OB extends forward on every bar and automatically invalidates (turns grey) when price closes through the opposite boundary — the exact behaviour seen when an OB has been mitigated by institutional flow.
Fair Value Gap Detection
A bullish FVG is identified when bar .low > bar .high (a gap in price between the current bar's low and two bars ago's high), indicating that price moved so fast upward that no trading occurred in that range. Bearish FVG is the mirror. FVGs are drawn as dotted-border boxes that extend forward and auto-fill (turn grey) when price returns to close the gap.
Equal Highs / Equal Lows (EQH / EQL)
At each new swing pivot, the engine compares the current pivot value against the previous pivot of the same type. If the absolute percentage difference is less than 0.15%, they are classified as equal and an EQH or EQL label is stamped at the midpoint. These levels represent liquidity pools resting above or below price — targets for institutional sweeps.
Liquidity Sweeps
A sweep is detected when price wicks beyond the last confirmed swing high or low but closes back on the opposite side. This is the classic liquidity grab: price hunts stops above a high (or below a low), then reverses. Sweep labels fire at the wick extreme in gold — one of the highest-probability reversal signals in institutional analysis.
Premium / Discount / Equilibrium Zones
After each confirmed BOS, the engine identifies the full range between the last confirmed swing high and swing low. This range is divided into three zones:
- Premium (top 38.2%): Statistically expensive — short bias in a bearish structure
- Equilibrium (38.2%–61.8%): Fair value — reduce exposure
- Discount (bottom 38.2%): Statistically cheap — long bias in a bullish structure
Previous zones are deleted and redrawn on each new BOS, keeping the chart clean.
Periodic Levels (PDH / PDL / PWH / PWL)
Previous Day High/Low and Previous Week High/Low are fetched via request.security() with lookahead disabled (barmerge.lookahead_off), preventing any future-bar contamination. These levels render as step-line plots and represent the primary reference levels used by institutional order desks at open.
Institutional Funding Candles
Bars where the true range exceeds 1.5× ATR(14) AND volume exceeds 2× the 20-bar volume SMA are highlighted as funding candles. These represent institutional participation bars and are coloured based on the current structural direction: teal (bullish structure), red (bearish structure), gold (neutral).
Dashboard (Top Right)
A compact 2-column, 8-row table displays: current structural direction, active OB count, open FVG count, last confirmed swing high/low values, and current sweep status for both sides.
Inputs Reference
Structure Settings
- Swing Pivot Left/Right Bars (10/10) — major swing sensitivity
- Internal Pivot Left/Right (3/3) — minor structure sensitivity
- BOS Confirmation Closes (1–5) — consecutive closes needed to confirm BOS
- Show BOS Labels / CHoCH Labels / HH-HL-LH-LL labels
Order Blocks
- Show Order Blocks
- OB Lookback Candles (10) — how far back to scan for the OB candle
- Max Active OBs (6) — older OBs are deleted when limit is reached
Fair Value Gaps
- Show Fair Value Gaps
- Max Active FVGs (5)
Premium / Discount
- Show PD Zones / EQH-EQL / Liquidity Sweeps
Periodic Levels
- Show Prev Day H/L / Prev Week H/L
Visual
- Theme: Dark, Light, Auto
- Show Funding Candles
How to Use
1. Apply on any liquid instrument. Allow the warmup period (driven by pivot lookback) before trusting the signals.
2. Read structure direction from the dashboard. BOS labels in teal confirm a bullish shift; CHoCH in gold signals a potential trend reversal.
3. Look for price to pull back into a valid (not invalidated) OB or into the Discount zone before considering long entries. Reverse for shorts.
4. FVG zones often act as magnets — price tends to revisit them before continuing in the BOS direction.
5. Treat Liquidity Sweep labels as potential reversal alerts, particularly when they align with OBs or Discount/Premium zones.
Non-Repainting Design
All BOS, CHoCH, sweep, and FVG signals are gated by barstate.isconfirmed. Periodic levels use close with lookahead_off. No pivot value is read until the required right-bar confirmation period has elapsed. Historical labels never shift position.
Limitations
- SMC is a discretionary framework. This indicator automates detection but cannot replace contextual judgment on higher-timeframe bias.
- In extremely fast-moving markets, FVGs may form and fill within the same session, reducing their relevance as future targets.
- EQH/EQL detection uses a 0.15% price equality threshold — this may need adjustment for very low-priced or highly volatile instruments.
- OBs are detected from the most recent opposing candle before a BOS. On some instruments, the true institutional OB may be further back.
Disclaimer
This indicator is provided for educational and informational purposes only. SMC concepts describe price behaviour patterns and do not guarantee any future market outcome. Always conduct your own analysis and use proper risk management.
Made with passion by officialjackofalltrades
Indicator

Compression Vector [JOAT]Compression Vector
Overview
Compression Vector is a dual-engine volatility compression detector built in Pine Script v6. It identifies moments when both Bollinger Band width and Average True Range simultaneously contract relative to their historical baselines — a confluence that institutional traders recognise as the calm before an explosive directional move. When the squeeze releases, the indicator fires scored breakout signals with adaptive ATR-based take-profit levels and stop-loss placement directly on the chart.
Why This Approach?
Most squeeze indicators rely on a single compression measure, such as BB width relative to Keltner Channel, which can produce false signals in low-volume sideways drift. Compression Vector cross-validates two independent compression engines:
- Engine 1 — ATR Historical Ratio: Compares the 14-bar ATR against a slow ATR of configurable length (default 50). If the ratio falls below the compression threshold, the first engine fires.
- Engine 2 — BB + ATR SMA Squeeze: Compares current BB width against its own SMA (so the band must narrow relative to its own recent average), AND compares the current ATR against its short-term SMA. Only when at least one of these secondary tests also confirms does a dual-engine squeeze register.
Both engines must agree before a zone is created. This eliminates the noise inherent in single-measure detectors.
Compression Zones — 3-Layer Institutional Box System
Each confirmed squeeze prints a three-layer box structure that visually encodes squeeze intensity through colour:
- Halo layer (outer): Wide, nearly transparent — marks the full expansion of the compressed range plus padding
- Body layer (mid): The actual high-to-low range of all bars inside the squeeze
- Core layer (inner): A tighter 40% interior slice highlighting the median energy pocket
The box colour progresses through a time-weighted palette: grey (< 5 bars), purple (5–9), teal (10–19), gold (20+). Longer squeezes accumulate more potential energy and are weighted accordingly in the signal score.
Breakout Signal Scoring (0–100)
When close breaks convincingly above or below a zone, the indicator computes a composite score before stamping the signal:
- Proximity score (up to 35) — volume vs. its 20-bar SMA
- Squeeze score (up to 35) — duration of the squeeze in bars × 2.5
- RSI score (up to 15) — directional RSI headroom (long: RSI below 62, short: RSI above 38)
- Impulse score (up to 15) — breakout candle body relative to ATR
Grade letter (A+, A, B, C, D) is stamped on the signal label. Only breakouts where the candle body exceeds a configurable ATR multiple ("Min Impulse Body") qualify.
Adaptive TP / SL Lines
Risk is calculated as the distance from entry to the opposite zone boundary plus an ATR buffer. Three take-profit levels at configurable R:R multiples (default 1.5R, 2.5R, 4.0R) are drawn as dotted lines extending forward 45 bars. The stop-loss line is drawn in the opposing colour at the calculated risk distance below/above entry.
Dashboard (Bottom Centre)
A compact 8-column table displays in real time:
- Squeeze state (COMPRESSING / RELAXED) with bar count
- ASCII compression gauge (6 segments)
- ATR ratio and BB width percentage
- RSI, volume multiplier, last zone score with grade
- Active zone count and warm-up status
Inputs Reference
Squeeze Engine
- ATR Historical Length (50) — lookback for the slow ATR baseline
- ATR Compression Threshold (0.72) — ratio below which ATR engine triggers
- Bollinger Band Length (20) — period for BB and BB-width SMA
- BB Std Dev Multiplier (2.0) — standard deviation width of the Bollinger Bands
- BB Width Squeeze Ratio (0.82) — fraction of BB-width SMA below which BB engine triggers
- ATR SMA Squeeze Ratio (0.90) — fraction of ATR SMA below which ATR secondary engine triggers
- Min Bars Required in Squeeze (3) — minimum consecutive bars before a zone is registered
Signal Filters
- Require Volume Above SMA — gates breakouts to above-average volume bars
- Volume SMA Length (20) — reference volume baseline
- Block Overbought/Oversold — RSI filter at 72 long / 28 short
- RSI Length (14)
- Min Impulse Body (1.3 ATR) — minimum breakout candle body in ATR units
- Max Zones Tracked (6)
Risk & Targets
- SL Buffer (0.3 ATR) — added to raw risk for stop placement
- TP1 / TP2 / TP3 R:R — take-profit multiples (1.5 / 2.5 / 4.0)
Visual Settings
- Show Compression Zones / Show TP-SL Lines / Show Dashboard
- Theme: Dark, Light, or Auto (detects chart background)
How to Use
1. Add the indicator on any liquid market and timeframe. A warmup of roughly 100 bars is required before signals appear.
2. Watch for the dashboard state to read COMPRESSING and the gauge to fill. The longer the squeeze, the higher the potential score on breakout.
3. Wait for a labelled signal (BREAK+ for long, BREAK- for short). Prefer grade A or A+.
4. Use the drawn TP lines for partial exits and the SL line for stop placement.
5. Higher timeframes (15m, 1H, 4H) tend to produce cleaner zones with fewer false breaks.
Non-Repainting Design
All signals are gated by barstate.isconfirmed, meaning they only fire on the final tick of a closed bar. Zones are computed from confirmed historical bars only. The indicator will never repaint a past signal.
Limitations
- In extremely choppy, low-volume markets, short squeezes (2–3 bars) may resolve without meaningful breakout momentum. Raise Min Bars to filter these.
- The composite score is calibrated for liquid instruments. Illiquid or exotic pairs may require adjustment of the volume multiplier filter.
- ATR-based TP/SL levels are approximate and should not replace proper position sizing.
- No future-bar lookahead is used in any request.security() call.
Disclaimer
This indicator is provided for educational and informational purposes only. Past performance of any signal pattern is not indicative of future results. Always use proper risk management and conduct your own analysis before making any trading decisions.
Made with passion by officialjackofalltrades
Indicator

Indicator

Indicator

Sovereign Trend Strategy [JOAT]Sovereign Trend Strategy
Introduction
The Sovereign Trend Strategy is a systematic, rules-based trend-following strategy built on the SMEMA (SMA of EMA) crossover engine — a double-smoothed moving average system that removes the erratic noise of raw EMA crossovers while remaining faster to respond than pure SMA systems. It enters long and short trades on SMEMA fast/slow crossovers, applies four optional confirmation filters (ADX, RSI, volatility ratio, and baseline), and manages each trade through a full exit framework: stop loss, two take-profit levels with partial close at TP1, a dynamic trailing stop, a trend-reversal exit, and a maximum bars cap that forces turnover.
This is a strategy designed to trade constantly — the default configuration is tuned for maximum trade frequency across all assets and timeframes, with all optional filters disabled so that every valid SMEMA crossover generates a signal. Traders seeking higher-quality entries can enable the ADX, RSI, baseline, or volatility filters individually to raise the bar.
Core Concepts
SMEMA — Double-Smoothed Moving Average Engine
The SMEMA construction applies a simple moving average on top of an exponential moving average, producing a line that is more responsive than a plain SMA but smoother than a raw EMA:
smema(float src, int len) =>
ta.sma(ta.ema(src, len), len)
float fast = smema(close, smFast)
float slow = smema(close, smSlow)
float baseline = smema(close, smBase)
Three SMEMA lines are computed: a fast line (default length 2), a slow line (default length 5), and a longer baseline (default length 15). Crossovers between fast and slow generate the entry signals. The baseline provides an optional directional filter when enabled.
Entry Conditions
Long entries fire when the fast SMEMA crosses above the slow SMEMA with all active filters passing:
bool xUp = ta.crossover(fast, slow)
bool longOk = xUp and adxOk and rsiLongOk and volOk and baseOk
and warmed and inDateRange and barstate.isconfirmed and doLong
Short entries mirror this on downward crossovers. Entries only fire when there are no open trades (pyramiding disabled), ensuring clean one-trade-at-a-time management.
Trade Management Framework
Each trade uses ATR-based levels calculated at entry:
| Level | Default Multiplier | Purpose |
|-------|-------------------|---------|
| Stop Loss | 1.8× ATR | Full position stop |
| TP1 | 2.5× ATR | 50% partial close, breakeven stop move |
| TP2 | 4.5× ATR | Full position close |
| Trailing Stop | 1.5× ATR | Activated after TP1 hit |
After TP1 triggers, the stop-loss is moved to the entry price (breakeven). The trailing stop then follows price by 1.5× ATR, locking in profit while letting the remaining position run toward TP2. This staged approach captures quick-reaction profits at TP1 and rides momentum toward TP2.
Six Exit Paths
// Priority order for long exits:
// 1. Stop Loss — low <= entrySL
// 2. TP1 — high >= entryTP1 (50% partial, breakeven stop set)
// 3. TP2 — high >= entryTP2 (full close after TP1 hit)
// 4. Trailing — low <= trlStop (after TP1 hit)
// 5. Reversal — fast SMEMA crosses below slow (xDn confirmed)
// 6. Max Bars — barsInTrd >= maxBars
The max bars exit (default 10) is particularly important for trade frequency — it guarantees no position is held longer than 10 bars regardless of whether any other exit triggers, creating rapid capital recycling and enabling 100+ trade sample sizes even on daily timeframes.
Optional Confirmation Filters
All four filters are disabled by default and can be enabled individually:
ADX Filter — requires ADX above a minimum threshold before entry. Prevents entries in ranging, low-momentum markets.
RSI Filter — requires RSI above the bull minimum for longs (default 52) or below the bear maximum for shorts (default 48). Confirms momentum alignment with direction.
Volatility Ratio Filter — requires current ATR to be at least a configurable fraction of its own SMA. Filters out squeeze conditions where ATR is compressed.
Baseline Filter — requires close to be above the baseline SMEMA for longs and below for shorts. Adds a medium-term trend confirmation layer.
Strategy Parameters (Backtesting Standards)
Initial capital: $10,000 (realistic for the average retail trader)
Position size: 100% of equity (maximizes trade count visibility in backtest)
Commission: 0.05% per side (appropriate for most spot and futures markets)
Slippage: 2 ticks (conservative estimate for liquid instruments)
Pyramiding: 0 (no compounding positions)
Features
SMEMA fast/slow crossover entry engine with three configurable period lengths
Full trade management: ATR-based SL, TP1 (50% partial), TP2 (full), trailing stop, reversal exit, max bars exit
Breakeven stop migration to entry price after TP1 hit
Four optional confirmation filters: ADX, RSI, volatility ratio, and SMEMA baseline
Long-only, short-only, or both directions configurable
Date range filter for restricted backtesting windows
Live SL, TP1, and TP2 dashed lines drawn on the chart while a trade is open
SMEMA ribbon fill between fast and slow lines, colored by crossover direction
▲ LONG / ▼ SHORT signal labels at every entry signal
Dashboard: position, SMEMA cross direction, ADX, RSI, vol ratio, trade count, win rate, net P&L, bars in trade, settings summary
Alerts for long entry and short entry signals
Webhook JSON alert format
Watermark
Input Parameters
SMEMA Engine
Fast SMEMA Length — period for the fast crossover line (default 2)
Slow SMEMA Length — period for the slow crossover line (default 5)
Baseline SMEMA — period for the optional trend baseline (default 15)
Trend Filter
ADX Length — period for ADX / DMI calculation (default 14)
Min ADX — minimum ADX value required before entry (default 18)
Enable ADX Filter — master toggle (default off)
RSI Filter
RSI Length — period for RSI calculation (default 14)
RSI Bull Min — minimum RSI for long entries (default 52)
RSI Bear Max — maximum RSI for short entries (default 48)
Enable RSI Filter — master toggle (default off)
Volatility Filter
ATR Length — lookback for ATR (default 14)
ATR Smooth — lookback for the ATR average used in ratio (default 20)
Min Vol Ratio — ATR/AvgATR minimum threshold (default 0.8)
Enable Vol Ratio Filter — master toggle (default off)
Baseline Filter
Enable Baseline Filter — when on, requires close above baseline for longs and below for shorts (default off)
Trade Management
Stop-Loss ATR Mult — distance of initial stop from entry in ATR units (default 1.8)
TP1 ATR Mult — distance of first take-profit from entry (default 2.5)
TP2 ATR Mult — distance of second take-profit from entry (default 4.5)
Use Trailing Stop — enables dynamic trailing after TP1 (default on)
Trailing Stop ATR Mult — trail distance in ATR units (default 1.5)
Max Bars in Trade — maximum bars before forced exit (default 10)
Trade Direction
Allow Long Trades — toggles long entry signals (default on)
Allow Short Trades — toggles short entry signals (default on)
Date Range
Enable Date Filter — restricts backtesting to a specific window
From Date / To Date — start and end of the active period
Visuals
Bull Color — cyan default for upside elements
Bear Color — red default for downside elements
Neutral Color — gray for baseline and neutral dashboard text
Show Dashboard — live performance and settings panel
Show Watermark
Show Signal Labels — ▲ LONG / ▼ SHORT markers on entry bars
Show SMEMA Bands — toggles the ribbon and three SMEMA line plots
How to Use
Add the strategy to any chart. The default settings are tuned for high trade frequency — no filters enabled, fast periods of 2/5, max bars 10.
Run the Strategy Tester to review backtest performance. Check that the trade count is above 100 on your chosen timeframe and symbol before drawing any performance conclusions.
To increase signal quality at the cost of trade frequency, enable filters one at a time: start with the ADX filter to eliminate ranging entries, then add RSI if you want additional momentum confirmation.
Use the SL/TP dashed lines drawn on-chart during live trades to monitor your risk levels visually in real time.
Set the Long Entry and Short Entry alerts to receive notifications. Use Webhook JSON format to route signals to automation platforms.
Adjust the ATR multipliers to fit the volatility profile of your market. Higher-volatility assets like altcoins benefit from wider stops (2.0–2.5×) and wider TP levels. Lower-volatility assets like indices may work better with tighter parameters.
The Max Bars in Trade parameter is the most powerful lever for trade frequency. Reducing it to 5–7 generates very high trade counts. Increasing it to 20–40 gives trades more room to develop but reduces total trade count.
Indicator Limitations
SMEMA crossovers are inherently lagging — by definition, the crossover confirms a direction change after it has already begun. In fast-moving markets this means entries will not be at the exact turning point.
The default configuration (all filters off, max bars 10) optimizes for trade count and sample size rather than highest possible win rate. Enabling filters will reduce trade count but may improve per-trade quality — test thoroughly on your symbol and timeframe before live use.
The 100% equity position sizing in the backtest is chosen to keep commission effects proportional and performance metrics visible at small capital sizes. This does not represent a recommendation to risk your entire account on any trade.
Backtested results are not a guarantee of future performance. Past performance under any parameters does not imply future results.
The strategy uses `calc_on_every_tick=false` — all orders execute at bar close, which is more realistic than tick-by-tick simulation but means intrabar SL/TP wicks may not be captured accurately in the backtest.
Originality Statement
The Sovereign Trend Strategy is an original Pine Script v6 strategy publication. The SMEMA (SMA of EMA) double-smoothing construction is an original baseline engineering choice that produces a distinct crossover behavior not replicated by standard EMA or SMA crossover systems. The six-path exit framework, the staged TP1/breakeven/trailing/TP2 management sequence, and the modular optional filter architecture are original design decisions. The strategy.position_size derivation of position state (avoiding the Pine Script v6 timing bug with strategy.opentrades and manual boolean flags) is an original technical solution developed for this publication.
Disclaimer
This is a backtested strategy provided for educational purposes only. It does not constitute financial advice or a recommendation to trade any specific instrument. All trading involves risk of capital loss. Backtested performance does not guarantee future results. Commission, slippage, and real-world execution conditions will differ from backtest simulations. Always perform your own analysis and consult a licensed financial professional before trading with real capital.
-Made with passion by jackofalltrades
Strategy

Prism Channel Architecture [JOAT]Prism Channel Architecture
Introduction
Prism Channel Architecture is a dual-channel overlay indicator that layers two mathematically distinct structural frameworks onto your price chart simultaneously: a best-fit Pivot Channel derived from actual price pivot points, and a Linear Regression Channel built from statistical least-squares fitting. Together they create a structural prism through which trend direction, channel quality, and breakout momentum can be evaluated from multiple angles at once.
Most channel tools force you to choose between objectivity and responsiveness. Pivot channels adapt to real market structure but can lag. Regression channels are statistically rigorous but ignore actual swing highs and lows. PCA runs both engines in parallel and highlights the moments when they agree — bull alignment and bear alignment states — as the highest-conviction reads in the system.
Core Concepts
Pivot Channel Fitting
The indicator collects up to a configurable maximum of confirmed pivot highs and pivot lows using PulseWire's built-in pivot functions:
float pivHigh = ta.pivothigh(high, pivLeft, pivRight)
float pivLow = ta.pivotlow( low, pivLeft, pivRight)
From those stored pivot arrays, it searches for the best pair of recent pivot highs to fit the upper channel boundary, and the best pair of recent pivot lows to fit the lower channel boundary. The quality score for each candidate pair is computed by checking how many of the recent bars were actually contained below the upper line (or above the lower line) within an ATR tolerance:
for k = 0 to checks - 1
float lineY = linePrice(x2, y2, x1, y1, bar_index - k)
if high <= lineY + atrVal * 0.3
contained += 1
float q = safeDiv(float(contained), float(checks), 0.0)
The pair with the highest containment ratio wins and becomes the drawn channel. This means the upper channel line is always the tightest valid resistance line through recent pivot highs, not an arbitrary parallel projection.
Linear Regression Channel
The regression channel computes a full manual least-squares fit over the lookback window, producing slope, intercept, and residual standard deviation:
float slope = safeDiv(n * sumXY - sumX * sumY, n * sumXSq - sumX * sumX, 0.0)
float intc = safeDiv(sumY - slope * sumX, n, close)
float stdDev = math.sqrt(safeDiv(ssRes, n, 0.0))
The upper and lower bands are drawn at `stdDev × Deviation Multiplier` distance from the regression midline, giving bands that are statistically calibrated to the actual spread of price around the trend. Color shifts from bull to bear when slope changes sign.
Channel Alignment Confluence
The system declares a Bull Alignment when both channels simultaneously agree price is in a bullish position — the regression slope is rising AND price is above the regression midline, AND price is in the upper half of the pivot channel (between the midline and the upper band):
bool lrBull = close > midNow and slope > 0.0
bool pivBull = close > uMid and close < uNow
bool alignBull = lrBull and pivBull
This confluence state is highlighted with a subtle background color — a quiet but meaningful signal that two independent structural frameworks are pointing in the same direction.
ATR-Based Breakout Detection
Breakout signals fire when price moves more than a configurable ATR multiple beyond the prior bar, provided the regression slope confirms direction:
bool brkUp = ta.crossover(close, close + crossTol * atrVal) and lrSlope > 0.0
bool brkDn = ta.crossunder(close, close - crossTol * atrVal) and lrSlope < 0.0
Breakout labels (▲ BRK / ▼ BRK) appear above or below the breakout bar and are alert-enabled.
Features
Pivot Channel — best-fit upper/lower boundaries through recent pivot highs/lows, quality-scored by containment ratio
Regression Channel — least-squares midline with statistically calibrated deviation bands, auto-colored by slope direction
Channel midline — dashed neutral midline bisecting the pivot channel for zone positioning
Bull and Bear Alignment detection — background highlight when both channels agree on direction
ATR-normalized breakout labels — ▲ BRK and ▼ BRK when price breaks out with trend confirmation
Channel Quality score — displayed in dashboard as percentage of recent bars contained
Pivot position classification — Bull Zone (upper half) or Bear Zone (lower half)
Up to 40 pivot highs and 40 pivot lows stored and evaluated
10-bar channel projection extended to the right of the last bar
Dashboard: LR direction, deviation mult, pivot quality, pivot position, alignment, breakout, ATR, pivot count
Alerts for bullish breakout, bearish breakout, bull alignment, and bear alignment
Webhook JSON alert format
Watermark
Input Parameters
Pivot Channel
Pivot Lookback Left — bars to the left required to confirm a pivot high or low (default 10)
Pivot Lookback Right — bars to the right required to confirm a pivot high or low (default 5)
Max Pivots Stored — maximum number of pivot highs and lows held in memory (default 30)
Quality Check Length — number of recent bars used to score channel containment (default 20)
Breakout ATR Mult — ATR multiplier threshold for breakout label generation (default 1.5)
Show Pivot Channel — toggle the pivot channel lines on/off
Regression Channel
Regression Length — bars used in the least-squares fit (default 50)
Deviation Mult — standard deviation multiplier for band width (default 2.0)
Show Regression Channel — toggle the regression channel lines and fill on/off
ATR Settings
ATR Length — lookback for ATR calculation used in breakout detection and containment tolerance (default 14)
Visuals
Bull Color — color for uptrending channels and bullish labels
Bear Color — color for downtrending channels and bearish labels
Neutral Color — color for channel midlines and neutral dashboard text
Show Dashboard — compact structural summary panel
Show Watermark
Show Breakout Labels — toggle ▲ BRK / ▼ BRK label markers
Alerts
Webhook JSON Format — switches alert messages to JSON format for automation pipelines
How to Use
Add PCA to your chart as a main-pane overlay indicator.
Let the chart load enough history so both channels initialize. A warmup period of at least 60 bars is enforced before channels begin drawing.
Use the Regression Channel to assess macro trend direction. If the midline slope is rising and price is above it, the macro environment is bullish.
Use the Pivot Channel to identify the structural support and resistance boundaries formed by actual price pivots. The upper pivot line is the tightest valid resistance. The lower pivot line is the strongest structural support.
Watch for Bull Alignment (cyan background) when both systems agree price is in a bullish structural position. This is the highest-conviction environment for long setups.
Watch for Bear Alignment (red background) for bearish structural setups.
Treat Breakout labels as momentum confirmation signals — they only fire when an ATR-significant price move occurs in the direction of the regression slope.
Check the Pivot Quality score in the dashboard. A quality above 65% means the channels are actively containing price well. Below 40% means the channel fit is loose and breakouts are less reliable.
Indicator Limitations
Pivot channel fitting evaluates only the 8 most recent pivot highs and the 8 most recent pivot lows when searching for the best pair. In very choppy markets with many closely-spaced pivots, the fitted channel may appear narrow or erratic.
The regression channel is recalculated on every bar over a fixed lookback window. It will repaint the past visually as new bars are added — the channel reflects the lookback window ending at the current bar, not a fixed historical period.
Channel quality scores can be artificially high in low-volatility trending conditions where price barely touches the edges of the channel.
Breakout signals require both an ATR threshold move AND a confirming regression slope. In sideways markets the slope condition filters out most breakout candidates, which may lead to missed signals on genuine horizontal range breaks.
Originality Statement
Prism Channel Architecture is an original Pine Script v6 publication. The dual-engine architecture combining a quality-scored best-fit pivot channel with an independently computed least-squares regression channel, and the definition of alignment confluence as agreement between those two distinct structural systems, is an original design. The pivot quality scoring methodology — measuring the containment ratio of recent bars within the candidate channel bounds with ATR tolerance — is an original technique not derived from any existing published indicator.
Disclaimer
This indicator is for educational and informational purposes only. Channels, alignment states, and breakout labels are analytical tools and do not constitute financial advice. Channel boundaries can and will be violated without warning. Always apply proper risk management and never trade solely based on indicator signals.
-Made with passion by jackofalltrades
Indicator

Torque Momentum Oscillator [JOAT]Torque Momentum Oscillator
Introduction
The Torque Momentum Oscillator is a sub-chart composite momentum engine that synthesizes four independent momentum perspectives into a single normalized 0–100 oscillator. Rather than relying on any one momentum calculation, it blends a stochastic-range oscillator, two RSI variants at different cycle lengths, and a Bollinger Band position reading into a weighted composite score — then colors the histogram on a gradient that instantly communicates whether momentum is building or exhausting.
The philosophy behind TMO is that any single momentum indicator can be fooled by choppy markets or unusual price action. When four different momentum frameworks all agree, the composite reading carries genuine conviction. When they diverge, the composite score gravitates toward the midline — a built-in disagreement signal that keeps you from over-committing to a directional bias.
Core Concepts
Component 1 — RSV (Raw Stochastic Value)
The RSV is a stochastic-style reading of where close sits within the highest high and lowest low range over the lookback period, smoothed with an SMA to reduce noise:
float hiRange = ta.highest(high, rsvPeriod)
float loRange = ta.lowest(low, rsvPeriod)
float rsvRaw = safeDiv(close - loRange, hiRange - loRange, 0.5) * 100.0
float rsvLine = ta.sma(rsvRaw, rsvSmooth)
The RSV line is also plotted independently as a fast overlay on the oscillator, giving it a secondary use as a crossover signal generator. When RSV crosses above 20, an Opportunity label fires. When it crosses back below 80, a Risk label fires.
Component 2 — RSI Fast
The standard Wilder RSI at the fast period (default 14) captures short-cycle momentum velocity. It contributes a responsive directional reading without being so short that it becomes noise.
Component 3 — RSI Slow (Blackcat-Style)
The slow RSI uses a blackcat-inspired manual construction: SMA of gains divided by SMA of absolute changes, rather than the standard Wilder smoothing:
float rsiSlowVal = safeDiv(
nz(ta.sma(math.max(close - prevClose, 0.0), rsiSlow), 50.0),
nz(ta.sma(math.abs(close - prevClose), rsiSlow), 1.0),
0.5) * 100.0
This produces a longer-cycle momentum trend bias that is less sensitive to individual candle extremes, creating a smoother counterpart to the fast RSI.
Component 4 — Normalized BB Position
Bollinger Band position tells you where price sits in its statistical envelope:
= ta.bb(close, bbLen, bbMult)
float bbPos = math.max(0.0, math.min(100.0,
safeDiv(close - bbLower, bbUpper - bbLower, 0.5) * 100.0))
At 100 price is at the upper band. At 0 it is at the lower band. At 50 it is exactly at the basis. This adds a volatility-relative momentum reading to the composite.
Weighted Composite Score
All four components are blended using user-configurable weights that are automatically normalized to sum to 1.0:
float wSum = wRsv + wRsiF + wRsiS + wBB
float composite = (rsvLine * (wRsv / wSum) +
rsiFastVal * (wRsiF / wSum) +
rsiSlowVal * (wRsiS / wSum) +
bbPos * (wBB / wSum))
Default weights: RSV 35%, RSI Fast 25%, RSI Slow 25%, BB Position 15%.
Gradient Histogram Coloring
The histogram is colored on a gradient that transitions from full bear red near 0 to transparent near 50, then from transparent bull green near 50 to full bull green near 100. This produces an immediate visual sense of momentum intensity — a faint histogram near midline means indecision, a saturated histogram near the extremes means conviction.
Features
Four-component weighted composite oscillator: RSV + RSI Fast + RSI Slow + BB Position
RSV component double duty: used in composite and plotted as independent fast line
Gradient histogram — color intensity scales with momentum conviction
Overbought (default 75) and oversold (default 25) zones with gradient fills
RSV Opportunity label when RSV crosses above 20 — potential upswing signal
RSV Risk label when RSV crosses below 80 — potential downswing signal
Per-component weight controls — customize the blend to your trading style
Midline reference at 50 and dashed OB/OS lines
Dashboard showing composite, RSV, RSI Fast, RSI Slow, BB position, and last signal
Auto dark/light theme detection
Alerts for Opportunity, Risk, entering Overbought, and entering Oversold
Webhook JSON alert format for automation
Watermark
Input Parameters
Oscillator Settings
RSV Period — lookback for the stochastic range calculation (default 20)
RSV Smoothing — SMA length applied to raw RSV before use (default 3)
RSI Fast Period — short-cycle RSI length (default 14)
RSI Slow Period — long-cycle blackcat-style RSI length (default 24)
BB Period — Bollinger Band lookback (default 20)
BB Multiplier — standard deviation multiplier for BB width (default 2.0)
Composite Weights
RSV Weight — relative weight of the stochastic component (default 0.35)
RSI Fast Weight — relative weight of the fast RSI (default 0.25)
RSI Slow Weight — relative weight of the slow RSI (default 0.25)
BB Position Weight — relative weight of the BB position reading (default 0.15)
Visual Settings
Overbought Level — upper threshold for OB zone and gradient fill (default 75)
Oversold Level — lower threshold for OS zone and gradient fill (default 25)
Show RSV Signals — toggles Opportunity and Risk label markers
Theme — Auto, Dark, or Light
Show Dashboard — compact panel with live component readings
Dashboard Position — four corner options
Show Watermark
Colors
Bull / Opportunity — color for bullish histogram bars and signal labels
Bear / Risk — color for bearish histogram bars and signal labels
RSV Line — color for the fast RSV overlay line
RSI Fast — color for the RSI Fast overlay line
How to Use
Add TMO to your chart below price as a separate sub-pane oscillator.
Watch the composite histogram for directional bias: readings above 50 favor longs, below 50 favor shorts.
Use the OB zone (above 75) and OS zone (below 25) as caution areas — not automatic reversal signals, but places where momentum is stretched and a mean reversion or consolidation becomes more likely.
Use Opportunity labels (RSV crossing above 20) as early warning that the stochastic component is turning up from deeply oversold — look for price confirmation before acting.
Use Risk labels (RSV crossing below 80) as early warning of a potential momentum rollover from overbought.
Check the dashboard to see exactly which components are driving the composite reading. If RSV and RSI Fast are both high but BB Position is low, the composite may not tell the full story.
Adjust the component weights in settings to emphasize the momentum style that best suits your market. For crypto, increasing RSV weight can be effective. For equities, RSI Slow weight can provide a smoother signal.
Indicator Limitations
The composite is a weighted average and can only be as accurate as the components that feed it. In strongly trending markets with low volatility, RSV and BB Position can both hover near extremes for extended periods — the composite will look overbought even when trend continuation is the correct read.
RSV Opportunity and Risk signals are generated by a single component (RSV) and should not be used in isolation as trade entries. They are high-probability turning-point flags that require price action confirmation.
Warmup bars are required before the oscillator becomes reliable. The indicator suppresses output until sufficient history is available.
This is a momentum indicator, not a trend direction indicator. It works best in liquid, active markets and may generate false signals during low-volume chop.
Originality Statement
The Torque Momentum Oscillator is an original Pine Script v6 publication. The architecture of combining RSV (stochastic-range), dual RSI cycles at different periodicities, and normalized Bollinger Band position into a single dynamically-weighted composite is an original design. The blackcat-style SMA-based RSI slow construction is an adapted technique included for its distinct noise characteristics, with full attribution. The gradient histogram coloring, RSV crossover signal system, and dashboard layout are original implementations built specifically for this publication.
Disclaimer
This indicator is for educational and informational purposes only. It does not constitute financial advice. Momentum readings are not predictions of future price direction. Always use proper risk management and never risk more than you can afford to lose.
-Made with passion by jackofalltrades
Indicator

Solstice Fibonacci Engine [JOAT]Solstice Fibonacci Engine
Introduction
The Solstice Fibonacci Engine is a fully automatic Fibonacci retracement and extension tool built for traders who want institutional-grade price levels drawn on their chart without the tedium of manually dragging anchor points. It detects the dominant swing high and swing low within your currently visible chart range, recalculates every time you scroll or zoom, and renders the complete Fibonacci suite — retracements from 0% to 100% and extensions to -100% — in a single, clean overlay.
The engine is purpose-built around two price zones that institutional order flow traders treat as highest-probability areas: the OTE (Optimal Trade Entry) zone from 61.8% to 78.6% retracement, and the Target Zone from -50% to -61.8% extension. These zones are shaded and labeled automatically, with TP1 through TP4 labels placed at the key confluence levels that align with those areas, giving you a ready-made trade management framework the moment any new swing is established.
Core Concepts
Visible Range Swing Detection
Unlike most Fibonacci tools that require manual anchoring or use fixed lookback lengths, Solstice tracks the swing high and swing low within the portion of the chart you are actually looking at:
int visLeft = int(chart.left_visible_bar_time)
int visRight = int(chart.right_visible_bar_time)
bool isVis = time >= visLeft and time <= visRight
if isVis
if na(swHi) or high > swHi
swHi := high
swHiBar := bar_index
if na(swLo) or low < swLo
swLo := low
swLoBar := bar_index
When you scroll left or right the swing resets instantly to reflect your new visible window. This makes the tool behave like a dynamic Fibonacci that always measures the most contextually relevant move — the one you are actually analyzing.
Trend Direction from Swing Sequence
The engine determines whether price is in an uptrend or downtrend by comparing the bar index of the swing high against the bar index of the swing low:
bool trendUp = nz(swLoBar, 0) < nz(swHiBar, 0)
If the swing low came first (left) and the swing high came after (right), price moved up — so retracement levels are drawn from the top down. If the swing high came first, price moved down and levels are drawn from the bottom up. This single boolean drives whether TP1–TP4 labels are placed above or below current price.
OTE Zone — 61.8% to 78.6%
The Optimal Trade Entry zone marks the golden pocket of Fibonacci retracement theory. Price returning into this band after a clean impulsive move often finds the institutional order flow that originally created the swing:
if showOTE
fibZone(color.new(oteClr, 90), 61.8, 78.6, trendUp,
bar_index - 2, lx, swHi, swLo, "OTE ZONE")
The zone is rendered as a shaded box extending to the right of the last visible bar, keeping it visible as new bars form. An alert fires on bar close the first time price enters this zone after it was outside it.
Target Zone — -50% to -61.8% Extension
The Target Zone marks the take-profit extension area beyond the 0% level:
if showTgt
fibZone(color.new(tgtClr, 90), -50.0, -61.8, trendUp,
bar_index - 2, lx, swHi, swLo, "TARGET ZONE")
When price has retraced into the OTE and reversed, the -50% to -61.8% extension zone becomes the natural profit target objective — where the move typically exhausts before the next consolidation.
TP1–TP4 Trade Management Labels
Four take-profit labels are placed at the levels that define a complete trade management plan from entry to full profit-taking:
| Label | Level | Meaning |
|-------|-------|---------|
| TP1 | 38.2% | First objective — scalp or partial close |
| TP2 | 0% | Full return to the original swing point |
| TP3 | -27.2% | First extension beyond the swing |
| TP4 | -61.8% | Deep extension — full target zone |
Features
Auto swing detection from visible chart range — no manual anchoring required
Dynamic recalculation on every chart scroll or zoom
Full Fibonacci suite: 0%, 23.6%, 38.2%, 50%, 61.8%, 70.6%, 78.6%, 100%, -27.2%, -50%, -61.8%, -100%, 150%, 200%
Per-level toggle switches — show only the levels you want
OTE Zone (61.8%–78.6%) shaded box with right-extension
Target Zone (-50% to -61.8%) shaded box with right-extension
TP1–TP4 labels with optional percentage labels on every level
Optional swing diagonal line from anchor to anchor
Dashboard showing swing trend, zone touch status, swing high/low, and range
Auto dark/light theme detection
Alerts fire on confirmed bar close when price enters OTE or Target Zone
Webhook JSON alert format for automation
Watermark
Input Parameters
Main Settings
Show All Elements — master toggle for all drawing objects
Show Swing Diagonal Line — draws a line connecting the two swing anchor points
Line Width — 1 to 5 pixels
Line Style — Solid, Dashed, or Dotted
Label Offset (bars) — how far to the right labels are placed beyond the last bar
Fibonacci Levels
Individual toggles for each level: 0%, 23.6%, 38.2%, 50%, 61.8%, 70.6%, 78.6%, 100%, -27.2%, -50%, -61.8%, -100%, 150%, 200%
Zones and Targets
Show OTE Zone — toggles the 61.8%–78.6% shaded box
Show Target Zone — toggles the -50% to -61.8% shaded box
Show Zone Labels — text inside zone boxes
Show TP1–TP4 Labels — take-profit label markers
Show Level % Labels — percentage text on every drawn level line
Visual Settings
Theme — Auto (reads chart background), Dark, or Light
Show Dashboard — compact panel showing current swing readings
Dashboard Position — Top Left, Top Right, Bottom Left, Bottom Right
Show Watermark
Webhook JSON — switches alerts to machine-readable JSON format
Colors
Fib Lines — color for all retracement/extension level lines
OTE Zone — fill color for the OTE box
Target Zone — fill color for the Target Zone box
How to Use
Add the indicator to any chart on any timeframe — it automatically maps to your current visible range.
Zoom or scroll your chart to frame the impulsive swing you want to analyze. The Fibonacci grid recalculates to match.
Look for price to retrace into the OTE Zone (gold band between 61.8% and 78.6%). This is the institutional entry area.
When price reverses out of the OTE zone, monitor the TP1 label at 38.2% for partial profits, TP2 at 0% for full return to the swing origin, and TP3/TP4 in the Target Zone for extended runners.
Set the OTE Zone and Target Zone alerts to receive notifications when price enters either area on bar close.
Enable percentage labels if you need to confirm exact level values for manual entries.
Indicator Limitations
The swing is determined by the highest high and lowest low within the visible range only — it does not use a structural pivot detection algorithm. On heavily zoomed-out charts, the swing might span an unusually long period.
Fibonacci levels are mathematical retracements of the detected swing range. They are areas of interest, not guaranteed reversal zones. Always combine with your own confluence analysis.
The OTE and Target Zone alerts trigger only on the first bar close when price enters the zone from outside. If price exits and re-enters, a new alert fires.
Retracement drawing regenerates on every bar close at the last bar. On very high-resolution timeframes with large numbers of active objects, this can approach PulseWire drawing limits.
Originality Statement
The Solstice Fibonacci Engine is an original Pine Script v6 implementation. Its use of chart.left_visible_bar_time and chart.right_visible_bar_time for dynamic visible-range swing detection is a novel approach that produces a self-adjusting Fibonacci tool with no manual intervention. The OTE and Target Zone framework, TP1–TP4 label system, and scroll-responsive recalculation are original design decisions made specifically for this publication.
Disclaimer
This indicator is for educational and informational purposes only. It does not constitute financial advice. Fibonacci levels are areas of potential price reaction, not certainties. Past Fibonacci confluence does not guarantee future performance. Always use proper risk management and consult a licensed financial professional before trading.
-Made with passion by jackofalltrades
Indicator

Strata Volume Contour [JOAT]Strata Volume Contour
Introduction
Strata Volume Contour (SVC) is an open-source dynamic volume profile engine that divides a configurable lookback window into 25 equidistant price bins and accumulates the total traded volume within each bin. The result is a real-time horizontal histogram drawn to the right of the current bar, showing exactly where the market has spent the most volume over the selected period. The Point of Control (POC) — the highest-volume bin — is highlighted as the dominant fair-value level. The Value Area — the range of bins containing 70% of total volume — is shaded to mark the institutional accumulation zone.
The problem SVC solves is the inability of time-based charts to show volume distribution across price levels. Standard volume bars show how much was traded each period, but not at which prices. Volume profile reveals the price levels that attracted the most participation — these are the levels where institutional orders were concentrated, making them the most meaningful support and resistance references available. SVC brings this institutional-grade analysis directly to the chart without requiring specialized volume profile software.
Core Concepts
1. Price Range Binning
The indicator determines the highest high and lowest low across the full lookback window, then divides this range into 25 equal-width bins. Each bin represents a price zone:
float rangeHi = ta.highest(high, math.min(bar_index + 1, lookback))
float rangeLo = ta.lowest( low, math.min(bar_index + 1, lookback))
float binStep = (rangeHi - rangeLo) / BINS
A zero-range guard (binStep > 0) prevents division errors on flat or illiquid instruments. With 25 bins, the histogram provides enough granularity to identify structural features while remaining visually clean.
2. Volume Accumulation (Performance-Gated)
Volume accumulation runs exclusively on the last bar of the chart (barstate.islast). This is a critical design decision: running the O(bins x lookback) double-loop on every bar within the lookback window would create an O(bars x bins x lookback) computational cost that exceeds PulseWire's execution limits on longer charts. By gating to the last bar, the full recalculation costs O(bins x lookback) exactly once per chart update:
if barstate.islast
if binStep > 0.0
for i = 0 to BINS - 1
float binLevel = rangeLo + binStep * i
float binVol = 0.0
for k = 0 to lookback - 1
if math.abs(close - binLevel) <= binStep
binVol += nz(volume , 0.0)
array.set(volBins, i, binVol)
Each bar within the lookback is assigned to the nearest bin based on its closing price.
3. Point of Control (POC)
The POC is the bin with the highest accumulated volume. It represents the price level where the most trading activity occurred over the lookback period. Markets tend to use the POC as a magnet — price is attracted to it during consolidation and uses it as a reference when transitioning between ranges. The POC is rendered with a distinct highlight color (default orange) to make it immediately identifiable.
4. Value Area Calculation (70% Rule)
The Value Area is determined by a symmetric expansion algorithm. Starting from the POC, the algorithm expands outward one bin at a time, always adding the bin (above or below) that contributes the most volume, until the accumulated volume within the expanding range reaches 70% of total volume:
while vaVol < vaTarget and (vaLow > 0 or vaHigh < BINS - 1)
float addUp = vaHigh < BINS - 1 ? array.get(volBins, vaHigh + 1) : 0.0
float addDn = vaLow > 0 ? array.get(volBins, vaLow - 1) : 0.0
if addUp >= addDn and vaHigh < BINS - 1
vaHigh += 1
vaVol += addUp
else if vaLow > 0
vaLow -= 1
vaVol += addDn
The Value Area High (VAH) and Value Area Low (VAL) define the institutional accumulation zone. Price outside the value area represents a premium (above) or discount (below) relative to the lookback period's fair value.
5. Horizontal Histogram Visualization
Each bin is drawn as a horizontal box extending rightward from the current bar. The box width is proportional to the bin's volume relative to the POC volume — the POC spans the maximum width (50 bars right), and all other bins scale proportionally. Volume amounts are labeled on each bar.
Features
25-Bin Volume Profile Histogram: Full horizontal volume distribution rendered to the right of price with proportional bar widths and volume labels
Point of Control (POC): Highest-volume bin highlighted in a distinct color (default orange) with automatic detection each bar update
Value Area (VAH / VAL): The 70%-volume range shaded in a distinct color, with Value Area High and Low explicitly tracked and displayed in the dashboard
Gradient Bin Coloring: Each non-POC, non-VA bin is colored on a gradient from low volume (nearly transparent) to high volume (full opacity), creating a visual density map
Static Level Plots: All 25 bin levels are plotted as horizontal lines over the lookback window, providing a persistent price level grid even without the boxes visible
Price vs POC Context: The dashboard reports whether price is currently Above POC, Below POC, or At POC
8-Row Dashboard (Top Right): POC price, VA High, VA Low, price vs POC relationship, total volume, lookback period, and version
Watermark: JackOfAllTrades signature at chart center-bottom
Input Parameters
Profile Settings:
Lookback Period: Number of bars to include in the volume accumulation (default: 200, range: 50-500)
Visual Settings:
Show Volume Bins: Toggle the horizontal histogram boxes
Bin Color: Base color for the bin gradient (default: blue)
Bin Width: Border width of histogram boxes (default: 1, range: 0-5)
Highlight POC: Toggle POC highlighting
POC Color: Color for the highest-volume bin (default: orange)
Show Value Area: Toggle the 70%-volume range shading
VA High Color: Color for the Value Area High reference
VA Low Color: Color for the Value Area Low reference
Theme: Auto, Dark, or Light
How to Use This Indicator
Step 1: Identify the Point of Control
The POC is the most important level on the profile. It is the price the market spent the most time trading at — the ultimate fair-value anchor. Price below the POC is at a discount; above is at a premium. Trading setups at the POC during retest often exhibit tight risk/reward.
Step 2: Use Value Area Boundaries for Support and Resistance
The Value Area High and Low are the primary structural boundaries. Price often oscillates within the value area and struggles when attempting to leave it. A close outside the value area with high volume often signals the beginning of a new directional move.
Step 3: Adjust Lookback to Your Trading Style
Shorter lookbacks (50-100 bars) produce a profile of recent price structure, relevant for intraday traders. Longer lookbacks (300-500 bars) produce a macro structural view, relevant for swing traders. The POC and value area boundaries shift as the lookback changes.
Step 4: Watch Price Return to the POC
After price moves away from the POC, it frequently returns to it during low-volume periods. When price is far from the POC and trending, the POC can serve as a magnet target for reversion. When price is oscillating around the POC, it reflects a balanced, two-sided auction.
Indicator Limitations
The profile recalculates only on barstate.islast — it reflects the state at the last confirmed bar. During real-time market hours, the profile is not updating tick-by-tick; it updates each time a bar closes
The volume accumulation assigns each bar to a bin based on closing price, not the intrabar high-low range. This is a simplification — a professional volume profile distributes volume across all prices touched during the bar. The close-based method is computationally feasible within Pine Script's constraints
The 25-bin resolution is fixed. Very large price ranges (e.g., a lookback spanning a major crash) may produce bins too wide to be structurally meaningful. Users should adjust the lookback to keep the range within a reasonable structural period
Instruments with no volume data (some indices, spot forex) will show all zero bins and the profile will not render meaningfully
The histogram boxes are drawn to the right of the current bar. On instruments with extended right-side padding disabled, the boxes may be partially hidden off-chart
Originality Statement
SVC is original in its approach to making volume profile accessible within Pine Script's performance constraints. This indicator is published because:
The barstate.islast performance gate is the key design innovation — it collapses what would otherwise be an O(bars x bins x lookback) computation into a single O(bins x lookback) pass, making a 25-bin volume profile with 500-bar lookback feasible within PulseWire's execution limits
The 70% Value Area algorithm uses a symmetric expansion approach (always adding the larger of the next bin up or down) that correctly implements the standard Volume Profile Value Area methodology
The gradient bin coloring uses color.from_gradient() against the POC volume as the maximum reference, making the visual density map adaptive to the actual volume distribution rather than a fixed scale
The Price vs POC contextual label in the dashboard provides an immediately actionable market context read without requiring the user to visually judge their position relative to the histogram
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Volume profile levels are based on historical volume distribution and represent areas of past interest, not guarantees of future price behavior. The Point of Control and Value Area boundaries can and do shift significantly as the lookback window evolves. Always use proper risk management. The author is not responsible for any trading losses resulting from the use of this indicator.
-Made with passion by jackofalltrades
Indicator

Velox Structure Ribbon [JOAT]Velox Structure Ribbon
Introduction
Velox Structure Ribbon (VSR) is an open-source multi-band trend structure ribbon that uses a volatility-normalized, dynamically-spaced band system to visualize how far price has extended from its trend baseline and in which direction. The ribbon is anchored by a dual SMEMA core — a fast and slow double-smoothed moving average — and radiates six equidistant bands above and below the baseline, with spacing determined by the smoothed average candle range. Each band that price has penetrated adds one point to a 0-3 bull or bear structure score. A 0-100 composite trend strength score combines band penetration with RSI momentum. Volume confirmation and RSI filters are available to sharpen signal quality.
The problem VSR solves is that standard envelopes and Bollinger Bands use fixed or volatility-scaled offsets that can cluster bands too tightly in low-volatility environments and spread them too far in high-volatility ones. VSR normalizes band spacing using the market's own smoothed candle range, meaning band width automatically contracts in quiet markets and expands in active ones. This keeps the structure score meaningful across all conditions: three bands penetrated in a quiet market represents the same degree of extension relative to current volatility as three bands penetrated in a volatile market.
Core Concepts
1. SMEMA Ribbon Core
The ribbon center uses two SMEMA lines — slow (full period, default 20) and fast (half period). The slow SMEMA defines trend direction: sloping upward means the trend is bullish, downward means bearish. The fill between fast and slow creates a visual ribbon that contracts during consolidation and expands during trends:
float smemaSlow = smema(close, smemaLen)
float smemaFast = smema(close, math.max(int(smemaLen / 2), 3))
bool trendUp = smemaSlow > smemaSlow
bool trendDn = smemaSlow < smemaSlow
2. Volatility-Normalized Band Spacing
The step unit for band placement is SMEMA applied to the high-low range over a long smoothing period (default 100 bars). This produces an adaptive measure of the average candle body size. Each of the six bands is placed at integer multiples of this step above and below the slow SMEMA:
float step = smema(high - low, stepSmooth)
float up1 = smemaSlow + step * 1
float up2 = smemaSlow + step * 2
float up3 = smemaSlow + step * 3
Because the step automatically adjusts to market volatility, the bands always represent meaningful structural extensions rather than arbitrary percentage offsets.
3. Bull and Bear Structure Scoring
Each bar, the indicator counts how many upper bands price has broken through (bullish penetration) and how many lower bands (bearish penetration). Each penetrated band adds one point to the respective score:
int bullStr = (above1 ? 1 : 0) + (above2 ? 1 : 0) + (above3 ? 1 : 0)
int bearStr = (below1 ? 1 : 0) + (below2 ? 1 : 0) + (below3 ? 1 : 0)
A score of 0 means price is between the baseline and first band — neutral zone. Score of 1 means first structural extension. Score of 3 means full breakout beyond all three bands in that direction.
4. Composite Trend Strength Score (0-100)
The strength score combines two inputs: the band penetration score converted to a 0-50 scale (each band = 16.7 points) and the RSI deviation from 50 on a 0-50 scale. The combination rewards moves that have both structural extension (price has pushed through multiple bands) and momentum confirmation (RSI is moving away from neutral):
float bandScore = math.min(float(math.max(bullStr, bearStr)) * 16.7, 50.0)
float rsiScore = math.min(math.abs(rsiVal - 50.0), 50.0)
int strScore = int(math.min(bandScore + rsiScore, 100.0))
5. Distance-Based Band Coloring
Each band receives a gradient color whose intensity scales with how far price is from that band relative to its historical range. Bands that price has recently broken through or is pressing against are rendered more vividly. Bands far from price are nearly transparent. This creates a visual heat-map effect showing where structural tension exists:
bandColor(float src, color col) =>
float dist = math.abs(close - src)
float pctNorm = ta.percentile_linear_interpolation(dist, 400, 100)
float colSize = pctNorm > 0 ? dist / pctNorm : 0.0
showBands ? color.from_gradient(colSize, 0, 0.5, color(na), col) : color(na)
Features
Six-Band Structure Grid: Three bands above and three below the slow SMEMA baseline, dynamically spaced by the smoothed candle range
Dual SMEMA Core Ribbon: Fast and slow baseline with gradient fill, colored by trend direction
Trend Direction Diamond: A small diamond marker on the baseline at every trend flip (when the slow SMEMA changes slope direction)
Bull / Bear Structure Score (0-3): Real-time count of penetrated upper or lower bands displayed in signal labels and the dashboard
Composite Strength Score (0-100): Combined band penetration and RSI momentum score with Strong/Moderate/Weak label
RSI Momentum Filter: Optional filter requiring RSI alignment before a signal is confirmed (configurable threshold, default 52)
Volume Filter: Optional filter requiring above-average volume (configurable multiplier, default 1.1x the 20-bar SMA). Auto-disables on volume-free instruments
Signal Labels: Small numeric labels at bull and bear signal bars showing the structure score (1, 2, or 3)
Strength Bar (Bottom Right): A visual bar table showing filled cells proportional to the current bull or bear structure score
Candle Coloring: Bar colors reflect trend direction at reduced opacity
9-Row Dashboard (Top Right): Trend direction, last signal and bars-since count, strength score with label, bull and bear band counts, RSI value, timeframe, and version
Watermark: JackOfAllTrades signature at chart center-bottom
Alerts: Bull signal, bear signal, and trend-flip alertconditions with optional JSON webhook format
Input Parameters
Ribbon Engine:
SMEMA Length: Core period for the slow baseline (default: 20). Fast = L/2
Step Smoothing: SMA period for the candle-range volatility step (default: 100)
Filters:
RSI Length: Momentum confirmation period (default: 14)
RSI Threshold: Minimum RSI for bull signal confirmation (default: 52). Bear mirror = 100 - threshold
Volume Filter: Enable/disable volume confirmation (default: off)
Volume Multiplier: Required volume multiple of the 20-bar SMA (default: 1.1)
Visuals / Dashboard:
Theme: Auto, Dark, or Light
Show Distance Bands: Toggle the six structural bands
Show Core Ribbon: Toggle the fast/slow SMEMA ribbon and fill
Show Signals: Toggle the numeric signal labels
Show Strength Bar: Toggle the bottom-right score visualization
Show Dashboard: Toggle the 9-row information panel
Color Palette: Bull, Bear, and Neutral colors are individually customizable
How to Use This Indicator
Step 1: Read Trend Direction from the Ribbon
When the ribbon is green and sloping upward, the baseline trend is bullish. When red and sloping downward, bearish. A flat ribbon in neutral color indicates a non-trending market.
Step 2: Use Structure Score for Entry Timing
A bull signal fires when price is above the first upper band (score 1+) and the trend slope is upward with RSI and volume confirmation. A score of 2 or 3 indicates deeper structural extension — potentially overextended for entry, better for trailing a position.
Step 3: Watch for Pullbacks to the Ribbon
After a bull signal, price often pulls back toward the ribbon (slow SMEMA) before continuing. Entries from the ribbon during an active bull structure are higher-probability than chasing at the outer bands.
Step 4: Scale Position with Strength Score
A strength score above 70 (labeled Strong) indicates both structural extension and momentum alignment — use for higher conviction. Below 40 (Weak) may indicate a fading move or early-stage structure not worth full position sizing.
Indicator Limitations
The warmup period (SMEMA length x3 or step smoothing + 50, whichever is larger) means the indicator is inactive for the first several dozen bars on any chart
The band spacing adapts to the smoothed candle range with a 100-bar lookback. On instruments with sharp volatility regime changes, the bands may lag behind the new volatility environment for many bars
The volume filter is automatically disabled when volume data is unavailable (e.g., indices, some forex pairs). In those cases, volume confirmation is effectively always true regardless of the toggle setting
Signal labels fire on every bull or bear structure bar — this can be frequent in strongly trending markets. The labels are informational, not entry triggers, and users should apply their own discretion for entry timing
Originality Statement
VSR is original in its use of the SMEMA-smoothed candle range as the band spacing unit. This indicator is published because:
The volatility-normalized step unit (SMEMA of high-low range) is a unique approach to band spacing that differs from standard ATR envelopes, Bollinger Bands (which use standard deviation), and Keltner Channels (which use raw ATR). The SMEMA smoothing produces a more stable, noise-resistant step unit than raw ATR
The 0-3 integer band-penetration scoring is a discrete structural measure that complements continuous oscillators. It quantifies how far price has extended structurally rather than how fast it has moved
The distance-based gradient coloring using percentile normalization creates an adaptive visual heat-map — the same visual logic is computationally novel within the band-coloring approach
The composite strength score combining band penetration with RSI deviation creates a measure that rewards both structural extension and momentum alignment simultaneously
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Band structure scores are based on historical price position relative to smoothed averages and do not predict future price movement. A score of 3 (maximum bullish extension) can increase further or reverse immediately. Always use proper risk management. The author is not responsible for any trading losses resulting from the use of this indicator.
-Made with passion by jackofalltrades
Indicator
