Sigma Channel [JOAT]JOAT Sigma Channel
Introduction
JOAT Sigma Channel is an open-source regression-based channel overlay built to identify the best-fit directional corridor across a search range of candidate windows.
It is designed to show whether price is traveling normally inside a fitted corridor, stretching away from it, reclaiming it, or moving into stress territory.
The problem it solves is model selection.
A fixed-length regression channel can look excellent in one regime and poor in the next.
If the market accelerates, slows down, or shifts its dominant drift horizon, a static window becomes less useful.
Sigma Channel solves that by searching a range of possible windows and selecting the strongest available fit.
That fit becomes the active corridor.
Around it the script builds multiple sigma tiers.
These tiers create a richer price-state map than a single upper and lower band.
The result is a more useful framework for reading acceptance, stretch, reclaim, and exhaustion.
Core Concepts
1. Multi-Window OLS Search
The script evaluates multiple candidate regression windows and scores them by fit quality.
for len = minWindow to maxWindow by stepWindow
= f_model(len)
2. Sigma-Tier Envelope Stack
The fitted centerline is surrounded by inner, core, outer, and stress layers.
3. Slope and Quality Diagnostics
The chosen model exposes both slope and fit quality.
4. Reclaim and Acceptance States
The script identifies when price reclaims or accepts back inside the corridor after extension.
5. Stress-State Shading
The most extreme statistical layer is visually emphasized.
6. Forward Projection
The active model projects forward to keep the corridor useful at the right edge.
7. Residual Awareness
Residual behavior helps judge whether the active model remains representative.
8. Gradient Candle Context
Bar coloring transitions with the current statistical state.
Features
Adaptive regression search: scans multiple windows instead of using one fixed length
Inner, core, outer, and stress bands: multiple sigma tiers for normal and abnormal travel
Slope-aware corridor logic: distinguishes positive and negative drift
Reclaim and acceptance events: return-to-channel behavior is identified
Stress shading: abnormal statistical extension is highlighted
Forward projection: the active corridor extends to the chart edge
Gradient candle tinting: bar color reflects the current z-state
Dashboard: slope, quality, window, and deviation state are summarized
Input Parameters
Model Search:
Minimum Window
Maximum Window
Window Step
Minimum R-Squared
Projection Bars
Deviation Envelope:
Inner Sigma
Core Sigma
Outer Sigma
Stress Sigma
Filter Stack / Visual System:
Bias EMA
ATR Length
Momentum RSI
Use EMA Bias Gate
Use RSI Gate
Use Volume Gate
Tint Bars
Show Projection
Show Dashboard
How to Use This Indicator
Step 1: Check the active slope and whether the corridor is upward, downward, or balanced.
Step 2: Check fit quality before trusting the active statistical path.
Step 3: Read whether price is inside the core corridor, at the outer layer, or in stress territory.
Step 4: Watch reclaims back into the channel after extension.
Step 5: Use the projection to organize the near-future chart space.
Indicator Limitations
The selected best-fit window can change as the market evolves
Linear regression becomes less representative in strongly nonlinear markets
Statistical extension does not guarantee immediate reversal
The indicator measures deviation from a model, not directional certainty
Originality Statement
This script is original in the way it combines adaptive regression selection, multi-tier sigma structure, reclaim logic, stress-state shading, and forward projection into one corridor framework.
The goal is not just to draw a regression channel.
The goal is to keep the active model responsive while preserving statistical context.
Disclaimer
This indicator is provided for educational and informational purposes only.
It is not financial advice.
Regression fit and statistical deviation do not predict future price with certainty.
Markets can remain extended or break away from the active fit entirely.
Best Use Cases
Reading whether price is behaving normally inside a fitted directional corridor
Identifying statistical stretch and stress states
Watching for reclaim behavior after extension
Combining statistical deviation with separate structure or liquidity analysis
Interpretation Notes
The channel should be trusted more when fit quality is stronger and the slope is clear.
Core travel is generally more normal than outer-band travel.
Stress states are especially useful when they coincide with separate structural or participation warnings.
The projection should be read as a continuation of the current best-fit model, not as a forecast guarantee.
Publication Notes
This script is intended to be published with a clean chart where the corridor, the active slope, and at least one reclaim or extension state are obvious.
The example chart should help the viewer understand how the band hierarchy works.
Avoid combining it with unrelated overlays in the publication image.
-Made with passion by jackofalltrades
Indicator

Candle DNA Morphology | AnonycryptousCandle DNA Morphology | Anonycryptous
Description & user manual
Why is this indicator different:
Most candle analysis tools work with names. They look at a candle and call it an engulfing, a hammer, a doji, a shooting star. They compare shape against a fixed template and fire a signal when the match is close enough. The problem is that names are approximations. A hammer in a trending market is not the same as a hammer at a structural level with elevated volume. A name cannot capture that. A fixed template cannot either.
Candle DNA Morphology works differently.
It does not use names. It does not use templates. It compares the current candle to every historical candle within a configurable lookback window and finds the one that is mathematically closest — across up to eight normalized dimensions simultaneously. Body size, wick proportions, body position within the range, relative volume, candle size relative to recent volatility, trend alignment, and structural context. Then it tells you what happened after that historical candle, directly on the chart, with a single marker you can hover.
Other tools that use candle similarity show you statistics. Continuation rates. Reversal percentages. Tables to read and interpret. You still have to decide what the numbers mean and whether they matter right now.
Candle DNA Morphology does not show you statistics. It shows you a signal — the exact historical candle that matched, marked on the chart, with the date, the score, the direction, the R value, the percentage move, and the price move of what followed. No table to interpret. No calculation required. The information is in the hover.
The score tells you how close the match was. The tier tells you how rare it is. The color tells you the direction. Everything else is in the tooltip.
Important notice
Candle DNA Morphology generates signals based on historical pattern similarity and price behavior.
These signals are not financial advice.
They do not predict the future.
They do not guarantee profitability.
The outcome values shown — R, percentage, and price — are historical measurements from the matched candle in the past. They reflect what happened then, on that instrument, at that price level. The market may behave differently now. Similar candles can produce different results. These values are context, not certainty.
All trading decisions are made entirely by the user.
Always manage your own risk. Always apply your own judgment.
1. Overview
Candle DNA Morphology is a candle fingerprint matching indicator built around the mathematical similarity between the current candle and historical ones — and what those historical candles preceded.
What it includes:
- Up to 8-dimensional candle fingerprint matching using Euclidean distance
- Configurable lookback window from 50 to 1000 bars
- Three signal quality tiers: standard, elite, and ultra
- Hoverable triangle markers on signal bars with full match details in the tooltip
- Diamond marker and vertical line on the exact historical matched candle
- Configurable cooldown between signals to prevent clustering
- Signal mode selector: current bar, match bar, or both
- Dynamic score normalization — score stays 0-100 regardless of how many dimensions are active
- Vertical signal line and background glow on qualifying bars
- Live dashboard with score bar, tier, bias, match date, outcome in R / percentage / price, cooldown countdown, active dimensions, and ATR
- All times displayed in the timezone you select in the dashboard settings
- Four alerts: bull match, bear match, elite match (90+), ultra match (95+)
2. How the fingerprint works
Every candle is described by a set of normalized values between 0 and 1. These values capture the shape and context of the candle without using price or time units — which is what makes the engine self-calibrating across instruments and timeframes.
The five core dimensions are always active:
Body ratio. The size of the body relative to the total candle range. A full-body candle scores near 1. A doji scores near 0.
Upper wick. The upper wick as a proportion of the total range. A long upper wick scores high. A candle with no upper wick scores 0.
Lower wick. Same logic for the lower wick.
Body position. Where the body sits within the range — 0 is at the bottom, 1 is at the top. A bullish candle with a close near the high scores near 1. A bearish candle with a close near the low scores near 0.
Relative volume. Volume divided by the 20-bar average, capped at 3x and normalized. A spike at 2x average scores higher than a quiet bar at 0.8x.
Three optional dimensions can be enabled independently:
Atr percentile (dimension 6). How large the current candle is relative to recent volatility. Measures the candle range against the 14-bar ATR, normalized to a 0-2x cap. A large candle matches better with historically large candles.
Trend alignment (dimension 7). How far the close sits above or below EMA 21, normalized to the ATR. A bullish candle well above the EMA matches better with historical bullish candles that were also above the EMA.
Candle context (dimension 8). The relationship between the current candle and the previous one. Inside bars score 0. Outside bars score 1. Normal bars score 0.5. This dimension helps the engine recognize structural setups like inside bar breakouts.
3. Scoring and tiers
Similarity is measured using Euclidean distance — the straight-line distance between two candles in multi-dimensional space. The closer two candles are in this space, the more similar they are.
The maximum possible distance scales automatically with the number of active dimensions, so the score always ranges from 0 to 100 regardless of configuration. A score of 100 would mean a perfect match across all active dimensions. A score of 70 means a strong structural similarity. A score of 95 or above is exceptionally rare.
Three tiers determine how signals are displayed:
Standard (70-89). Green for bull, red for bear. The match is meaningful but not uncommon.
Elite (90-94). Gold marker with a star prefix ★. The match is close enough to be notable. These appear infrequently.
Ultra (95+). Cyan marker with a diamond prefix ◈. A near-identical historical candle was found. Very rare. When one fires, it is worth attention.
4. Understanding the signal
When a signal fires, two things appear on the chart depending on your signal mode setting.
A triangle on the current bar points in the direction the market moved after the historical match — up for a bullish outcome, down for a bearish one. Hovering the triangle with your cursor or S-Pen shows the full match details: the date and time of the historical candle, the score, the tier, the bias, the outcome in R, and the R value.
When a signal fires, two dotted lines and a vertical connector appear on the chart. The first dotted line runs horizontally from the signal bar close — this is the entry reference level, the price from which all R, percentage, and dollar measurements are calculated. The second dotted line shows the target level — where the market would reach if the historical outcome repeats. A vertical connector at the end of the forward window closes the structure. All three lines run exactly as many bars as your forward outcome setting.
The target level is calculated using the current ATR, not the historical ATR from the matched candle. This makes it relevant to the current market conditions. Hovering the target line shows both values — the target using the current ATR and the target using the historical ATR — so you can see how much volatility has changed between then and now. If the current ATR is significantly higher than the historical ATR, the target is further away than it was in the original setup. If it is lower, the target is closer.
A diamond and a vertical line on the historical matched candle shows you exactly which bar was used as the reference. The line runs through the full range of that candle so there is no ambiguity about which bar matched. The color follows the signal tier.
In addition to the dotted lines, the indicator can draw historical projection candles to the right of the signal bar. This feature is off by default and can be enabled in the visuals settings. When enabled, candles appear to the right of the signal bar showing the exact OHLC of the bars that followed the historical matched candle. Each candle has a body and centered wicks, drawn in the tier color of the signal. They scale correctly with chart zoom. A small label above the first candle reads "Historical projection" to make it immediately clear that these are historical bars, not predictions. The number of projection candles follows your forward outcome setting. Body transparency and wick transparency are independently configurable in settings.
The bias shown in the dashboard and the tooltip is the direction the market moved after the matched candle — not a prediction of what will happen now. It is historical context, not a guarantee.
All times shown in this indicator use the timezone you select in the dashboard settings. The default is UTC. Set it to your local timezone — for example UTC+2 for Amsterdam, UTC-4 for New York, UTC+9 for Tokyo — and all match times will display in your local time automatically.
5. Understanding the outcome values
The dashboard and tooltip show three outcome measurements for the historical matched candle. All three describe the same move — the price action in the bars following that historical candle — expressed in different units.
Outcome (R). How far price moved after the matched candle, expressed as a multiple of the ATR at that historical bar. This is the primary measurement. It is instrument-independent and works the same on BTC, SOL, MNQ, or any other asset. A value of +2.4R means price moved 2.4 times the ATR upward in the forward window.
Outcome (%). The same move expressed as a percentage of the close price at the matched candle. This gives a more intuitive sense of the magnitude for traders who think in percentage terms.
Outcome (price). The same move expressed in the currency of the instrument. This is the raw price distance the market covered — for example, $1,075 on Bitcoin or $0.87 on SOL. This value is calculated using the ATR and close price at the historical match bar, not at the current price.
The target line on the chart uses the current ATR rather than the historical ATR. This is intentional — the current ATR reflects how the market is moving right now, making the projected target more relevant to your actual trade. The historical ATR is still shown in the target line tooltip for reference, so you can see whether volatility has expanded or contracted since the original setup occurred. A large difference between the two ATR values means the market is in a different volatility regime than it was at the time of the match.
An important note on the price value: this reflects the historical move at the time and price of the matched candle. If Bitcoin was at 60,000 when the match occurred and is now at 78,000, the same R move produces a larger dollar value today than it did then. The price outcome is historical context — it shows what that candle type led to in dollar terms at that moment, not what the current setup will produce now.
This is not your personal risk-to-reward ratio. The R value gives you the historical move size. Your stop loss placement determines your actual R:R.
6. Bias and cooldown
The bias shown in the dashboard reflects the outcome direction of the current best match. It shows bull when the matched historical candle was followed by an upward move, and bear when it was followed by a downward move.
Bias changes when a new bar closes and the engine finds a different best match with a different historical outcome direction, or when the cooldown expires and a new signal fires pointing in a new direction.
During cooldown, the dashboard shows — wait. The last match date and all three outcome values remain visible. No new signal fires until the cooldown bar count has elapsed. The cooldown countdown shows how many bars remain before the next signal is allowed, or ready when it can fire freely.
Cooldown prevents signal clusters from forming on consecutive bars where the same setup repeats. On faster timeframes with many morphologically similar candles, a cooldown of 15 bars or more is strongly recommended.
7. Self-calibration
All fingerprint dimensions are normalized to values between 0 and 1. Volume is measured relative to its own 20-bar average. Candle size is measured relative to the ATR. Trend alignment is measured in ATR units. There are no fixed price thresholds anywhere in the engine.
This means the indicator adapts automatically to different instruments and timeframes. A BTC candle and an MNQ candle with the same proportional shape, same relative volume, and same relationship to their respective EMAs will produce the same fingerprint score — even though one trades at 78,000 and the other at 20,000.
When switching instruments, only the min match score typically needs a small adjustment. SOL and other volatile assets produce more morphological variation, so a slightly lower score threshold (75-80) often works better. More structured instruments like futures perform well at 85-90.
8. Settings guide
8.1 Match engine
Lookback window (bars). How many historical bars to scan for fingerprint matches. Range: 50-1000. Recommended: 500 on 1m-5m charts, 1000 on 15m and above. A larger window finds better matches but takes longer on lower timeframes.
Min match score (0-100). The minimum similarity score required to fire a signal. 70-79 is standard, 80-89 is strong, 90-94 is elite, 95+ is ultra. Start at 85 and adjust from there.
Cooldown between signals (bars). Minimum bars between signals. On a 5m chart, 15 bars equals 75 minutes. On a 1H chart, 15 bars equals 15 hours. Lower values produce more signals. Higher values enforce a minimum spacing between setups.
Dimension 6 — Atr percentile. Adds candle size context relative to recent volatility. Recommended: on.
Dimension 7 — Trend alignment. Adds EMA 21 directional context. Recommended: on.
Dimension 8 — Candle context. Adds inside/outside bar structural context. Recommended: on.
8.2 Outcome filter
Forward outcome (bars). How many bars after the historical match are used to measure the resulting move. Match this to your typical trade duration. On a 5m chart with 6 bars, the engine looks at 30 minutes of forward price action to determine the outcome direction and magnitude.
Min outcome move (ATR x). The historical match only qualifies if the resulting move exceeded this ATR multiple within the forward window. Filters out matches where the historical candle led to no meaningful move. Recommended: 1.0-2.0.
8.3 Visuals
Signal mode. Current bar only shows only the triangle. Match bar only shows only the diamond and vertical line on the historical candle. Both shows both simultaneously.
Show score on marker. When on, the triangle displays the score as text. When off, the triangle is clean. Hover always shows the full details regardless.
Signal bar background. Subtle glow on the signal bar in the tier color.
Vertical signal line. A faint vertical box through the signal bar. Useful for identifying signal bars when zoomed out.
Timezone. Select your local timezone from the dropdown. All match times in the dashboard and tooltips display in this timezone. Default is UTC. Amsterdam = UTC+2, London = UTC+1 (summer) or UTC, New York = UTC-4 (summer), Tokyo = UTC+9.
8.4 Dashboard
Score bar — visual meter 0-100 in tier color.
Tier — standard, ★ elite (90+), or ◈ ultra (95+).
Bias — ▲ bull or ▼ bear, or — wait during cooldown.
Match date — date and time of the historical matched candle in your selected timezone.
Outcome (R) — price move after the match in ATR multiples with forward bar count.
Outcome (%) — same move as a percentage of the historical close price.
Outcome (price) — same move in currency units at the historical price level.
Lookback — current lookback window setting.
Min score — current minimum score setting.
Cooldown — bars remaining until next signal, or ready.
Dimensions — how many dimensions are active and which ones (ATR, EMA, CTX).
ATR (14) — current ATR value.
9. Recommended starting settings
For 1m-5m scalping:
Lookback 500, min score 85, cooldown 15 bars, forward outcome 3 bars, min outcome move 1.0.
For 15m-1H:
Lookback 1000, min score 88, cooldown 8 bars, forward outcome 6 bars, min outcome move 1.5.
For 4H and above:
Lookback 1000, min score 90, cooldown 5 bars, forward outcome 4 bars, min outcome move 2.0.
10. How to use
Load the indicator and set signal mode to both. This gives you the triangle on the current signal bar and the diamond with border box on the historical matched candle simultaneously.
When a signal fires, hover the triangle with your cursor or S-Pen. Read the match date (UTC), score, bias, and outcome values. Then locate the diamond on the chart — the bordered box marks exactly which candle was matched. Look at what followed it on the chart. That is your reference.
The three outcome values give you the same historical move in three different units. Use whichever is most natural for how you think about size. The R value is instrument-independent. The percentage gives quick context. The price value shows the raw historical distance.
Watch the cooldown counter in the dashboard. When it shows ready, the next qualifying signal will fire without restriction. When it shows a bar count, the engine is waiting before it can fire again.
If you see too many signals, raise the min match score or increase the cooldown. If you see too few, lower the min outcome move or reduce the min score.
Candle DNA Morphology works best as a confluence tool. It tells you what the current candle morphology historically preceded. Your other indicators — levels, sessions, volume, trend — confirm whether the context justifies acting on it.
11. Disclaimer
This indicator is provided for educational and informational purposes only. Nothing in this document constitutes financial advice or any form of recommendation. Trading financial instruments involves substantial risk of loss. Past performance is not indicative of future results. You may lose all of your invested capital.
Anonycryptous accepts no responsibility or liability for any losses incurred as a result of using this indicator.
Indicator

Trendline Retest Planner [AGPro Series]Trendline Retest Planner
🧠 Core Idea
Is the active trendline retest constructive enough to keep the setup under review, or is it starting to fail?
📌 Overview / What it does
Trendline Retest Planner is a chart-first decision tool for traders who review price behavior around active support and resistance trendline retests.
Instead of drawing many trendlines or flagging every break, the script focuses on one active trendline retest context at a time. It measures line age, touch count, retest depth, close response, and volume support, then converts that evidence into a 0-100 Retest Score and a clear next-action state.
The script produces an active trendline, retest pocket, hold/fail labels, invalidation edge, target path, alerts, and a compact AGPro planning panel. It does not predict price movement, automate execution, or provide guaranteed outcomes.
🎯 Purpose & Design Philosophy
This script was built to fill the gap between auto-trendline drawing and practical retest planning.
Many tools can draw diagonals or detect a break. The harder question is what to do after price returns to the line: is the retest holding, weakening, failing, or still waiting for confirmation?
Trendline Retest Planner supports a decision workflow: identify the active retest, read the score, locate the invalidation edge, compare the target path, and decide what deserves review next.
⚡ Why This Script Is Different
Most trendline tools focus on drawing many lines, ranking confluence, or detecting trendline breaks.
This script does NOT clone Auto Trendline Break Quality, Auto Trendlines MTF - Break/Retest, Trendline Confluence Map, Break-Retest Quality, Structure Retest Planner, Swing Retest Quality, or a generic support/resistance zone map.
Instead, it narrows the workflow to one active support or resistance trendline retest and evaluates whether that retest is constructive or failing. The main output is not a buy or sell signal. It is a decision state: READY, MONITOR, FAILING, INVALIDATED, WATCH, WAIT, or SCAN.
⚙️ Methodology
1. Context Detection
The script builds the latest support and resistance trendline candidates from confirmed swing pivots, then selects the nearest valid retest context.
2. Reference Mapping
It maps the active trendline, a retest pocket around the line, an invalidation edge, and a forward target path.
3. Reaction Evaluation
The 0-100 model scores line age, touch count, retest depth, close response, and volume support.
4. Visual Output
The chart shows the active planning objects, compact state labels, and a clean AGPro decision panel.
🗺️ How to Read the Chart
Trendline = the active support or resistance line being evaluated.
Retest Pocket = the ATR-based area around the trendline where a retest is considered active.
Invalidation Edge = the planning reference where the active retest context is considered broken.
Target Path = a forward guide based on the trendline-to-risk distance.
Labels = compact TEST, READY, MONITOR, WEAK, INVALID, PATH, and sparse context labels.
Colors = teal marks support-side retest context, pink marks resistance-side retest context, amber marks caution, indigo marks monitoring/follow-through, and red marks invalidation.
Panel = the AGPro panel summarizes Trendline Side, Retest Score, Hold State, Risk Edge, and Action.
🚦 Signals & States
• READY → the retest is active, holding on the correct side, and the score is strong enough for structured review.
• MONITOR → the retest is developing, but confirmation or score quality is still incomplete.
• FAILING → price touched the pocket, but the response is weak or on the wrong side.
• INVALIDATED → price crossed the invalidation edge and the active context should be rebuilt.
• WATCH → price is approaching the trendline pocket.
• WAIT → a valid trendline exists, but price is not close enough for useful retest review.
• SCAN → no valid trendline context is active yet.
🔔 Alerts Logic
Alerts trigger when price touches the active retest pocket, when READY state appears, when MONITOR state appears, when a failing retest is detected, when the invalidation edge is crossed, and when follow-through appears after an active retest.
Alerts are attention markers only. They are not trade instructions, automated strategy commands, or outcome promises.
🧩 Confluence Logic
The strongest context appears when the active line is fresh enough, has enough touches, retests with controlled depth, closes back on the correct side, and receives supportive relative volume.
When these components conflict, the panel moves toward MONITOR, FAILING, WATCH, WAIT, or INVALIDATED.
📊 When to Use
• Trendline support retests during constructive pullbacks
• Trendline resistance retests during bearish continuation attempts
• Price-action review after a diagonal support or resistance line is already visible
• Retest planning where invalidation and target path matter
• Liquid markets where pivots, candles, and volume behavior are readable
⚠️ When NOT to Use
• Very low-liquidity symbols with irregular candles
• Extremely noisy micro-timeframes
• News-driven spikes where trendline geometry becomes distorted
• Markets where swing pivots are too compressed to form useful lines
• Situations where the user expects a signal-only or auto-trading tool
🎛️ Key Inputs
• Trendline Side → selects Auto, Support Retest, or Resistance Retest.
• Trendline Pivot Length → controls how confirmed swing anchors are detected.
• Max Trendline Age → controls how old a trendline can be before it is ignored.
• Touch Count Lookback → controls how extra line touches are counted.
• Sensitivity → adjusts retest pocket width and activation distance.
• READY Score → sets the score threshold for stronger review states.
• Label and Panel Font Size → controls chart-label and panel readability.
• Panel Location and Theme → adjusts the AGPro panel layout.
🖥️ Interface & Visual Design
The interface is designed to stay chart-first and decision-led.
The active trendline is the main reference. The retest pocket is drawn around that line with centered text so the chart stays readable. The invalidation edge and target path explain where the planning context weakens and what forward room is being mapped.
The AGPro panel uses a merged blue title row and five compact rows so the user can read side, score, hold state, risk edge, and action quickly.
🧪 Practical Usage Workflow
1. Read the panel state and Retest Score.
2. Check whether price is approaching or touching the retest pocket.
3. Compare current price with the invalidation edge.
4. Review whether the label says TEST, READY, MONITOR, WEAK, INVALID, or PATH.
5. Confirm the broader market context before making any decision.
🔍 Interpretation Guidelines
Think in terms of retest quality, not prediction.
A higher score means multiple retest components align inside the script's rule set. A weaker score means the line may be too old, the retest may be too shallow, too deep, missing a constructive close, or lacking participation.
The script helps organize the review process. It does not replace judgment.
🚫 What This Script Is NOT
• Not a prediction engine
• Not financial advice
• Not an auto-trading system
• Not a guaranteed signal tool
• Not a broad auto-trendline map
• Not a trendline confluence scanner
• Not a break-and-retest scanner
• Not a generic support/resistance zone map
• Not an order block, FVG, or supply/demand tool
⚠️ Limitations & Transparency
• Pivot-based trendlines appear only after pivots are confirmed.
• Scores can vary across symbols, sessions, and timeframes.
• Volume scoring depends on exchange-provided volume data.
• Fast volatility can cross a trendline before a clean retest can be measured.
• In Live Updating mode, active-bar values can change before the bar closes.
🧠 Market Context Notes
Trendline retests are easiest to interpret when liquidity, volatility, and swing structure are readable.
A trendline touch is not enough by itself. Line quality, response, invalidation distance, and target path all matter.
🧾 Use Case Examples
When price returns to an upward support trendline and closes back above the pocket with a high score, the panel may move toward READY.
When price touches a downward resistance trendline but cannot close back below it, the planner may move toward FAILING or INVALIDATED.
When price is near the line but has not touched the pocket yet, the panel can stay in WATCH or WAIT.
🧱 System Philosophy
Trendline Retest Planner follows the AGPro decision-engine approach: identify context, score quality, map risk, show the next action, and keep the chart readable.
It is designed to help traders evaluate a specific planning question instead of adding another generic signal layer.
🔐 Non-Promise Statement
No score, label, alert, or chart object guarantees any market outcome.
The script organizes retest context and highlights conditions for review. It does not provide certainty.
📉 Risk Disclosure
Trading involves risk.
Users remain responsible for their own decisions, position sizing, execution, and risk management.
This script is for educational and analytical purposes only and does not provide financial advice.
📚 Educational Note
Use the planner as a structured reading layer: trendline context first, retest quality second, invalidation and target path third, broader market context always.
Indicator

Sortino Ratio Oscillator [MarkitTick]💡 The Sortino Ratio Oscillator introduces a sophisticated, risk-adjusted performance metric typically reserved for portfolio analysis, adapting it into a highly responsive momentum oscillator. By strictly penalizing downside volatility while rewarding upside momentum, it provides a much clearer picture of market strength compared to traditional oscillators that treat all volatility equally.
✨ Originality and Utility
Standard momentum indicators measure the velocity of price movement based on general variance. However, traditional models penalize both upside and downside volatility. A massive bullish breakout creates "high volatility," which standard indicators often misinterpret as an overextended or risky market condition.
This script resolves that inherent flaw by migrating the academic Sortino Ratio into a technical trading framework. It isolates "bad" volatility (price drops) from "good" volatility (price gains). The utility here is immense: traders can identify trends where the price action is genuinely supported by positive risk-adjusted returns, filtering out noisy markets where the downside deviation is too high. Furthermore, this tool features an integrated divergence detection engine, dynamic histogram coloring, and built-in webhook alert formatting, making it a comprehensive suite for algorithmic and discretionary traders alike.
🔬 Methodology and Concepts
The core engine of this indicator relies on continuously assessing the bar-to-bar percentage return of the asset.
First, it calculates the raw percentage return between the current close and the previous close.
Next, it isolates the downside returns. If a return is positive, it is ignored for the risk calculation (treated as zero). If it is negative, it is squared to emphasize larger drawdowns, following standard variance practices.
The script then computes the Simple Moving Average of these squared negative returns over a user-defined lookback window, calculating the square root to determine the final Downside Deviation.
Simultaneously, the Simple Moving Average of the raw returns is calculated to find the mean return over the same period.
The final Sortino Ratio is produced by dividing the mean return by the downside deviation.
To smooth the output and generate actionable crossovers, a secondary Signal Line is derived by applying an average to the raw Sortino Ratio.
To enhance the analytical depth, the script incorporates a robust divergence engine that scans for pivot highs and lows over a customizable lookback window. By comparing price action pivots with the oscillator's momentum peaks and troughs, it systematically maps out both regular and hidden divergences.
🎨 Visual Guide
The visual presentation is meticulously structured to provide instant clarity on risk-adjusted momentum states.
• The Sortino Histogram
The core oscillator is plotted as a multi-colored histogram. It utilizes a four-state coloring system to indicate momentum shifts:
Solid Bull Color: The ratio is above zero and rising, indicating accelerating positive risk-adjusted returns.
Transparent Bull Color: The ratio is above zero but falling, suggesting positive momentum is decelerating.
Solid Bear Color: The ratio is below zero and falling, indicating accelerating downside risk.
Transparent Bear Color: The ratio is below zero but rising, showing that downside risk is waning.
• Signal Line and Cloud Fill
A highlighted Signal Line tracks the moving average of the Sortino Ratio. The space between the Sortino histogram and the Signal Line is filled with a dynamic cloud, helping traders easily spot shifts in immediate trend strength.
• Threshold Lines
Dashed lines represent the Overbought and Oversold thresholds. A solid gray line marks the Zero Level, acting as the primary baseline for positive versus negative risk-adjusted states.
• Divergence Mapping
Regular Bullish (RB): Displayed as a solid line connecting price lows to oscillator lows, complete with a label below the candle.
Hidden Bullish (HB): Displayed as a dashed line, indicating trend continuation.
Regular Bearish (RD): Displayed as a solid line connecting price highs to oscillator highs.
Hidden Bearish (HD): Displayed as a dashed line.
• Candle Coloring
When enabled, the price chart's candles are painted to match the four-state color logic of the Sortino Histogram, linking the oscillator's data directly to the price action on the main chart.
📖 How to Use
Traders can interpret the Sortino Ratio Oscillator through several distinct frameworks depending on their trading style.
• Zero-Line Crossovers
A baseline shift occurs when the histogram crosses the zero line. A cross into positive territory confirms that the average returns now outweigh the downside deviation, signaling a structurally sound bullish environment. Conversely, a drop below zero warns that downside volatility is dominating the asset's behavior.
• Signal Line Interactions
Watch for the histogram to cross the Signal Line. When the Sortino Ratio spikes above its signal line, momentum is expanding. When it crosses below, it often precedes a consolidation or a reversal, as highlighted by the cloud fill changing colors.
• Extremes and Reversals
The Overbought and Oversold threshold lines act as exhaustion markers. An asset sustaining a Sortino Ratio above the Overbought level is exhibiting unusually high, unpenalized upside movement. While strong, traders should watch for the histogram to peak and cross back below the Signal Line as an early warning of a pullback.
• Trading Divergences
Divergences are perhaps the most powerful signals generated by this tool. Look for Regular Bullish Divergences when the price makes a lower low, but the Sortino Ratio makes a higher low. This indicates that despite the price drop, the underlying downside volatility is shrinking relative to the mean return, hinting at a bottom. Hidden Divergences are excellent for trading pullbacks in the direction of the macro trend.
⚙️ Inputs and Settings
• Sortino Settings
Lookback Length: Defines the period used to calculate the mean return and downside deviation. A shorter length is highly reactive, while a longer length provides macroscopic trend stability.
Signal Length: Adjusts the smoothness of the Signal Line.
Overbought / Oversold Levels: Customizes the threshold lines for extreme readings.
• Candle Coloring
A simple toggle to enable or disable the dynamic coloring of the main chart price candles based on the oscillator's state.
• Divergence Settings
Enable Divergence: Master toggle for the divergence engine.
Show Regular / Hidden: Independent toggles to filter specific divergence types.
Pivot Lookback Left / Right: Determines the strictness of the pivot point detection. Higher values require more significant peaks and troughs to form a valid pivot, filtering out noise.
• Webhook Action Names
Customizable string inputs allowing algorithmic traders to map specific script events directly to JSON payloads for automated execution platforms.
🔍 Deconstruction of the Underlying Scientific and Academic Framework
The Sortino Ratio, developed by Dr. Frank A. Sortino, is a vital modification of the Sharpe Ratio. In Modern Portfolio Theory, the Sharpe Ratio evaluates the performance of an investment by adjusting for its risk, defined universally as the standard deviation of its returns. However, standard deviation measures total volatility, treating an unexpected positive gain exactly the same as a negative loss.
This oscillator resolves that mathematical paradox by isolating downside deviation. The scientific framework dictates that a minimum acceptable return—in this script's case, zero—must be established. Only returns falling strictly below this threshold are aggregated and squared to calculate the downside variance. By exclusively measuring the standard deviation of negative asset returns, the formula effectively removes the penalty for upside volatility.
In a purely academic sense, a high Sortino Ratio mathematically proves that the asset is generating its returns without suffering significant, erratic drawdowns. Translated into technical analysis, when the indicator rises, it mathematically proves that the ratio of upward momentum relative to downward variance is expanding. This makes it an incredibly robust statistical measure, completely immune to the standard look-around bias of typical mathematical oscillators that collapse under the weight of sudden, positive price shocks.
⚠️ Disclaimer
All provided scripts and indicators are strictly for educational exploration and must not be interpreted as financial advice or a recommendation to execute trades. I expressly disclaim all liability for any financial losses or damages that may result, directly or indirectly, from the reliance on or application of these tools. Market participation carries inherent risk where past performance never guarantees future returns, leaving all investment decisions and due diligence solely at your own discretion. Indicator

AI UltraTrend X Pro V1The AI UltraTrend X Pro V1 is a high-performance, signal-based indicator engineered to identify explosive trend reversals while aggressively filtering out sideways market noise. Built specifically to handle high-volatility environments like BankNifty, this tool excels at capturing large point moves by combining institutional flow tracking with advanced price-action breakouts.
Key Features
Multi-Segment Mastery: While optimized for the fast-paced nature of BankNifty, the logic is universally applicable across Equity, Forex, Commodities, and Crypto.
Optimized for 3m+ Timeframes: Designed for the 3-minute duration and above, providing a perfect balance between early entries and noise reduction.
Hybrid Execution Logic: Unlike standard indicators that rely solely on crossovers, this script uses a dual-trigger system—line crosses and volatility-backed breakouts—ensuring you never miss a gap-up or a sudden trend explosion.
Intraday & Swing Flexibility: Seamlessly transitions between aggressive Intraday scalping and Positional trend following. The indicator maintains its state, allowing users to carry trades or square off at the end of the session based on their own risk profile.
Advanced Anti-Chop Shield: Features a built-in Volume & Volatility filter that identifies "dead zones" (gray signal areas) to prevent the "multiple entries/exits" common in flat markets.
Dynamic Trailing Stop-Loss: Plots a real-time, ATR-based trailing exit (Yellow Line) that locks in profits while giving the trend enough "breathing room" to survive minor pullbacks.
How to Use
Enter CE: Triggered when the signal turns Green and price breaks recent resistance.
Enter PE: Triggered when the signal turns Red and price breaks recent support.
Stay with the Trend: The background remains color-coded (Green/Red) as long as the trend is healthy.
Exit: Close your position when the signal label flips.
Best Settings
Timeframe: 3m, 5m, or 15m.
Chart: Works best on standard Candlesticks or Heikin Ashi for smoother trend following. Indicator

Caldera Relative Pressure [JOAT]Caldera Relative Pressure
Introduction
Caldera Relative Pressure is an open-source effort-versus-result oscillator designed to measure whether price movement is being supported by participation, directional efficiency, and close location within the bar. It is built to distinguish clean directional drive from absorption, exhaustion, and two-way rotation.
The problem this script solves is that raw price movement does not explain whether a move is efficient, forced, rejected, or fading. A wide candle on low participation is not the same as a wide candle with expanding participation and strong close location. Caldera converts candle anatomy, relative volume, range behavior, and baseline context into a structured pressure model that is easier to read in real time.
Core Concepts
1. Effort-Versus-Result Framework
The script blends three weighted components:
Effort: candle body and directional spread relative to true range
Result: directional efficiency relative to ATR
Location: where the bar closes inside its own range, adjusted by wick pressure
Those three parts are multiplied by relative volume so that quiet moves and committed moves do not receive the same score.
2. Directional Drive Detection
Bull and bear drive states require a sufficiently large composite pressure reading, positive spread between the composite and its signal line, and close location agreement. This keeps small or conflicted moves from being treated as decisive tape control.
3. Absorption Detection
Absorption is identified by unusually strong volume combined with limited body progress and asymmetric wick behavior. In practical terms, that means participation increased but result did not expand proportionally. This is often a useful clue that one side is meeting aggressive pressure with passive liquidity.
4. Exhaustion Detection
The script also tracks exhaustion. It compares the current pressure state with recent pressure extremes and short-term momentum fade. A move can still be directionally positive or negative while simultaneously losing efficiency.
5. Multi-Layer Pressure Visualization
The pane includes a histogram, composite line, signal line, drive quality line, balance line, participation band, efficiency band, location band, rotation ribbon, and reference ladders. These are separate on purpose:
The histogram shows raw directional pressure
The composite and signal lines show state and rotation
Drive quality shows how healthy the move is
Participation, efficiency, and location bands show what is contributing to the reading
Features
Composite pressure engine: Candle anatomy, ATR efficiency, location, and relative participation
Bull and bear drive states: Measures directional initiative
Bull and bear absorption states: Flags high-effort / low-result behavior
Bull and bear exhaustion states: Flags fading pressure after prior extremes
Baseline context filter: Can require price to align with a directional baseline
Drive quality and balance lines: Separate force from quality
Participation, efficiency, and location bands: Show what is driving the current reading
Rotation ribbon: Highlights positive and negative carry
Dashboard summary: State, bias, strength, regime, context, participation, quality, balance, rotation, and compression
Input Parameters
Core Engine:
Relative Volume Length
Range Normalization Length
Baseline Context Length
Signal Smoothing
Pressure Model:
Effort Weight
Result Weight
Location Weight
Drive Threshold
Expansion Threshold
State Logic:
Absorption Volume Z
Absorption Range Cap
Exhaustion Lookback
Recent State Window
Baseline Context Filter toggle
How to Use This Indicator
Step 1: Read the State Row
The State row tells you whether the market is currently showing directional drive, absorption, exhaustion, or balance. This is the first layer of interpretation.
Step 2: Compare Pressure With Quality
A strong pressure reading with weak drive quality can be unstable. A smaller pressure reading with improving quality can be more constructive. Use those two together rather than treating histogram height alone as the answer.
Step 3: Inspect Participation, Efficiency, and Location
These bands explain why the model is leaning in one direction. If participation is strong but efficiency is weak, the move may be absorption. If efficiency and location are strong but participation is weak, the move may be less durable.
Step 4: Watch the Rotation Ribbon
Rotation tells you whether pressure is continuing, stabilizing, or turning. This can be useful for early changes in internal character even when the headline state has not fully flipped yet.
Indicator Limitations
Relative volume is broker and instrument dependent, so the same thresholds may not transfer perfectly across markets
Absorption and exhaustion are contextual states, not guaranteed turning points
High-volatility event bars can temporarily distort effort-versus-result relationships
A baseline filter improves context but can delay state recognition during sharp reversals
Originality Statement
Caldera Relative Pressure is original in the way it turns candle anatomy, participation, efficiency, and location into a layered pressure model with separate drive, absorption, and exhaustion states. The script is not a simple volume oscillator or candle-coloring tool. Its design is centered on explaining how price is moving, not only how far it moved.
Disclaimer
This script is provided for educational and informational purposes only. It is not financial advice. Pressure readings are based on historical bar data and can misclassify conditions during abnormal liquidity or fast event-driven moves. Always use independent confirmation and prudent risk management.
Indicator

Fair Value GapsFair Value Gaps (FVG) auto-detects bullish (+FVG) and bearish (-FVG) three-candle imbalances on any chart, any timeframe. Tracks each gap's state through its lifecycle and shows a real-time dashboard with active gap counts, nearest gap distance, and exact zone prices.
WHAT IS A FAIR VALUE GAP
An FVG is a three-candle pattern where the middle candle moves so aggressively that it leaves a gap between the wick of the prior candle and the wick of the following candle. Price often returns to fill these gaps before continuing — making them useful as targets, entry zones, or invalidation levels.
A bullish (+FVG) forms when the low of the current candle is above the high of two candles ago, with a bullish middle candle. A bearish (-FVG) is the inverse.
FEATURES
Auto-detects pip size for JPY pairs, other forex, metals, indices, and crypto — no manual configuration needed
Tracks up to 10 active FVGs per side with configurable minimum size filter to ignore noise
Auto-removes filled FVGs OR keeps them on chart greyed out (your choice)
Optional midline marker (50% mitigation level)
Configurable label limit so only your most recent active gaps are annotated — prevents chart clutter
Dashboard shows active count, distance to nearest gap, and exact zone prices
Cells highlight amber when price is currently inside a gap (mid-mitigation)
Movable dashboard position (six options) so it coexists with other indicators
Built-in alerts for new bullish and bearish FVG formations
HOW TO USE
Use FVGs as targets when price has left an unfilled gap behind — markets often return to fill them. Use them as entry zones when price retraces into a gap in the direction of the higher-timeframe trend. Use them as invalidation when price closes through a gap that should have held as support or resistance.
Particularly useful for SMC and ICT traders watching for liquidity sweeps followed by displacement into a fair value gap, then a retracement entry.
Pairs cleanly with the Key Swing Levels (KSL) indicator from the same author — KSL's dashboard defaults to top-right, FVG's to bottom-left, no overlap.
Open-source. Feedback and forks welcome.
Indicator

Segmented Pressure Bands [JOAT]Segmented Pressure Bands
Introduction
Segmented Pressure Bands (SPB) is an open-source, institutional-grade regression channel system that computes a linear best-fit line and deviation bands from scratch using manual Ordinary Least Squares (OLS) mathematics — no built-in regression functions used. The channel operates in distinct segments: it builds over a dynamic lookback window, freezes all parameters at a minimum length threshold, extrapolates forward using the frozen slope and intercept, and resets automatically when price closes beyond the outer deviation band. Gradient linefill layers between the basis and outer bands communicate channel pressure visually. A volume regime tint adjusts visual weight based on relative volume activity, and ATR-based TP/SL visualization is drawn on each breakout reset.
The core problem SPB solves is that standard regression channels repaint continuously as new bars add to the calculation window, making historical channel boundaries unreliable for reference. SPB's freeze-and-extrapolate architecture locks the regression parameters at a fixed point in time, then projects the channel forward. Price that deviates far enough from that projection triggers a segment reset — the channel is redrawn from the breakout point. This creates a clear, non-repainting record of each regression segment and the breakout that ended it.
Core Concepts
1. Manual OLS Linear Regression
The regression is computed using the standard Ordinary Least Squares normal equations applied to the source series over the active lookback window:
float denom = float(length) * sumX2 - sumX * sumX
slope := (float(length) * sumXY - sumX * sumY) / denom
intercept := (sumY - slope * sumX) / float(length)
RMSE (root mean square error) is calculated as the deviation of the source from the fitted line, providing the basis for band width. All accumulator variables (sumX, sumY, sumXY, sumX2) are computed in a per-bar loop, giving full control over the calculation window without relying on built-in functions that may change behavior across versions.
2. Channel Freeze and Extrapolation
When the lookback window reaches the minimum length threshold, the slope, intercept, and RMSE are locked into freeze variables. From that point forward, the x-coordinate passed to the regression formula is the number of bars elapsed since the freeze bar, allowing the channel to project forward without recalculating:
float xCur = -float(bar_index - freezeBar)
basis := frozenIcpt + frozenSlope * xCur
This extrapolation means the bands continue to move with the slope direction, but their relative spacing (the RMSE deviation) remains constant from the freeze point.
3. Segment Reset on Breakout
When a candle closes beyond the outer upper or lower band, the current segment is terminated. The channel redraws from the current bar using the fresh source data from that point forward. Old linefill objects are explicitly deleted before new ones are created to stay within Pine Script's object limits.
4. Gradient Linefills and Volume Regime Tint
N intermediate lines are drawn between the basis and each outer band, filled progressively with increasing transparency from the inner region to the outer edge. This creates a gradient pressure visualization — tighter fills near the basis signal equilibrium, wider fills near the outer band signal stretch. When the volume regime ratio (short-term MA / long-term MA) is elevated above the high threshold, line widths increase and fill opacity deepens to communicate high-activity conditions visually.
Features
Manual OLS Regression: Slope, intercept, and RMSE computed entirely from first principles — no built-in regression functions
Freeze and Extrapolate Architecture: Regression parameters locked at minimum length; channel projected forward along the locked slope
Automatic Segment Reset: Outer band close-beyond triggers segment restart — prior segment preserved as a historical record
RMSE Deviation Bands: Upper and lower bands placed at configurable RMSE multiples from the basis line
Gradient Linefill Layers: N intermediate lines fill the channel space with a visual pressure gradient — configurable step count
Volume Regime Tint: Relative volume ratio (short/long MA) adjusts visual weight — elevated volume deepens channel fills and thickens lines
ATR TP/SL Visualization: On each breakout reset, ATR-based take profit and stop loss boxes drawn from the breakout close
Channel Direction Color: Downward slope (bullish context — price above a declining regression) renders in teal; upward slope (bearish context) renders in rose
Non-Repainting Basis: Freeze architecture ensures historical segment boundaries do not move after they are drawn
Configurable Source: Basis line source is selectable (close, hl2, hlc3, ohlc4, etc.)
Dashboard (Top Right): Current slope, RMSE, volume regime label, band multiplier, and active segment bar count
Near-Band Warning Dots: Subtle circle markers appear on the chart when price is within 12% of either channel edge — early warning that price is approaching a band extreme before a breakout occurs
Distance-to-Nearest-Band in Dashboard: Current distance from price to the nearest band displayed as a percentage of channel width — provides a precise quantitative read of how stretched or compressed the current position is within the segment
Live Regression Slope in Dashboard: Live regression slope value shown in the dashboard — communicates the current directional angle of the frozen channel projection in real time
Breakout Win/Loss Tracking: Outcome of every breakout trade tracked against ATR-based TP/SL levels — total breakout trade count and cumulative win rate displayed in the dashboard
Expanded Dashboard (7 Rows): Dashboard expanded to 7 rows — now includes distance-to-band percentage, live slope, and breakout win rate alongside existing regime and segment data
Input Parameters
Regression Settings:
Source: Price input for regression calculation (default: close)
Lookback Length: Maximum bar window for OLS computation (default: 50)
Min Length to Freeze: Bar count at which slope/intercept are locked (default: 20)
Band Multiplier: RMSE multiple for outer band placement (default: 2.0)
Gradient Settings:
Gradient Steps: Number of intermediate fill lines between basis and outer band (default: 5)
Volume Regime:
Short Vol MA: Short-term volume moving average length (default: 10)
Long Vol MA: Long-term volume moving average length (default: 40)
High Vol Threshold: Vol ratio above which volume tint activates (default: 1.5)
ATR / Risk:
ATR Length: Period for ATR calculation (default: 14)
ATR SL Multiplier: Stop loss distance on breakout (default: 1.5)
Reward:Risk Ratio: Take profit multiple of stop distance (default: 3.0)
How to Use This Indicator
Step 1: Read the Channel Direction
A teal channel indicates a downward-sloping regression — price is above a declining trend line, suggesting bullish pressure within the distribution. A rose channel indicates an upward-sloping regression — price is below a rising channel ceiling, suggesting bearish pressure. The gradient fills communicate how far price has deviated from the basis within that segment.
Step 2: Trade Within the Channel
Price compressing toward the basis from an outer band (thin fill region narrowing) suggests mean reversion is underway. Price expanding toward the outer band (fills widening) suggests momentum continuation. The outer band itself acts as a stretch boundary — closes beyond it trigger a new segment.
Step 3: React to Breakout Resets
When a segment resets, the breakout bar is the reference point for directional bias. The ATR TP/SL boxes visualize the immediate risk/reward from that close. The new channel building from the breakout will establish the next directional context.
Step 4: Monitor Volume Context
Elevated volume regime (shown in dashboard) at a channel boundary gives more conviction to breakout or reversal signals. Low-volume channel touches carry less institutional weight.
Indicator Limitations
The OLS calculation runs a loop over the lookback window on every bar. On very long lookback lengths with high chart data density, this may increase script execution time — keep lookback below 200 for best performance
The freeze architecture means the channel projection can diverge significantly from price if the instrument trends strongly after the freeze point. Segment resets bring the channel back to current price, but wide outer bands may delay that reset on low-volatility instruments
Gradient linefills are subject to Pine Script's 50-linefill object limit. SPB manages this with explicit deletion on each segment reset. If the gradient steps setting is set very high (above 10), this limit may be approached in active markets
ATR TP/SL boxes on breakout are drawn from the breakout close. They do not adjust for gaps, overnight moves, or instrument-specific spread — manual adjustment of the ATR multiplier may be needed for highly volatile instruments
Volume regime calculation uses simple moving averages of volume. On instruments where volume data is synthetic or unavailable, the regime indicator will not reflect true market activity
Originality Statement
SPB implements a regression channel with a freeze-extrapolate-reset lifecycle that produces stable, non-repainting historical segment boundaries. This design is original for the following reasons:
Computing OLS slope, intercept, and RMSE from scratch using raw accumulator mathematics — rather than using ta.linreg() or similar built-ins — gives full control over the calculation window, source, and update behavior, and avoids implicit look-ahead that some built-in functions can introduce
The freeze-and-extrapolate architecture is distinct from standard rolling regression, where every new bar shifts the entire historical channel. Once frozen, SPB's channel parameters are immutable — historical band boundaries drawn in past segments are permanent reference levels
The gradient linefill layer system communicates statistical deviation pressure visually across the full channel width, rather than drawing only a basis and outer band with no information about the space between them
The integration of a volume regime tint directly into the regression channel visualization — adjusting visual weight based on relative volume — provides immediate context for whether current channel position is occurring during active or quiet market conditions
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. Regression channels and statistical deviation bands are mathematical constructs applied to historical data — they do not predict future price behavior. Breakout signals at band extremes do not guarantee continuation in any direction. Always apply 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

PGS - Pareto-Gaussian Skew [Zofesu]PGS - Pareto-Gaussian Skew is a trend gravity indicator built on two mathematical principles: the Gaussian distribution for detecting statistically significant price moves, and the Pareto principle for isolating the minority of moves that drive the majority of directional displacement.
The result is a single adaptive line that acts as a gravitational center — pulling toward institutional price displacement while filtering out the noise that makes standard moving averages lag or whipsaw.
─────────────────────────────────────
01 — What is PGS?
─────────────────────────────────────
PGS plots a gravity line that tracks where price is being pulled by significant institutional moves. Unlike a standard moving average, it does not react to all price movement equally. It reacts only when price moves beyond one standard deviation from its mean — the threshold where statistically normal noise ends and directional displacement begins.
Below that threshold, the line stays anchored to the mean. Above it, the Pareto Skew Factor shifts the gravity line toward the extreme, capturing the 20% of moves that drive 80% of the trend.
─────────────────────────────────────
02 — How it works
─────────────────────────────────────
The engine runs in three steps:
Step 1 — Mean and standard deviation
SMA and standard deviation are calculated over the lookback window (default 100 bars). This defines the Gaussian baseline — the statistical center of recent price behavior.
Step 2 — Extreme detection
The distance between current close and the mean is measured. If that distance exceeds 1x standard deviation, the move is classified as extreme. Moves within 1 standard deviation are treated as noise and ignored.
Step 3 — Pareto displacement
Extreme moves are multiplied by the Pareto Skew Factor (default 0.8). This skewed value is then smoothed with an EMA over a quarter of the lookback period and added back to the mean — producing the final gravity line.
Formula:
gravity = SMA(close, n) + EMA(d × extreme × skew, n/4)
where d = close − SMA(close, n), extreme = 1 if |d| > StDev else 0
─────────────────────────────────────
03 — Visuals
─────────────────────────────────────
Blue line — Pareto-Gaussian gravity line
Tension Cloud — fill between price and the gravity line.
Green fill = price above gravity line (bullish tension).
Pink fill = price below gravity line (bearish tension).
Note: Price Reference and PGS Reference appear in the indicator's plot list but are invisible on the chart. They are internal anchors required by Pine Script's fill() function and serve no visual or analytical purpose for the user.
─────────────────────────────────────
04 — Settings
─────────────────────────────────────
Smith's Memory (Lookback) — default 100
Number of candles used for the Gaussian baseline. Higher = slower, more stable line. Lower = faster, more reactive.
Pareto Skew Factor — default 0.8
Weight applied to extreme moves. Higher = gravity line shifts more aggressively toward institutional displacement. Lower = more conservative, stays closer to the mean.
─────────────────────────────────────
05 — How To Use
─────────────────────────────────────
Step 1 — Read the Tension Cloud
Green fill = price is above the gravity line. Bullish context — look for longs or hold existing positions.
Pink fill = price is below the gravity line. Bearish context — look for shorts or avoid longs.
Step 2 — Watch for gravity line crossings
Price crossing the gravity line from below = potential bullish shift.
Price crossing from above = potential bearish shift.
Step 3 — Use as dynamic support and resistance
In trending markets the gravity line acts as a dynamic S/R level. Price pulling back to the line in a green cloud = potential long entry zone.
Step 4 — Combine with higher timeframe context
PGS works best as a trend context filter alongside entry tools. It defines the direction — your entry indicator defines the moment.
Works on all asset classes: Indices, Forex, Gold, Oil, Crypto.
Best timeframes: H1, H4, D1. Indicator

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

Auric Regime Classifier [JOAT]Auric Regime Classifier
Introduction
Auric Regime Classifier (ARC) is an open-source, multi-factor market regime detection engine that classifies every confirmed bar into one of five distinct market states: Strong Bull, Weak Bull, Ranging, Weak Bear, or Strong Bear — with a special Compression override that fires when volatility is contracting. The engine uses five independent data sources — adaptive ATR volatility ratio, Bollinger Band squeeze detection, SMEMA trend slope, ADX directional index, and RSI momentum bias — fused through a weighted scoring system into a single net score that drives the regime classification.
The problem ARC solves is that most traders apply a fixed strategy regardless of whether the market is trending strongly, drifting weakly, compressing before a breakout, or chopping without direction. Each of those conditions demands a completely different approach. Applying a trend-following system in a ranging market produces losses. Trading with tight stops in a compression phase produces whipsaws. ARC gives you a clear, real-time label for the current market phase so you can match your approach to the conditions rather than fighting them.
Core Concepts
1. SMEMA Adaptive Baseline
The indicator uses SMEMA (Simple Moving Average of Exponential Moving Average) as its core trend baseline — a proprietary double-smoothing construct used throughout the JackOfAllTrades indicator suite. SMEMA applies a standard EMA first to capture responsiveness, then a SMA over the same period to suppress noise. The result is a baseline that reacts faster than a raw SMA but is smoother than a raw EMA:
smema(float src, int len) =>
ta.sma(ta.ema(src, len), len)
Two SMEMA lines run in parallel: a slow line over the full period (default 20) and a fast line at half the period. Their slope comparison over three bars determines the trend direction score. When the slow SMEMA slopes upward for three consecutive bars, two bull points are awarded. When it slopes downward, two bear points are awarded.
2. Adaptive ATR Volatility Ratio
ATR over the input period (default 14) is compared against a long-run SMA of ATR (default 50 bars) to produce a volatility expansion/contraction ratio:
float volRatio = safeDiv(atrRaw, atrBase, 1.0)
A ratio above 1.1 in the direction of the existing trend awards a bonus point — recognizing that trend moves are more reliable when accompanied by above-average volatility. This prevents the engine from scoring weak, low-volume drifts as strongly as genuine impulsive moves.
3. Bollinger Band Squeeze Detection
The indicator measures Bollinger Band bandwidth (upper minus lower) and compares it against its own 100-bar SMA. When bandwidth falls below the configurable threshold fraction (default 0.75) of its smoothed average, the market is classified as Compressing. Compression overrides all other regime classifications — a compressing market has no valid directional edge regardless of what the other signals say:
bool isSqz = bbBW < bbBWAvg * sqzPct
A Squeeze Release signal fires when compression ends (isSqz transitions from true to false), marking the potential start of an expansion move.
4. ADX Directional Index
ADX (Average Directional Index) and the +DI/-DI directional lines are calculated using Pine Script v6's built-in ta.dmi() function. ADX above the threshold (default 25) confirms that the market is in a genuine trending regime rather than a sideways range. The directional bias of +DI vs -DI adds two bull or bear points to the regime score:
= ta.dmi(adxLen, adxLen)
bool isBullDir = diPlus > diMinus
bool isBearDir = diMinus > diPlus
5. Regime Scoring Engine
All five components feed a dual-sided scoring system. Bull and bear points are accumulated independently, and the net score (bull minus bear, range -6 to +6) determines the regime code:
int bullPts = (trendUp ? 2 : 0) + (isBullDir ? 2 : 0) +
(rsiBull ? 1 : 0) + ((volRatio > 1.1 and trendUp) ? 1 : 0)
int netScore = bullPts - bearPts
int regCode = isSqz ? 0 : netScore >= 4 ? 2 : netScore >= 1 ? 1 :
netScore <= -4 ? -2 : netScore <= -1 ? -1 : 0
Strong Bull requires a net score of +4 or higher (all four components aligned). Weak Bull requires +1 to +3. Ranging sits at 0. The mirror applies for bearish regimes.
6. Trend Strength Score (0-100)
Beyond the categorical regime label, ARC produces a continuous trend strength score that measures conviction within the current regime. It combines a distance score (how far price is from the SMEMA baseline in ATR units, capped at 50 points) with a momentum score (RSI deviation from 50 in the trend direction, capped at 50 points). A score of 70+ indicates a strong, high-conviction regime. Below 40 indicates a weak or transitional state.
Features
Five-State Regime Classification: Every bar labeled Strong Bull, Weak Bull, Ranging, Weak Bear, or Strong Bear with a Compression override — no ambiguity
SMEMA Ribbon: Fast and slow SMEMA lines with a gradient fill between them, colored by the current regime state for instant visual context
Regime Background Tint: Subtle, semi-transparent background coloring that shifts with the regime — green family for bull states, red family for bear, yellow for compression
Candle Coloring: Bar colors inherit the regime color at reduced opacity, giving every candle immediate regime context without obscuring price action
Squeeze Markers: Circle markers on the SMEMA baseline during compression, with a diamond signal at the moment of squeeze release
Trend Strength Score: A 0-100 numeric score with a Strong/Moderate/Weak label updated each bar, shown in the dashboard
Regime Change Alerts: Alert fires on every confirmed regime state transition with either plain text or structured JSON for webhook delivery
12-Row Dashboard (Top Right): Displays current regime, trend strength score, ADX value and trending/ranging status, +DI/-DI directional reading, volatility ratio, Bollinger Band state, RSI, timeframe, and version
Watermark: JackOfAllTrades signature rendered at chart center-bottom
Input Parameters
Core Engine:
ATR Length: Period for raw ATR calculation (default: 14)
ATR Smoothing Period: Baseline ATR lookback for volatility ratio (default: 50)
Directional Index:
ADX / DI Length: Period for +DI, -DI, and ADX (default: 14)
Trend Threshold: ADX level above which the market is considered trending (default: 25)
Volatility Band:
BB Length: Bollinger Band period (default: 20)
BB Multiplier: Standard deviation multiplier (default: 2.0)
Squeeze Threshold: Bandwidth fraction of its 100-bar SMA below which compression is declared (default: 0.75)
Trend Engine:
SMEMA Length: Period for the double-smoothed baseline (default: 20)
RSI Length: Momentum confirmation period (default: 14)
Visuals / Dashboard / Alerts:
Theme: Auto, Dark, or Light — auto-detects chart background
Regime Background Tint: Toggle the subtle background color
Show SMEMA Baseline: Toggle the ribbon plots
Show Squeeze Markers: Toggle the circle and diamond markers
Show Dashboard: Toggle the 12-row information panel
Show Watermark: Toggle the JackOfAllTrades signature
Webhook JSON Format: Switch alert messages between plain text and JSON
Color Palette: All six regime colors are individually customizable
How to Use This Indicator
Step 1: Read the Regime
The dashboard regime field and the background tint tell you exactly where the market stands. This single label is the most actionable piece of information — it drives which strategy is appropriate.
Step 2: Match Your Approach to the Regime
Strong Bull / Strong Bear: All four scoring components are aligned. High-conviction directional trades, trend-following entries on pullbacks to the SMEMA ribbon
Weak Bull / Weak Bear: Only one or two components agree. Lighter position sizing, wider stops, prepare for a possible regime shift
Ranging: Net score near zero — avoid directional trades, consider mean-reversion or wait for breakout
Compression: All directional analysis is suspended. Reduce exposure, prepare for a breakout in either direction, and watch the squeeze release signal for timing
Step 3: Use Trend Strength for Conviction
Within any directional regime, the strength score tells you how far into that regime the market has moved. A Strong Bull reading with a strength score of 85 is a very different trade environment from one with a strength score of 42. Use the score to scale position size or filter lower-conviction entries.
Step 4: Set Alerts on Regime Transitions
The regime-change alert fires the moment a new regime is confirmed on bar close. Enable the Strong Bull and Strong Bear alertconditions specifically to catch the high-conviction regime entrances.
Indicator Limitations
All five components are backward-looking. The regime label describes what has happened over the lookback windows — not what will happen. A Strong Bull classification can reverse on the very next bar
The warmup period (equal to the longest lookback, at least 50 bars) means the indicator produces no signals on the first several bars of any chart, including after switching timeframes
Compression detection uses a 100-bar SMA of bandwidth, which is a long-run reference. On very short or illiquid charts with few bars, the bandwidth average may not be reliable
The five-state classification uses fixed score thresholds (+4 for Strong, +1 for Weak). These thresholds are not auto-calibrated to the instrument. In range-bound markets where ADX rarely exceeds 20, the Strong Bull/Bear states may rarely appear
RSI and ADX both work with default periods. No single set of periods is optimal across all assets and timeframes. Users may need to adjust periods when applying to highly volatile assets or longer timeframes
Originality Statement
ARC is original in its synthesis approach and the use of SMEMA as the core trend baseline. This indicator is published because:
The SMEMA construct (SMA of EMA) is a proprietary double-smoothing formula used consistently across the JackOfAllTrades suite — it provides a smoother baseline than raw EMA while retaining more responsiveness than raw SMA, and it is not a standard available in typical indicator libraries
The dual-sided bull/bear point system scores each directional component independently before computing a net score. This is distinct from composite oscillators that blend components into a single signed value — the dual-side approach preserves information about how many bear components are active even when the net score is positive
The Compression override takes precedence over all directional scores, explicitly suspending regime analysis during volatility contractions. Most regime indicators simply produce lower directional readings in compression without explicitly declaring the compression state
The trend strength score combines an ATR-normalized price distance with an RSI momentum deviation to produce a conviction metric that is distinct from the categorical regime label
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. Market regime classifications are based entirely on historical data and past behavior. A market classified as Strong Bull can and will reverse at any time. The Compression state does not guarantee a subsequent breakout, and the direction of any eventual breakout cannot be predicted from compression alone. Always apply 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

Artemis Regression Bands🟦 Artemis Regression Bands is a kernel-driven volatility envelope indicator built on the KernelLens Nadaraya–Watson regression library (a_jabbaroff/KernelLens/1). A single kernel estimate — selectable from eight classical kernel families — anchors the Fair Value line. Around it, three residual-standard-deviation bands (±1σ, ±2σ, ±3σ) fan outward with either Linear or Exponential spacing, producing a statistically grounded envelope far cleaner than the classical close-stdev approach used by legacy Bollinger-style indicators. A four-gate Romb signal engine overlays buy / sell diamond markers when price pokes through the outermost enabled σ boundary and reverses back inside.
🟦 HOW IT WORKS
Artemis calls the KernelLens library's unified dispatcher once per bar to build the Fair Value line, then queries three additional library exports to derive the band widths, slope direction, and residual σ:
```
fair = kl.estimate (type, src, ℓ, α, period, phase, filter)
sigma = kl.confidenceBand(src, fair, window)
slopeVal = kl.slope (fair, 1)
trendSt = kl.trendState (fair, 1)
dev = baseMult · sigma
upper1 = fair + 1·dev lower1 = fair − 1·dev
upper2 = fair + 2·dev lower2 = fair − 2·dev
upper3 = fair + k3·dev lower3 = fair − k3·dev (k3 = 3 Linear | 4 Exp)
```
The library handles all weighted-sum computation, loop-depth selection, NA-safe iteration, division-by-zero guards, and input validation internally. Artemis contains zero kernel math — every bug fix or optimization in the library automatically propagates to this indicator.
🟦 KERNEL LIBRARY INTEGRATION
Artemis imports the published KernelLens library and uses the following exports:
| Library Export | Used For |
|---|---|
| `kl.estimate()` | Unified dispatcher — routes to the correct kernel based on the user's Kernel Type dropdown. Called once per bar to produce the Fair Value line. |
| `kl.confidenceBand()` | Rolling standard deviation of the (source − Fair Value) residual. Drives the band half-widths on every bar. |
| `kl.slope()` | Discrete first derivative of the Fair Value line. Feeds trend flip alerts. |
| `kl.trendState()` | Ternary classifier (+1 rising / −1 falling / 0 flat) of the Fair Value line. Drives the slope-adaptive color, the kernel trend confluence filter, and the dashboard Trend row. |
Every regression computation — kernel weight evaluation, NA-safe summation, bandwidth-aware loop termination, residual stdev, finite-difference slope — is delegated to the library. The indicator itself only orchestrates the four library calls and layers the visual pipeline on top.
🟦 EIGHT KERNEL FAMILIES
A single Kernel Type dropdown selects any of the eight kernels shipped with the KernelLens library. Each is a different mathematical smoother with its own statistical character:
| Kernel | Formula | Best For |
|---|---|---|
| Rational Quadratic | (1 + d² / (2·α·ℓ²))^(−α) | Multi-scale mixer; α controls stretch. Recommended default. |
| Gaussian / RBF | exp(−d² / (2·ℓ²)) | Canonical smoother; infinitely differentiable. |
| Periodic | exp(−2·sin²(π·d/p) / ℓ²) | Resonates with a known repetition distance p. |
| Locally Periodic | Periodic × Gaussian | Seasonal patterns with slow trend drift. |
| Epanechnikov | (3/4)·(1 − u²), \|u\| ≤ 1 | MSE-optimal; compact support, no tail contamination. |
| Tricube | (70/81)·(1 − \|u\|³)³, \|u\| ≤ 1 | LOWESS standard; near-Gaussian compact profile. |
| Triangular | (1 − \|u\|), \|u\| ≤ 1 | Simplest compact kernel; cheapest to compute. |
| Cosine | (π/4)·cos(π·u/2), \|u\| ≤ 1 | Raised-cosine; smooth boundary transition. |
Because the dropdown feeds the library's `kl.estimate()` dispatcher directly, every kernel inherits the same three-mode filter layer (No Filter / Smooth / Zero Lag) and the same non-repainting guarantees — there is no special case per kernel in Artemis.
🟦 FILTER LAYER
A second dropdown applies an optional post-processing layer on top of the raw Nadaraya–Watson estimate:
| Filter | Formula | Trade-off |
|---|---|---|
| No Filter | ŷ = ŷ_raw | Single-pass kernel. Rawest output, most reactive. |
| Smooth | ŷ = K(ŷ_raw) | Double-pass — kernel applied to its own output. Cleaner line, slightly more lag. |
| Zero Lag | ŷ = 2·ŷ_raw − K(ŷ_raw) | Ehlers de-lagging identity — sharpens edges without adding lag. |
The filter is resolved entirely inside `kl.estimate()`, so switching modes incurs no runtime cost beyond the extra kernel pass.
🟦 RESIDUAL-σ BAND ENGINE
Artemis bands are statistically grounded on the residual standard deviation — not on raw close stdev as in classical Bollinger indicators. The residual is computed as:
```
residual = src − fair
sigma = ta.stdev(residual, window) // via kl.confidenceBand()
```
Because Fair Value is already an unbiased local estimate of the source, the residual is a zero-mean noise series and its stdev captures **only the portion of price variance that the kernel could not explain**. This produces three benefits over the classical approach:
1. **Tighter bands in trending regimes** — close-stdev widens during strong trends because the trend itself inflates the variance; residual-σ does not, because the kernel absorbs the trend.
2. **Faster reaction to volatility regime changes** — residual-σ tightens as soon as the kernel fits well, and widens the instant the market breaks out of the kernel's neighborhood.
3. **True statistical interpretation** — under the assumption of locally Gaussian residuals, ±1σ / ±2σ / ±3σ enclose approximately 68 % / 95 % / 99.7 % of near-term price variation. The traditional close-stdev envelope carries no such interpretation.
A dedicated Residual σ Window input controls the lookback; typical values range from 50 (reactive, scalping) to 300 (stable, position trading).
🟦 BAND SPACING MODES
Two spacing presets shape the outward fan of the three σ bands:
| Mode | Multipliers | Character |
|---|---|---|
| Linear | 1·, 2·, 3· | Classical Bollinger-style uniform steps. Predictable, symmetric. |
| Exponential | 1·, 2·, 4· | Fibonacci-flavored — outer band (4σ) is reserved for genuine blow-off excursions. |
Base Multiplier scales all three bands uniformly (default 1.0). The formula is:
```
band_level = fair ± (baseMult · k · sigma) k ∈ {1, 2, k3}
```
where k3 resolves to 3 in Linear mode and 4 in Exponential mode. Every band has an independent visibility toggle, so minimalist users can run ±1σ only, swing traders ±3σ only, or any combination.
🟦 FOUR-GATE ROMB SIGNAL ENGINE
The Romb engine prints buy / sell diamond markers when price pokes through the outermost enabled σ band and reverses back inside. Four sequential gates protect against false entries:
| Gate | Logic | Purpose |
|---|---|---|
| 1 — Crossover | `ta.crossunder(high, triggerUp)` / `ta.crossover(low, triggerDn)` | Detects the reversal back through the outer band. |
| 2 — Warm-up | Residual σ computable for N consecutive bars | Blocks signals during the early kernel-settlement window. |
| 3 — Confluence | Fair Value slope aligns with the reversal direction | Optional PRO filter — Sell Romb requires falling kernel, Buy Romb requires rising kernel. |
| 4 — Cooldown | Minimum bar gap since the last same-side Romb | Prevents signal clustering on a single extended poke-and-reverse sequence. |
A Signal Mode toggle layers on top:
- **Confirmed** — signals fire only on `barstate.isconfirmed`; zero repaint on closed bars.
- **Realtime** — signals fire live on the current open bar; faster reaction, may vanish if price reverses before close.
Each confirmed signal is rendered as a two-layer neon diamond:
- **Halo** — `size.small`, 40 % transparent theme hue (glow layer).
- **Core** — `size.tiny`, fully opaque theme hue (bright center).
The halo renders first so the core sits cleanly on top, producing a sharp luminous marker that reads instantly even on dense price charts.
🟦 ADAPTIVE OUTER-BAND TRIGGER
The Romb engine does not hard-code the ±3σ band as the signal trigger. Instead, it resolves the outermost currently-enabled band on every bar:
```
triggerUp = show3 ? upper3 : show2 ? upper2 : show1 ? upper1 : na
triggerDn = show3 ? lower3 : show2 ? lower2 : show1 ? lower1 : na
```
The result is an envelope that respects the user's visibility choices:
| Visible Bands | Romb Fires At |
|---|---|
| ±1σ + ±2σ + ±3σ | ±3σ (default) |
| ±1σ + ±2σ | ±2σ |
| ±1σ only | ±1σ |
| All off | no signals |
Diamond positioning follows the same trigger, so the glyph always floats ~0.3σ outside whatever envelope is actually drawn on the chart. The behavior matches user intent: the band I can see is the band that fires signals.
🟦 NON-REPAINTING BEHAVIOR
Artemis inherits non-repainting behavior directly from the KernelLens library's `_phase` parameter. A single Phase input (default 2) shifts the kernel center into the past by that many bars:
- **Phase = 0** — live estimate, flickers on the current bar (real-time only; history is immutable).
- **Phase = 1** — 1-bar lag, non-repainting once the bar is confirmed.
- **Phase = 2** — recommended balance between freshness and stability (default).
- **Phase = 3+** — extra margin against erratic ticks, higher lag.
Historical repainting never occurs at any phase value. The library contains no `request.security` calls, no lookahead, and no array rotation that could leak future data. Every historical bar's plotted Fair Value, band, and Romb signal is final once confirmed.
🟦 VISUAL PIPELINE
**σ Band Outlines** — Three upper bands (±1σ / ±2σ / ±3σ) in progressively lighter `thBear` hues, three lower bands in progressively lighter `thBull` hues. Hidden bands collapse to na via their individual visibility toggles; the outline widths share a single Band Line Width input.
**Tapered Gradient Fills** — Six fills drawn between the Fair Value line and each σ band. Opacity scales progressively from ±1σ (densest, most opaque) to ±3σ (lightest, most transparent), creating a halo that mirrors the statistical density of price residuals under normality. Master Fill Opacity input (0 = invisible, 100 = fully opaque) scales all three fills uniformly.
**Fair Value Line** — Slope-adaptive color resolver swaps between `thBull` (rising kernel) and `thBear` (falling kernel). Flat bars retain the previous color so the line never flashes neutral on a perfectly horizontal tick. Width is user-controlled (1–5 px).
**Romb Diamonds** — Two-layer neon glow at the adaptive trigger band; halo + core rendering described above.
**Bar Coloring** — Optional theme-aware candle coloring driven by the Fair Value slope. Off by default; when enabled it paints every bar with the active theme's bull / bear hue based on the current trend state.
🟦 THEME SYSTEM
Twelve cohesive color palettes drive every visual component — Fair Value line, σ band outlines, gradient fills, Romb diamonds, bar coloring, and dashboard accents — all sharing the same four color axes (`thBull`, `thBear`, `thNeutral`, `thSignal`):
| Theme | Bull | Bear |
|---|---|---|
| Tropic | Cyan steel | Deep orange |
| Amber | Warm amber | Indigo blue |
| Pastel | Sky blue | Soft lavender |
| Cyber | Neon lime | Hot crimson |
| Helios | Bright gold | Scarlet |
| Electric | Electric aqua | Magenta |
| Candy | Neon green | Hot pink |
| Bloomberg | Terminal orange | Cyan |
| Solar | Solarized olive | Crimson |
| Royal | Imperial gold | Deep purple |
| Midnight | Deep navy | Dark crimson |
| Graphite | Near-black | Silver grey |
A separate Display Mode toggle (Dark / Light) controls the dashboard palette independently of the chart theme — so a Bloomberg chart theme with a Light dashboard is a valid configuration, as is Midnight chart + Dark dashboard.
🟦 DASHBOARD
A 2-column, 12-row theme-aware status panel that updates only on the last bar (zero historical overhead). Supports Dark and Light display modes, six docking positions, and four text sizes. Renders via `force_overlay = true` on the main price chart.
| Row | Label | Content |
|---|---|---|
| Header | ARTEMIS | DARK / LIGHT |
| Theme | Theme | Active palette name |
| Kernel | Kernel | Selected kernel type |
| Divider | REGRESSION | — |
| Bandwidth | Bandwidth ℓ | Bandwidth value / Phase offset φ |
| Filter | Filter | No Filter / Smooth / Zero Lag |
| Fair Value | Fair Value | Current Fair Value in chart mintick format |
| Divider | BANDS | — |
| Spacing | Spacing | Linear 1·/2·/3· or Exp 1·/2·/4· |
| Residual σ | Band σ | Rolling residual standard deviation |
| Trend | Trend | ▲ BULL / ▼ BEAR / ━ FLAT (bull/bear colored) |
| Last Romb | Last Romb | ▲ BUY (N ago) / ▼ SELL (N ago) — bull/bear colored |
**Zebra-stripe layout** — alternating `dashBg` / `dashBgAlt` row backgrounds improve scan-ability on narrow cells. Section dividers (REGRESSION, BANDS) use a third background tone (`dashSection`) with the theme's bull accent as the header color — preserving brand identity across both Display Modes.
🟦 ALERT CONDITIONS
Six opt-in alert conditions, each gated by its own toggle:
| Alert | Fires When |
|---|---|
| Bullish Trend Flip | Fair Value slope crosses from ≤ 0 into positive territory |
| Bearish Trend Flip | Fair Value slope crosses from ≥ 0 into negative territory |
| Buy Romb | Confirmed Buy Romb fires — all four signal gates passing |
| Sell Romb | Confirmed Sell Romb fires — all four signal gates passing |
| Upper Band Touch | Price touches or exceeds the outermost enabled upper band |
| Lower Band Touch | Price touches or falls below the outermost enabled lower band |
All alerts use `alertcondition()` for maximum compatibility with PulseWire's alert system including webhooks. Messages are structured as `"Artemis Regression Bands: "` for easy parsing in downstream automation. Touch alerts are off by default (can be noisy in trending markets); the four core alerts are on by default.
🟦 RECOMMENDED PRESETS
| Style | Bandwidth ℓ | Filter | Phase | Spacing | σ Window | Chart |
|---|---|---|---|---|---|---|
| Scalper | 10–20 | No Filter | 1 | Linear | 50–80 | 1m–5m |
| Day Trader | 20–40 | Smooth | 2 | Linear | 80–120 | 15m–1h |
| Swing | 30–60 | Smooth | 2 | Linear or Exp | 100–200 | 4h–1D |
| Position | 60–120 | Smooth or Zero Lag | 3 | Exp | 200–300 | 1D–1W |
**Kernel type tuning**
- **Trending instruments** — Rational Quadratic (α = 1–3) or Gaussian. Smooth multi-scale response.
- **Mean-reverting instruments** — Epanechnikov or Tricube. Compact support keeps the band envelope tight.
- **Session-cyclic patterns** — Periodic (with p = session length in bars) or Locally Periodic. Resonates with known cycles.
**Romb filter tuning** — Keep Kernel Trend Confluence ON for high-conviction setups only. Switch OFF on range-bound instruments to capture both sides of the oscillation.
🟦 COMPATIBILITY
- Pine Script v6
- All exchanges, all asset classes (crypto, forex, equities, commodities, indices)
- All timeframes (1 minute through Monthly)
- Both Dark and Light chart themes — the Display Mode toggle controls dashboard palette independently
- No exchange-specific logic — fully deterministic
🟦 TECHNICAL NOTES
- **Library dependency** — `import a_jabbaroff/KernelLens/1` — all kernel regression, residual σ, slope, and trend-state math is delegated to the published library.
- **Plot budget** — 6 band plots + 1 Fair Value anchor + 1 Fair Value visible + 6 gradient fills + 4 Romb plotshapes + 1 barcolor = well under Pine's plot limits.
- **Table** — Single `var table` rebuilt on `barstate.islast` with `force_overlay = true`; zero historical overhead.
- **Signal state** — Two `var int` cooldown anchors (`lastSellBar`, `lastBuyBar`) seeded at −10000 so the very first bar always passes the gap test. A `var int stabCount` warm-up counter blocks signals during early kernel settlement.
- **No persistent drawing objects** — no `box.new`, `line.new`, no array rotations; every visual is either a plot or a single-bar plotshape.
- **Adaptive trigger resolver** — Romb crossover detection, touch alerts, and diamond positioning all read from the same `triggerUp` / `triggerDn` resolver, so band visibility toggles stay semantically coherent across every layer of the indicator.
- **Non-repainting** — inherits from the library's `_phase` parameter; no `request.security`, no lookahead, no future-bar leakage at any phase value.
🟦 DISCLAIMER
Artemis Regression Bands is a technical analysis indicator built on the KernelLens Nadaraya–Watson regression library. It is provided solely for educational and research purposes and does not constitute financial, investment, or trading advice.
Kernel regression is a local smoothing technique. It estimates the mean of a source series in the neighborhood of the current bar based on historical data, but it does not predict future prices, does not generate trading signals on its own, and does not guarantee the profitability of any strategy built on top of its output. The residual-σ envelope describes past dispersion around the kernel estimate — not a forecast of future range — and should always be combined with broader context: higher-timeframe structure, volatility regime, liquidity, news, and risk management.
Past performance of any model does not guarantee future results. Markets contain systemic risks that cannot be eliminated by any amount of mathematical rigor. Responsibility for any trading decisions rests entirely with the user. Always apply sound capital management, conduct your own independent analysis, and never risk capital you are not prepared to lose.
The author assumes no liability for direct or indirect losses incurred through the use of Artemis Regression Bands or the underlying KernelLens library. Indicator

Quant Edge Ribbon PRO🟦 Quant Edge Ribbon PRO is a multi-kernel divergence ribbon indicator built on the KernelLens Nadaraya–Watson regression library (a_jabbaroff/KernelLens/1). A primary kernel and eleven longer-bandwidth kernels form a dual-ribbon visualization driven by kernel regression mathematics, an integer trend score in , a theme-aware rendering pipeline, four user-configurable reference levels, and a PRO dashboard. All twelve kernels route through the unified library dispatcher, so the user may select any of the eight kernel families and any of the three filter modes from a single configuration panel.
🟦 HOW IT WORKS
Quant Edge Ribbon PRO calls the KernelLens library's unified dispatcher (`kl.estimate`) twelve times per bar — once for the primary kernel and once for each of the eleven outer kernels:
```
primary = kl.estimate(type, src, ℓ, α, period, phase, filter)
long00 = kl.estimate(type, src, ℓ + 1·s, α, period, phase, filter)
long01 = kl.estimate(type, src, ℓ + 2·s, α, period, phase, filter)
...
long10 = kl.estimate(type, src, ℓ + 11·s, α, period, phase, filter)
```
where ℓ is the Primary Bandwidth and s is the Bandwidth Step. All twelve kernels share the same kernel type, filter, shape α, period, and phase — only the bandwidth differs. This guarantees the ribbon behaves as a coherent spectrum of kernel scales rather than a mixture of unrelated signals.
The library handles all weighted-sum computation, loop-depth selection, NA-safe iteration, division-by-zero guards, and input validation internally. Quant Edge Ribbon PRO does not reimplement any kernel math — every bug fix or optimization in the library automatically propagates to this indicator.
🟦 KERNEL LIBRARY INTEGRATION
Quant Edge Ribbon PRO imports the published KernelLens library and uses the following export:
| Library Export | Used For |
|---|---|
| `kl.estimate()` | Unified dispatcher — routes to the correct kernel based on the user's Kernel Type dropdown. Called twelve times per bar, once for the primary kernel and once for each of the eleven outer kernels. |
Every regression computation — kernel weight evaluation, NA-safe summation, bandwidth-aware loop termination — is delegated to the library. The indicator itself contains zero kernel math; it only orchestrates twelve library calls and aggregates their outputs into the trend score.
🟦 THE TWELVE-KERNEL RIBBON ARCHITECTURE
**Primary kernel (the shortest, the anchor)** — A single kernel at bandwidth ℓ that serves two roles: (1) it is the reference baseline for the trend score calculation, and (2) it is plotted as a dedicated highlighted anchor line when the "Highlight Primary Kernel" toggle is ON.
**Eleven outer kernels (progressively wider)** — Kernels at bandwidths ℓ+1·s, ℓ+2·s, …, ℓ+11·s, where s is the Bandwidth Step (default: 1). Each outer kernel is plotted as a line on the main chart, all eleven sharing a single score-driven gradient color — so the entire outer ribbon shifts between the theme's bull and bear hues as the trend score moves between −11 and +11.
**Eleven inner ribbon plots (lagged primary snapshots)** — The primary kernel plotted at eleven time-lag offsets (0, 1, 2, …, 10 bars). The resulting visual is a gently flowing shadow that makes expansion and contraction of the outer ribbon easier to perceive. Opacity is user-controlled (default: 40 %).
🟦 INTEGER TREND SCORE
The trend score is a signed integer in , computed on every bar by eleven pairwise comparisons between the primary kernel (at progressive lag offsets) and the eleven outer kernels:
```
score = 0
for i in 0..10:
if primary < long_i:
score += 1
else:
score -= 1
```
**Semantic interpretation** — Each comparison pairs an older snapshot of the shortest kernel against a current snapshot of a progressively wider kernel. In an uptrend, past primary values are lower while current wider-kernel values have caught up above them — the inequality resolves positive on most pairs and the score climbs toward +11. The symmetric argument drives the score toward −11 in a downtrend.
**Score parity** — Because the score is a sum of eleven ±1 terms (score = 2k − 11, k ∈ ), it is always odd. Reachable values: { −11, −9, −7, −5, −3, −1, 1, 3, 5, 7, 9, 11 }. The score is never exactly zero.
🟦 STRENGTH CATEGORIZATION
The absolute score is bucketed into four bands, each with a matched label glyph used throughout the dashboard and the last-bar signal label:
| Score Range | Strength | Label |
|---|---|---|
| \|score\| = 1 | NEUTRAL | ▰▱▱▱ NEUTRAL |
| \|score\| ∈ {3, 5} | WEAK | ▰▰▱▱ WEAK BULL / WEAK BEAR |
| \|score\| = 7 | STRONG | ▰▰▰▱ STRONG BULL / STRONG BEAR |
| \|score\| ∈ {9, 11} | TRIPLE | ▰▰▰▰ TRIPLE BULL / TRIPLE BEAR |
The bull / bear suffix is driven by the sign of the score. The progress-bar glyphs (▰▱) give an instant at-a-glance read of confluence intensity without needing to parse the numeric value.
🟦 NON-REPAINTING BEHAVIOR
Quant Edge Ribbon PRO inherits non-repainting behavior directly from the KernelLens library's `_phase` parameter. A single Phase input (default: 2) shifts every one of the twelve kernel centers into the past by that many bars.
- Phase = 0 — live estimate, flickers on the current bar (real-time only; history is immutable)
- Phase = 1 — 1-bar lag, non-repainting once the bar is confirmed
- Phase = 2 — recommended balance between freshness and stability (default)
- Phase = 3+ — extra margin against erratic ticks, higher lag
Historical repainting never occurs at any phase value. The library contains no `request.security` calls, no lookahead, and no array rotation that could leak future data. Every historical bar's plotted value is final once confirmed.
🟦 VISUAL PIPELINE
**Outer Ribbon Gradient** — All eleven outer kernels are plotted with a single shared color driven by the trend score via `color.from_gradient(score, -11, 11, thBear, thBull)`. As the score walks across its range, the entire ribbon shifts continuously between the active theme's bearish and bullish hues — producing a smooth visual feedback loop between the math and the palette.
**Inner Ribbon Shadow Trail** — Eleven lag-shifted primary snapshots (primary through primary ) drawn in the theme's accent hue with user-controlled opacity. On a trending chart the trail visually expands; on a reversing chart it contracts. Adjust opacity from 0 (invisible) to 100 (fully opaque) — default 40 balances presence and subtlety.
**Primary Kernel Anchor Line** — The primary kernel plotted as a dedicated bold line in the theme's accent color at 80 % opacity, distinct from the shadow trail. Provides a clear centerline amid the ribbon flow. Toggleable.
**Oscillator Subplot** — The smoothed trend score plotted in a dedicated subplot with a score-gradient vertical fill between the score line and the zero line. Opacity is user-controlled. An optional bold score line (up to 4 px wide) overlays the fill for sharp numeric reading.
**Last-Bar Trend Label** — A right-anchored label at the current bar in the oscillator pane. Format: `▲ TRIPLE BULL 11 / 11` (bull) or `▼ WEAK BEAR −3 / 11` (bear). The label is deleted and redrawn on every bar, so only one instance is ever present on the chart.
🟦 OSCILLATOR STYLES
The oscillator subplot ships with two visual presets, selectable from the Oscillator Style dropdown:
| Style | Plot Style | Fill | Best For |
|---|---|---|---|
| Classic Gradient | `plot.style_line` (smooth curve) | Continuous vertical gradient from score to zero | Trend flow, slope momentum |
| Stepline | `plot.style_stepline` (staircase) | Stepped gradient mirroring the discrete score plateaus | Signal / threshold trading, discrete level crossings |
**Classic Gradient** produces a smooth curve traced through the smoothed score values, with the gradient fill flowing continuously between the score line and the zero line. This is the default and suits traders who read trend direction through slope and curvature.
**Stepline** renders each bar as a horizontal plateau joined to the next bar by a vertical edge. Because the raw score is always an odd integer in { −11, −9, …, 9, 11 }, the staircase visualization honors the score's true discrete nature — making it easier to identify exact threshold crossings (e.g. the moment the score enters the ±9 extreme zone). The fill inherits the same stepline style, so the entire oscillator pane stays geometrically consistent.
Both styles share the same opacity controls, score line toggle, and line width setting — only the geometry of the score line and its fill changes between them.
🟦 THEME SYSTEM
Ten cohesive color palettes tuned to the Quant Edge Ribbon PRO optical brand. One selection drives every visual component — outer ribbon gradient, inner ribbon accent, oscillator fill, reference lines, signal label, dashboard accents — all sharing the same bull / bear / accent color axes:
| Theme | Bull | Bear |
|---|---|---|
| Prism | Forest green | Crimson red |
| Focus | Cyan steel | Deep orange |
| Solar | Warm amber | Indigo red |
| Frost | Sky blue | Soft lavender |
| Laser | Neon lime | Hot crimson |
| Aurora | Bright gold | Scarlet |
| Plasma | Electric aqua | Magenta |
| Bloom | Mint green | Hot pink |
| Eclipse | Deep navy | Dark crimson |
| Carbon | Near-black | Silver grey |
The oscillator's zero line uses Pine's `chart.fg_color` so it auto-adapts to the actual chart background (white on dark charts, black on light charts) — independent of the Dashboard's Display Mode setting.
🟦 REFERENCE LEVELS
Four user-configurable horizontal reference lines mark the score's structural thresholds inside the oscillator subplot:
| Level | Style | Meaning |
|---|---|---|
| +11 / −11 | Dotted | Ceiling / floor — the mathematical maximum (every comparison aligned) |
| +9 / −9 | Dashed | Extreme zone — nine or more of the eleven comparisons agree on direction |
Each pair (±11 and ±9) has an independent opacity input (0–100 %). A master toggle (Show Reference Levels) collapses all four lines to fully transparent in a single branch — useful for minimalist layouts. An additional `showOsc` gate hides them automatically when the oscillator itself is disabled.
🟦 PRO DASHBOARD
A 2-column, 12-row theme-aware status panel that updates only on the last bar (zero historical overhead). Supports Dark and Light display modes, six docking positions, and four text sizes. Renders via `force_overlay = true` on the main price chart.
| Row | Label | Content |
|---|---|---|
| Header | Q-EDGE PRO | DARK / LIGHT |
| Theme | Theme | Active palette name |
| Kernel | Kernel | Selected kernel type |
| Divider | RIBBON | — |
| Primary ℓ | Primary ℓ | Primary bandwidth value |
| Span | Span | ℓ → ℓ + 11·s |
| Filter | Filter | No Filter / Smooth / Zero Lag |
| Divider | SCORE | — |
| Score | Score | ▲/▼ + integer score + " / 11" (bull/bear colored) |
| Bull / Bear | Bull / Bear | Bull comparison count / bear comparison count |
| Strength | Strength | ▰-bar + NEUTRAL / WEAK / STRONG / TRIPLE label |
| Primary | Primary | Primary kernel value in chart mintick format |
**Bull / Bear breakdown** — The eleven pairwise comparisons split into bulls (resolved +1) and bears (resolved −1). Always sums to 11, so this row gives a direct visual of how many kernel scales agree with the net direction.
🟦 ALERT CONDITIONS
Six opt-in alert conditions, each gated by its own toggle:
| Alert | Fires When |
|---|---|
| Bullish Flip | Score crosses from ≤ 0 into positive territory |
| Bearish Flip | Score crosses from ≥ 0 into negative territory |
| Extreme Bullish | Score reaches +9 or higher (first entry into the zone) |
| Extreme Bearish | Score reaches −9 or lower (first entry into the zone) |
| Full Confluence Up | Score hits +11 — every outer kernel aligned bullishly |
| Full Confluence Down | Score hits −11 — every outer kernel aligned bearishly |
All alerts use `alertcondition()` for maximum compatibility with PulseWire's alert system including webhooks. Messages are structured as `"Quant Edge Ribbon PRO: "` for easy parsing in downstream automation.
🟦 RECOMMENDED PRESETS
| Style | Primary ℓ | Bandwidth Step s | Phase | Filter | Chart |
|---|---|---|---|---|---|
| Scalper | 8–16 | 1 | 1 | No Filter | 1m–5m |
| Day Trader | 16–32 | 1–2 | 2 | Smooth | 15m–1h |
| Swing | 25–50 | 1–2 | 2 | Smooth | 4h–1D |
| Position | 50–120 | 2–3 | 3 | Smooth | 1D–1W |
**Bandwidth Step tuning** — Step = 1 produces a tight ribbon where adjacent outer kernels sit visually close together. Steps of 2–4 spread the eleven outer kernels across a broader spectrum of scales, making expansion / contraction easier to read at a glance. Step 5–6 is reserved for very wide ribbons where each line represents a distinctly different time scale.
🟦 COMPATIBILITY
- Pine Script v6
- All exchanges, all asset classes (crypto, forex, equities, commodities, indices)
- All timeframes (1 minute through Monthly)
- Both Dark and Light chart themes — visual elements auto-adapt via `chart.fg_color`
- No exchange-specific logic — fully deterministic
🟦 TECHNICAL NOTES
- **Library dependency** — `import a_jabbaroff/KernelLens/1` — all kernel regression math is delegated to the published library
- **Plot budget** — 11 outer + 11 inner + 1 primary + 2 oscillator plots + 1 fill + 4 hlines = well under Pine's 64-plot limit
- **Table** — Single `var table` created once on `barstate.islast` with `force_overlay = true`; dashboard renders on the main chart pane, zero historical overhead
- **No persistent drawing objects** — no `box.new`, `line.new`, no `array.new`; the single trend label is deleted and recreated every bar so only one instance is ever present
- **Opacity convention** — every user-facing opacity input follows `0 = invisible, 100 = fully opaque`; conversion to Pine's native transparency is centralized in a single helper function (`f_opac`)
- **Non-repainting** — inherits from the library's `_phase` parameter; no `request.security`, no lookahead, no future-bar leakage at any phase value
- **Chart background adaptive** — the oscillator's zero line uses `chart.fg_color`, so it always renders with high contrast regardless of the user's chart color scheme
🟦 DISCLAIMER
Quant Edge Ribbon PRO is a technical analysis indicator built on the KernelLens Nadaraya–Watson regression library. It is provided solely for educational and research purposes and does not constitute financial, investment, or trading advice.
Kernel regression is a local smoothing technique. It estimates the mean of a source series in the neighborhood of the current bar based on historical data, but it does not predict future prices, does not generate trading signals on its own, and does not guarantee the profitability of any strategy built on top of its output. The integer trend score is a geometric summary of kernel alignments — not a forecast — and should always be combined with broader context: higher-timeframe structure, volatility regime, liquidity, news, and risk management.
Past performance of any model does not guarantee future results. Markets contain systemic risks that cannot be eliminated by any amount of mathematical rigor. Responsibility for any trading decisions rests entirely with the user. Always apply sound capital management, conduct your own independent analysis, and never risk capital you are not prepared to lose.
The author assumes no liability for direct or indirect losses incurred through the use of Quant Edge Ribbon PRO or the underlying KernelLens library. Indicator

Trendline Confluence Map [AGPro Series]Trendline Confluence Map
Overview
Trendline Confluence Map automatically draws ascending and descending trendlines from major and minor swing pivots, then maps the zones where two or more of these trendlines intersect with each other or with key horizontal support and resistance levels. Every confluence zone is scored from 0 to 100 based on touch count, line age, trendline angle and volume, so traders can instantly see which reaction levels are backed by the most structural weight. Drawn as long rectangular zones in the classic S/R style, the map stays anchored to current price and hides old, irrelevant levels automatically.
Unique Edge
Most trendline tools either draw a single line or flood the chart with dozens of low-quality lines that never interact with each other. This indicator is built around the opposite idea: confluence is the signal, single lines are just noise. Its three design choices make the difference. First, the script maintains a disciplined pool of only the trendlines whose current projection is on-chart, so a zero-visibility clutter problem cannot happen — the panel count always equals what you actually see. Second, horizontal S/R levels participate as first-class confluence sources alongside trendlines, with a guard requiring at least one real trendline per zone so the tool remains true to its name. Third, every zone label shows a source breakdown such as "2 TL" or "1 TL + 1 SR", giving you immediate insight into why a zone was considered high-probability.
Methodology
Swing pivots are detected at two depths (major and minor) using pivot-high and pivot-low structures, with configurable lookback lengths. Each valid consecutive pivot pair spawns a trendline, and every subsequent bar that wicks into the projected line within an ATR-based tolerance increments its touch count, raising its structural validity. Horizontal S/R levels are extracted from recent major pivots and merged when they fall within 0.4 ATR of each other. On each confirmed bar, the detector builds a combined pool of all on-chart trendline projections plus horizontal levels, then runs a greedy clustering pass using a zone-width-sized tolerance window. Candidate clusters that contain at least one trendline and meet the minimum source count are scored by combining touch strength, line age, slope quality, a rolling volume component and a horizontal S/R bonus. The highest-scoring cluster becomes a confluence zone, drawn as a rectangle whose right edge extends dynamically to the current bar so every active zone stays visually anchored to price. Zones are deduplicated by price and direction, and expire automatically after a configurable age.
Signals and Alerts
Every new confluence zone is announced with a descriptive alert that carries its mid-price, score and source breakdown. A second alert fires when price first crosses into an active zone from outside, helping traders react to the moment a level is tested. Zone colors encode directional bias: green zones indicate support-favored confluence while pink zones indicate resistance-favored confluence, with the bias derived from the dominant trendline direction in the cluster. Labels on the right edge of each zone show the current score, the source breakdown and the bias tag, so at a glance the trader knows which level is strongest and why.
Key Inputs
Major Pivot Length and Minor Pivot Length define the swing-detection depth of the two pivot streams. Max Active Trendlines caps the internal pool, while Min Touches to Validate filters out unconfirmed trendlines from the confluence pass. Touch Tolerance in ATR units controls how generously the script counts interactions. Min Sources for Zone sets the confluence requirement, Zone Width in ATR units determines rectangle thickness, and Zone Forward Extension controls how far each zone reaches to the right. Max Active Zones and Max Zone Age in bars keep the map focused on currently relevant structure. Panel Theme, Panel Location and Font Size cover the full visual customization layer.
How to Use
Start on the timeframe you trade and leave the defaults — they are tuned for 4H crypto and major FX on equivalent timeframes. Scan for zones with a score above 60 in a direction aligned with the higher-timeframe bias. Use the green support-biased zones as pullback entry areas in uptrends and the pink resistance-biased zones as fade or short entry areas in downtrends. Break-and-retest traders can wait for price to pierce a high-score zone and return to its edge; mean-reversion traders can watch for rejection at zones where the source breakdown includes both a trendline and a horizontal level, as those tend to hold more strongly. The panel at the top shows a quick summary of the current map state and the distance to the nearest zone in ATR units, which is useful for position sizing and stop placement.
Limitations and Transparency
This is not a strategy and not a complete trading system. It does not predict price and does not generate buy or sell instructions. Confluence zones are structural context, not entries, and their score is an internal quality estimate derived from visible price action, not a probability of success. The script needs a reasonable amount of historical bars to build a stable trendline pool. Very low timeframes and very illiquid symbols can produce erratic pivot structures and are not the intended use case. Like all pivot-based tools, the indicator reflects past structure, and levels can weaken or become stale as market regimes change. Zones older than the configured age are removed automatically to reduce this risk.
Risk Disclosure
Trading involves substantial risk of loss and is not suitable for every investor. Past performance is not indicative of future results. This indicator is provided for educational and analytical purposes only and should not be interpreted as financial advice, an investment recommendation or a solicitation to trade. Always combine multiple forms of analysis, manage position size responsibly, and never risk capital you cannot afford to lose.
Indicator

Smart Trader, Episode 06, Isotropic Trend Lines🔷 WHAT IS ST-EP06 — ISOTROPIC TREND LINES?
ST-EP06 is a multi-scale structural trend channel indicator built on a σ-normalized coordinate system. It is designed to solve one of the oldest unaddressed problems in technical analysis:
trend angles that cannot be compared across instruments, timeframes, or volatility regimes.
A trend line drawn on a chart appears to carry a measurable angle — yet that angle is an artifact of the display window, not a property of the market. Resize the chart horizontally and the slope flattens; compress it and the slope steepens. A given price movement on Gold daily and Bitcoin 1-hour may produce visually identical slopes on screen while reflecting entirely different structural conditions. This happens because traditional charts use a coordinate space where the vertical axis (price) and the horizontal axis (time) share no fixed dimensional relationship.
The consequence is not merely cosmetic. A trader cannot meaningfully compare the steepness of a trend on one instrument with another — or even across timeframes on the same instrument — because the weight of "one unit of price per bar" varies with the instrument's current volatility.
As the author of this indicator, I sought a coordinate system where trend angles would be an intrinsic structural property of the market, independent of charting software or display settings. The goal: a space where a 30° uptrend on EUR/USD weekly carries the same structural meaning as a 30° uptrend on NASDAQ 5-minute — indicating that each market is moving at the same rate relative to its own realized volatility.
The solution draws on the principle of dimensional analysis, well established in physics and engineering. Just as the Reynolds number normalizes fluid flow to make behavior comparable across different pipe sizes and fluid viscosities, this indicator normalizes price movement by realized volatility, producing a dimensionless space we call the Isotropic Coordinate System (ICS).
In ICS, price is expressed in natural logarithmic form and scaled by a volatility estimate (σ) derived from the Yang-Zhang (2000) method — a drift-invariant estimator that incorporates Open, High, Low, and Close data. The resulting vertical axis is dimensionless: one unit equals one standard deviation of recent realized price behavior. When trend angles are measured in this space, 45° indicates approximately one σ of movement per bar — whether the chart shows a penny stock, a major currency pair, or a commodity index.
Traditional chart coordinates assign no fixed relationship between the price axis and the time axis. Resizing the chart window changes the visual slope of the same price movement — a compressed view may show 52° while a stretched view of the same data shows 25°. The angle is a display artifact, not a market property. The Isotropic Coordinate System (ICS) addresses this by normalizing log-price by realized volatility (σ). In this space, the trend angle is designed to remain constant regardless of how the chart is displayed — because it measures price displacement in units of σ per bar, not in pixels per pixel.
🔷 HOW THE MODULES WORK TOGETHER
ST-EP06 operates as a deterministic pipeline where each stage consumes the output of the one before it:
Realized volatility estimation (σ) → Structural block construction → Monotonic direction detection → ICS angle measurement → Channel boundary fitting → Six-scale parallel analysis → Consensus aggregation → Breakout and retest state tracking → Dashboard narrative generation
The Yang-Zhang σ provides the normalization constant for every downstream computation. Price history is then partitioned into structural blocks, each distilled to a single central tendency that resists close-price bias. Consecutive block centers are compared to identify the longest uninterrupted directional segment. The slope of that segment, measured in σ-normalized space, yields the ICS angle. Four price extremes located within the segment define two log-linear channel boundaries. This complete pipeline runs independently at six temporal scales, and their independent outputs are aggregated into a structural consensus. A finite-state machine then tracks the evolving relationship between price and the primary channel — breakout, retest, confirmation, or failure — and translates it into a single-line human-readable narrative.
ST-EP06 operates as a deterministic sequential pipeline. Yang-Zhang volatility (σ) provides the normalization constant that flows into every downstream stage. Price history is partitioned into structural blocks, each reduced to a geometric mean. The longest monotonic segment determines direction, and its slope in σ-normalized space yields the ICS angle. Four price extremes define the channel boundaries. This complete pipeline runs independently at six scales — 3, 7, 13, 19, 29, and 47 bars per block — all prime numbers, chosen to minimize harmonic overlap so that multiple scales are unlikely to lock onto the same cyclical artifact. Scale 19 (highlighted) serves as the primary engine: it is the only scale that maps to the user's Trend Block Period input, and the only scale whose output drives the chart-overlay channel lines, the projection, the diamond markers, and the breakout/retest state machine. The other five scales operate at fixed periods and contribute exclusively to the cross-scale consensus count — providing structural context that a single scale cannot offer alone. When 5 or 6 of the 6 scales agree on direction, it suggests a structural trend visible across a broad range of temporal resolutions.
🔷 DATA ANCHORING
Every structural computation in ST-EP06 — volatility, block means, direction, channel coordinates, state machine transitions, and dashboard narrative — is governed by a single anchoring reference, selected through the Calculation Bar input.
Live Bar mode (default): the anchor is the current forming bar. Values update with each incoming tick. This is standard PulseWire behavior and means the indicator may exhibit intra-bar repaint — the live bar's data enters all computations as it evolves.
Close Bar mode: the anchor shifts to the last fully confirmed (closed) bar. The forming bar is excluded from every computation. Values lock once a bar closes and do not change retroactively. This mode is intended for structural analysis, back-testing, and any workflow where historical consistency is a priority.
One deliberate exception is maintained in both modes: the dashboard header always displays the current live closing price (Live Exception protocol), preserving real-time price awareness regardless of how the indicator's structural engine is anchored.
Two modes, same chart moment. In Live Bar the anchor sits on the forming bar, so every value updates tick-by-tick and may repaint within the bar. In Close Bar the anchor shifts to the last closed bar, locking all structural values once the bar closes. The only exception is the dashboard header row, which always displays the live closing price in both modes, so real-time price awareness is never lost.
🔷 YANG-ZHANG VOLATILITY (σ)
The foundation of the ICS is a robust volatility estimate. ST-EP06 uses the Yang-Zhang (2000) realized volatility estimator, an academically established method that combines three variance components:
Overnight variance — capturing the gap between consecutive sessions, measured from the prior close to the current open.
Intraday variance — capturing the movement from open to close within each session.
Range-based variance — using the Rogers-Satchell (1991) estimator, which extracts additional information from the high and low prices without assuming zero drift.
These three components are blended using an optimal weight that is designed to minimize estimation error. The resulting σ updates every bar, adapts to changing market conditions, and — crucially — is drift-invariant: it is intended to remain unbiased whether the market is trending strongly or mean-reverting.
🔷 BLOCK CONSTRUCTION
Rather than analyzing individual bars, ST-EP06 partitions recent price history into consecutive non-overlapping blocks. Each block spans a user-defined number of bars (the Trend Block Period input) and is reduced to a single representative value: the geometric mean of the block's highest high and lowest low, computed in logarithmic space.
This log-midpoint serves as the block's central tendency. Unlike a simple average of closing prices, it captures the structural center of the entire price range within the block, avoiding bias toward any single price point. The number of consecutive blocks compared is controlled by the Trend Block Groups input — more groups means deeper lookback and the ability to detect longer structural trends.
Price history is partitioned into consecutive non-overlapping blocks. Each block reduces to a single log-midpoint — the geometric mean of its highest high and lowest low. Connecting the midpoints forms the representative chain used for trend detection.
🔷 DIRECTION DETECTION + ICS ANGLE
Once blocks are constructed, the engine compares their geometric means in sequence, starting from the most recent. It identifies the longest consecutive segment where each block's central tendency moves in the same direction — either consistently rising or consistently falling. A single reversal terminates the segment.
The slope of this segment is then measured in ICS space: the logarithmic price difference between the oldest and newest blocks in the segment, divided by σ, divided by the number of bars between them. The arctangent of this normalized slope produces the ICS angle in degrees.
If the absolute angle falls within the Range Threshold (a user-configurable dead zone in degrees), the direction is classified as ranging rather than trending. This threshold acts as a sensitivity filter — wider values require steeper moves before declaring a trend, narrower values respond to subtler directional shifts.
An ICS angle of 45° indicates approximately one σ of price movement per bar. An angle near 0° suggests the market may be structurally flat. Because σ adjusts for volatility and the logarithm adjusts for price level, these angles are intended to be directly comparable across any instrument and any timeframe.
🔷 CHANNEL FITTING
Within the identified trending segment, the engine locates four price extremes: the highest high, the lowest high, the highest low, and the lowest low — each paired with its bar position. These four points define two linear boundaries in ICS space.
During an uptrend, the upper boundary is fitted through the lowest high and highest high (capturing the rising ceiling), while the lower boundary is fitted through the lowest low and highest low (capturing the rising floor). During a downtrend, the fitting order reverses to capture descending structure. During a ranging market, the channel uses horizontal boundaries at the segment's absolute high and low.
All boundary computations occur in the σ-normalized logarithmic coordinate system, meaning the channel lines represent geometric (log-linear) paths in price space — curves that naturally follow multiplicative price behavior rather than additive assumptions.
Within the trending segment, four extremes — HH, LH, HL, LL — define two log-linear boundaries. In an uptrend, the upper line fits through LH and HH, the lower through LL and HL. The direction reverses the fitting order for downtrends, and a ranging market uses horizontal boundaries.
🔷 6-SCALE PARALLEL ANALYSIS
A single temporal scale may capture the trend at one resolution but miss structure at others. ST-EP06 runs the complete pipeline — volatility normalization, block construction, direction detection, ICS angle, and channel fitting — independently at six different scales: 3, 7, 13, 19, 29, and 47 bars per block. These values were chosen as prime numbers to minimize harmonic overlap between scales.
Scale 19 serves as the primary engine and maps to the user's Trend Block Period input. The other five scales use fixed periods, providing a structural context that the primary engine alone cannot offer.
The dashboard displays each scale's independent trend direction. A consensus count shows how many of the six scales agree: 5/6 or 6/6 agreement suggests a structural trend that is visible across multiple temporal resolutions, while low agreement may indicate transitional or conflicting structure.
🔷 BREAKOUT / RETEST STATE MACHINE
ST-EP06 includes a 5-state finite automaton that tracks price's structural relationship to the primary channel boundaries:
Inside — price is observed between the channel floor and ceiling. The dashboard shows the position as a percentage: distance from floor and distance to ceiling (summing to 100%).
Breakout Up / Breakout Down — price has exited above the ceiling or below the floor. The dashboard shows the breakout price and the percentage of channel width that price has moved beyond the boundary.
Retest Up / Retest Down — after a breakout, price has moved at least one σ away from the boundary (establishing distance), then returned to test it. The dashboard shows both the original breakout price and the current retest level.
Transitions between states use dynamic σ-based thresholds rather than fixed percentages, meaning the sensitivity automatically adjusts with market volatility. Additional flags track:
✓ Confirmed — a breakout that has been retested and bounced at least one σ away from the boundary.
(gap) — price crossed the entire channel width in a single transition.
Failed breakout — price re-entered the channel after initially breaking out.
Direction reset — the primary trend direction changed, wiping all breakout state.
🔷 VISUAL TOOLS
All chart-overlay elements are drawn from the primary engine (scale 19):
Channel lines — solid upper and lower boundaries from the segment start to the anchor bar, colored by trend direction (configurable up/down/range colors, width, and line style).
Projection lines — dotted forward extension of the channel slopes beyond the anchor bar, providing a visual reference for potential future support and resistance. The projection offset, width, and style are independently configurable.
Channel fill — semi-transparent shading between channel boundaries, with independent color selection and adjustable transparency. Applies to both the solid channel and projection segments.
Diamond markers (◆) — placed at the channel endpoints on the anchor bar. Hovering reveals a tooltip with the anchored close price, ceiling level, floor level, and the price's position as a percentage of channel width.
Direction label — positioned at the midpoint between segment start and projection end. Displays the trend arrow, direction text, and ICS angle (e.g., "▲ UP +7.3°"). Tooltip includes block count.
🔷 DASHBOARD
A compact information table appears at the top-right corner of the chart, organized in 5 rows:
Header — indicator name, ticker symbol, timeframe, and live price (always live under the Live Exception protocol, even in Close Bar mode).
Period — the six scale values (3, 7, 13, user's period, 29, 47) displayed across columns. The primary engine column is highlighted.
Trend — per-scale trend direction with directional arrows (▲ UP, ▼ DN, ◈ RNG) and color coding.
Agreement — consensus count (e.g., "5/6 UP") with the primary channel ceiling (▲) and floor (▼) price levels.
Narrative — a single merged row presenting the breakout/retest state machine output as a human-readable sentence with distance measurements. This row updates dynamically as price interacts with the channel.
All dashboard text, tooltips, and narrative phrases are fully localized.
🔷 ALERT CONDITIONS
ST-EP06 provides 19 alert conditions organized in 5 categories, all gated by a master Enable Alerts toggle:
D · Direction (3 alerts) — fires when the primary engine trend changes to uptrend, downtrend, or range.
B · Breakout (4 alerts) — fires on initial breakout above ceiling or below floor, and separately on confirmed breakout (retested and bounced).
R · Retest (2 alerts) — fires when price returns to test the boundary after establishing distance.
S · Structural (5 alerts) — fires on gap-through events (price crosses entire channel), failed breakouts (price re-enters channel), and direction resets (trend change wipes state).
A · Agreement (5 alerts) — fires when cross-scale consensus reaches significant thresholds: full bullish (6/6), strong bullish (5/6), full bearish (6/6), strong bearish (5/6), or range consensus (≥4/6).
Important: alerts require Calculation Bar = Live Bar. In Close Bar mode, all alert conditions are automatically suppressed and a visual warning is displayed on the chart — because Close Bar mode intentionally lags by one bar, which is semantically incompatible with live alert delivery.
🔷 LANGUAGE SUPPORT
The dashboard, all tooltips, the breakout/retest narrative, and the alert warning label are available in 7 languages:
English · Türkçe · العربية · Русский · Italiano · Português (BR) · 中文
Select the preferred language from the Language dropdown in the Display settings group. All structural and numerical outputs remain unchanged — only the display language of text elements is affected.
🔷 HOW TO USE
Apply ST-EP06 to any chart — the indicator is designed to work across instruments (equities, forex, crypto, commodities, indices) and timeframes without parameter re-optimization, because the ICS framework normalizes for volatility and price level automatically.
Start with the default settings (Period 26, Groups 5, Sigma Length 20) and observe how the channel captures the dominant structural trend. The 6-scale consensus in the dashboard may help assess whether the observed trend is isolated to one temporal resolution or confirmed across multiple scales.
The Calculation Bar setting is a structural decision: use Live Bar for real-time monitoring and alert-driven workflows; use Close Bar for analysis and back-testing where historical stability is prioritized.
The ICS angle on the direction label provides a quantitative measure of trend intensity. Comparing angles across different instruments or timeframes is one of the intended use cases of the ICS framework — a 15° angle on one chart and a 15° angle on another may suggest similar structural momentum relative to each market's own volatility.
The breakout/retest narrative in the dashboard bottom row is designed to provide context-rich status updates without requiring manual chart reading. The σ-based thresholds ensure that breakout sensitivity adapts to current market conditions rather than relying on fixed values.
🔷 SETTINGS
Calculation — Calculation Bar (Live/Close Bar anchoring), Trend Block Period (bars per block), Trend Block Groups (consecutive blocks compared), Range Threshold (ICS dead zone in degrees), Yang-Zhang Sigma Length (volatility lookback).
Channel Lines — Up Color, Down Color, Range Color, Line Width, Line Style.
Projection Lines — Projection Offset (forward bars), Projection Width, Projection Style.
Display — Language (7 options), Show Channel (toggle overlay), Show Fill (toggle shading), Show Dashboard (toggle table), Dashboard Font Size.
Channel Fill — Fill Up Color, Fill Down Color, Fill Range Color, Fill Transparency.
Alerts — Enable Alerts (master toggle, requires Live Bar mode).
🔷 DISCLAIMER
ST-EP06 is an educational and analytical tool. It is designed to provide structural context through σ-normalized trend channels and multi-scale analysis. It does not generate buy or sell signals, does not predict future price movement, and is not intended as financial advice. Historical patterns observed through this indicator do not guarantee future outcomes. All trading decisions remain the sole responsibility of the trader.
Indicator

KernelLens🟦 KernelLens is a professional kernel regression library for Pine Script v6, providing eight mathematically rigorous Nadaraya–Watson estimators, a three-mode filter layer, a unified string dispatcher, and a suite of trading utilities — all built from the ground up on correct non-parametric statistics. Unlike existing Pine smoothing libraries — which inherit a decade-old loop-bound bug that silently reduces every kernel window to a handful of bars, regardless of the bandwidth parameter — KernelLens is built with auditable math, NA-safe iteration, input validation at every entry point, and academic references cited inline next to the formulas they describe.
The library integrates eight independent kernel families — Rational Quadratic, Gaussian, Periodic, Locally Periodic, Epanechnikov, Tricube, Triangular, and Cosine — behind a consistent API, with every raw estimator wrapped in a filter layer (None / Smooth / Zero Lag), a unified dispatcher for dropdown-driven kernel selection, and five utility exports covering slope detection, trend state, crossover signaling, residual confidence bands, and Silverman's rule-of-thumb bandwidth recommendation. Every public function validates its inputs, raises descriptive runtime errors on misuse, and returns `na` only when there is genuinely no data — never as a silent fallback.
🟦 MATHEMATICAL FOUNDATION
**The Nadaraya–Watson Estimator**
Given a source series `y_t` and a symmetric kernel `K` with scale parameter `ℓ` (the "bandwidth"), the Nadaraya–Watson estimator of the regression function `m(x) = E ` evaluated at the current bar is:
```
Σᵢ K(dᵢ / ℓ) · y_{t−i}
ŷ(t) = ───────────────────────
Σᵢ K(dᵢ / ℓ)
```
where `dᵢ` is the bar-distance from the kernel center and the sum runs over a finite window determined by the effective support of `K`.
The estimator is a locally weighted average: bars close to the kernel center contribute heavily, distant bars contribute proportionally less, and bars outside the support contribute nothing. It is asymptotically unbiased up to `O(ℓ²)` for twice-differentiable `m`, with variance of order `(n·ℓ)⁻¹` — the classical bias–variance trade-off that defines all non-parametric smoothers.
**Why Kernel Regression Beats Rolling Means**
A simple moving average gives every bar in the window the same weight. Kernel regression gives each bar a weight that decays smoothly with distance, producing:
- **Smoother output** — no step artifacts when bars enter / leave the window
- **Better bias control** — the peak of the kernel sits exactly on the point being estimated
- **Kernel-specific behavior** — compact-support kernels eliminate tail contamination entirely; Rational Quadratic's `α` parameter exposes multi-scale mixing; Periodic kernels resonate with known cycle lengths
The math has been the academic standard for non-parametric regression since Nadaraya (1964) and Watson (1964). KernelLens brings it to Pine Script v6 in its correct, bug-free form.
🟦 THE EIGHT KERNELS
All eight kernels implement the Nadaraya–Watson weighting scheme. They differ in support (compact versus infinite), smoothness (how many times differentiable), and how weight decays with distance.
| # | Kernel | Formula | Support | Smoothness | Character |
|---|---|---|---|---|---|
| 1 | **Rational Quadratic** | `(1 + d² / (2·α·ℓ²))^(−α)` | ℝ | C∞ | Multi-scale mixer — `α` controls stretch versus wiggle |
| 2 | **Gaussian (RBF)** | `exp(−d² / (2·ℓ²))` | ℝ | C∞ | The canonical smoother — smoothest possible with L² optimality |
| 3 | **Periodic** | `exp(−2·sin²(π·d/p) / ℓ²)` | ℝ | C∞ | Resonates with repetition distance `p` — ideal for cycles |
| 4 | **Locally Periodic** | Periodic · Gaussian | ℝ | C∞ | Seasonal patterns that slowly drift with trend |
| 5 | **Epanechnikov** | `(3/4)(1 − u²) · 𝟙{|u|≤1}` | | C⁰ | Asymptotically MSE-optimal (Watson 1964) — no tail contamination |
| 6 | **Tricube** | `(70/81)(1 − \|u\|³)³ · 𝟙{|u|≤1}` | | C² | The LOWESS standard — near-Gaussian with compact support |
| 7 | **Triangular** | `(1 − \|u\|) · 𝟙{|u|≤1}` | | C⁰ | Simplest non-uniform kernel — fastest to compute |
| 8 | **Cosine** | `(π/4)·cos(π·u/2) · 𝟙{|u|≤1}` | | C¹ | Raised-cosine taper — smoother boundary than Epanechnikov |
where `u = d/ℓ` and `𝟙` is the indicator function.
**Infinite-Support vs Compact-Support — Why Both Matter**
| | Infinite Support (RQ, Gauss, Periodic, LocPeriodic) | Compact Support (Epa, Tricube, Triangular, Cosine) |
|---|---|---|
| **Tail weight** | Never exactly zero | Exactly zero beyond ±ℓ |
| **Loop depth** | `3·ℓ` (3-σ cutoff, ≈99.7% mass) | Exactly `ℓ` |
| **Bar contamination** | Distant bars still pull the estimate a tiny amount | Distant bars cannot affect the estimate at all |
| **Best for** | Smooth trends, Gaussian-process intuition | Robust regression, outlier resistance |
KernelLens picks the correct loop depth automatically based on kernel family: `_depthInfinite` for Gaussian-family kernels, `_depthCompact` for bounded kernels, `_depthPeriodic` for Periodic (which must span enough cycles to reach stable weights).
**Why Eight, Not Four**
Most Pine kernel libraries ship only the four kernels from MacKay's Gaussian process tutorial. KernelLens adds the four compact-support classical kernels because:
- **Epanechnikov** minimises asymptotic mean squared error among all non-negative kernels of bounded support (Watson 1964) — it is the MSE-optimal baseline against which all other kernels are measured
- **Tricube** is the kernel used by LOWESS (Cleveland 1979), the de-facto standard for robust locally weighted scatterplot smoothing
- **Triangular** is the cheapest non-uniform compact kernel — useful when loop-budget matters on intraday charts with huge dataset size
- **Cosine** is C¹-continuous at the support boundary, unlike Epanechnikov's C⁰ discontinuity, producing visibly smoother transitions at kernel edges
Adding them makes the library an academically complete toolkit, not just a Pine port of one tutorial.
🟦 FILTER LAYER — NONE / SMOOTH / ZERO LAG
Every kernel export accepts a `_filter` parameter with three valid values. The filter layer is implemented identically across all eight kernels, so switching kernel families does not change filter behavior.
**"No Filter" — Single-Pass Raw Estimate**
```
ŷ = K(y)
```
One Nadaraya–Watson pass over the source. Cheapest mode, most reactive, fully represents the underlying kernel. Use this when you want the kernel's raw behavior with no additional smoothing or lag correction.
**"Smooth" — Double-Pass Estimate**
```
ŷ = K(K(y))
```
The kernel is applied once to the source, then applied again to its own output using the same bandwidth and the same parameters. The result is a more strongly smoothed curve at the cost of one extra loop pass per bar.
This is mathematically equivalent to convolving the kernel with itself — the effective kernel is wider and flatter, pulling longer-range context into each estimate without requiring the user to double the bandwidth.
**"Zero Lag" — Ehlers De-Lagged Estimate**
```
ŷ = 2·K(y) − K(K(y))
```
The ZLEMA identity from Ehlers (*Rocket Science for Traders*, 2000): subtract the smoothing lag from the raw estimate, effectively shifting the output back in time to match the source more closely.
The intuition: `K(y)` lags `y` by some amount; `K(K(y))` lags `K(y)` by the same amount; so `K(y) − K(K(y))` is an estimate of the lag itself, and adding it back to `K(y)` cancels out. The result tracks the source more tightly than either pass alone, at the cost of slightly noisier turning points.
**Lazy Evaluation — No Wasted Cycles**
In `"No Filter"` mode, the second pass is skipped entirely — it never runs. The filter branch uses an `if` block (not a ternary), so Pine's short-circuit semantics prevent the unused computation. A single kernel call costs one pass; `"Smooth"` or `"Zero Lag"` costs two. You only pay for what you use.
🟦 KERNEL CENTER OFFSET — THE `_phase` PARAMETER
Every KernelLens kernel takes a `_phase` parameter that shifts the kernel center into the past by `_phase` bars. It is the library's non-repainting knob.
**_phase = 0 — Live Estimate**
The kernel is centered on the current bar. The most recent price has maximum weight, and the estimate is as fresh as possible. Suitable for live signal generation, but the most recent bar can re-evaluate as it develops within its interval — standard Pine real-time behavior.
**_phase > 0 — Non-Repainting Historical Estimate**
The kernel center is moved `_phase` bars into the past. The estimate becomes the smoothed value *at that historical bar*, not the current bar. Once the bar at `bar_index − _phase` is fully confirmed (`barstate.isconfirmed`), its estimate cannot change again.
This is the standard trick for publishing kernel indicators that do not repaint: you get a stable, historically accurate curve at the cost of shifting the entire output `_phase` bars to the right on the chart. A `_phase = 25` call gives a curve that lags live price by 25 bars but is guaranteed stable for every past bar.
**Why It Belongs in the Library, Not the Caller**
Pushing `_phase` into the kernel's own loop is not the same as evaluating the kernel at a shifted source (`K(src )`). Shifting the source just uses a stale input with a current-bar-centered kernel, which still produces a fresh estimate of a stale series. KernelLens's `_phase` genuinely moves the kernel center, producing a historical-bar estimate that computes over the correct surrounding window.
🟦 NON-REPAINTING BEHAVIOR
Repainting is the single most-asked question about any Pine indicator, and the single most common source of silent failure when a retail trader moves from backtest to live. A strategy that looks flawless on historical bars and then bleeds money the moment it is deployed is almost always suffering from some form of repainting. KernelLens is engineered from first principles to eliminate every class of repainting by construction — not by patching symptoms, but by removing the dependencies that cause repainting in the first place.
**The Two Forms of Repainting**
| Form | Symptom | Typical Cause |
|---|---|---|
| **Historical repainting** | A bar that was closed days or weeks ago silently changes its plotted value when the chart is refreshed or scrolled | `request.security()` with `lookahead = barmerge.lookahead_on`, un-gated higher-timeframe data, or incorrect array rotation that reads into future bars |
| **Real-time repainting** | The plotted value on the live (current developing) bar flickers tick-by-tick as new price ticks arrive, then freezes at a final value when the bar closes | The indicator reads `close ` (or any current-bar value) inside a weighted sum — the current-bar weight changes every tick |
KernelLens avoids the first kind **entirely and unconditionally**: the library contains no `request.security` calls, no higher-timeframe lookups, no `lookahead_on` usage, and no array rotation that could leak future bars into the window. Every historical bar plotted by any KernelLens kernel is computed exclusively from bars that existed at the time that bar was closed. The plotted history is immutable.
Real-time repainting is controlled explicitly by the `_phase` parameter — it is the user's choice whether to accept tick-by-tick flicker on the live bar in exchange for zero lag (`_phase = 0`) or to eliminate the flicker entirely at the cost of a small fixed lag (`_phase ≥ 1`).
**Why Kernel Regression Normally Repaints (And How KernelLens Stops It)**
A traditional Nadaraya–Watson call centered on the current bar evaluates:
```
ŷ(t) = Σᵢ K(dᵢ/ℓ) · y_{t−i} for i = 0 … depth
```
On the live bar, the term `y_{t−0} = close ` is the current real-time price — which changes on every tick. Every tick moves the weighted sum, every tick moves the estimate, and the trader watching the chart sees the kernel plot flicker as the bar develops. The historical bars (where `close ` for that past bar is now fixed) are stable, but the live plot is unstable.
KernelLens's `_phase` parameter shifts the loop so the kernel runs over `i = _phase … _phase + depth`. With `_phase = 2`:
```
ŷ(t) = Σᵢ K((i−2)/ℓ) · y_{t−i} for i = 2 … 2 + depth
```
The sum no longer touches `close ` or `close ` — every bar it reads is already confirmed and cannot change. The live-bar kernel output is therefore identical from the first tick of the bar to the last tick of the bar, and identical again when the bar finally closes. There is no flicker and nothing to repaint.
**The Lag / Stability Trade-Off**
| `_phase` | Lag on Live Bar | Live-Bar Flicker | Historical Repainting | Best For |
|---|---|---|---|---|
| **0** | 0 bars | Yes (real-time only; history is stable) | None | Scalping, academic research, calibration |
| **1** | 1 bar | None | None | Fast day-trading; minimum acceptable lag for a live trading desk |
| **2** | 2 bars | None | None | Default for most users — the sweet spot between freshness and stability |
| **3** | 3 bars | None | None | Swing trading — extra margin against false flickers from erratic ticks |
| **5+** | 5+ bars | None | None | Position trading, long-term chart analysis, published signal marks |
Even at `_phase = 0`, **historical repainting never occurs** — only the live bar flickers during its own development. Once a bar closes, its plotted value is final; scrolling away and back, refreshing the chart, or re-opening PulseWire will never change that historical plot. The flicker is exclusively a live-bar tick-by-tick phenomenon.
**KernelLens as a Non-Repainting Primitive**
KernelLens exposes real-time flicker as an explicit, user-controlled trade-off rather than a hidden behavior. The caller picks any point on the spectrum from "fully live" (`_phase = 0`, maximum reactivity with tick-by-tick flicker) to "fully confirmed" (`_phase ≥ 1`, one or more bars of lag in exchange for a curve that never redraws) with a single integer parameter. Historical repainting — the dangerous form that silently rewrites past plots — is eliminated unconditionally regardless of `_phase`.
**How to Verify Non-Repainting Yourself**
Do not trust the word "non-repainting" from any library — always verify. KernelLens can be verified in about thirty seconds:
1. Load a chart with KernelLens on it using `_phase = 2` (or any value > 0).
2. Take a screenshot at any specific historical bar.
3. Scroll far to the left, refresh the chart, or reload the indicator.
4. Return to the same bar. The plotted value at that bar must be pixel-identical to the screenshot — because the computation on that bar used only the bars before it, which have not changed.
5. Repeat with `_phase = 0`. The historical bars must still be pixel-identical — only the live bar's plot can differ between observations, and only because the live bar's `close` is now a different number than it was when you took the screenshot.
For a stricter test, use PulseWire's **Bar Replay** mode. Enable Bar Replay, step forward one bar at a time, and watch the kernel plot on each newly-closed bar. With `_phase ≥ 1`, the value plotted on each newly-closed bar will exactly match what the indicator shows after you exit replay mode and view the same bar normally. This is the gold-standard test — Bar Replay reproduces live-bar tick arrival in a controlled way.
**Common Misconceptions**
> *"Any Pine indicator that uses `close` repaints."*
False. Using `close` on a confirmed bar does not repaint — the confirmed bar's close is locked. What can repaint is using `close` on the live bar, and only within that live bar's interval. KernelLens with `_phase > 0` never reads the live-bar close at all.
> *"`lookahead = barmerge.lookahead_on` is always wrong."*
Context-dependent. `lookahead_on` is used correctly in some multi-timeframe indicators to request a higher-TF value that is already settled on the lower TF. KernelLens does not use `request.security` at all, so this question does not apply — but for libraries that do, `lookahead_on` is only problematic when it leaks values from bars that were not yet closed at the lower-TF time of evaluation.
> *"Non-repainting means zero lag."*
False. Zero lag and non-repainting are orthogonal properties. KernelLens `_phase = 0` is zero lag with real-time flicker; `_phase = 2` is two-bar lag with no flicker. You can have any combination of the two, and the right choice depends on the trading style.
> *"The `FILTER_ZEROLAG` mode makes the indicator non-repainting."*
False. `FILTER_ZEROLAG` is an Ehlers-style de-lagging filter applied to the kernel output; it reduces the perceived lag of the estimate, but it does not affect whether the live bar flickers. Non-repainting is controlled exclusively by `_phase`. Choose `_phase` for repainting behavior, and `_filter` for smoothness / lag shape — they are independent knobs.
**When to Accept Real-Time Flicker (`_phase = 0`)**
Despite everything above, there are legitimate reasons to deliberately use `_phase = 0`:
- **Academic research and backtesting** — you want the kernel mathematics in its classical form, centered on the point being estimated, with no phase adjustment
- **Scalping on very short timeframes** — a 2-bar lag on a 1-minute chart is a 2-minute delay, which can matter when you are exiting within a 4-minute window
- **Visual calibration** — when you are choosing a bandwidth by eye, the live-bar flicker actually helps: you see how sensitive the curve is to each incoming tick, which is diagnostic information
- **Indicators that read the kernel output only on `barstate.isconfirmed`** — if your signal logic is gated by `if barstate.isconfirmed`, then live-bar flicker is invisible to your signal (it sees only the frozen close-of-bar value), and you can safely use `_phase = 0` with no practical consequence
For every other case — and especially for any live alert or automated trading system — use `_phase ≥ 1`. Two bars of lag on a clean, stable curve is almost always worth more than zero lag on a curve that redraws itself several times per bar.
🟦 UNIFIED DISPATCHER — `estimate()`
For indicators where the user picks a kernel from a dropdown, writing eight separate ternary branches is tedious and error-prone. KernelLens ships with a unified dispatcher that routes to the correct kernel based on a string argument:
```pine
import a_jabbaroff/KernelLens/1 as kl
line = kl.estimate(
kernelType = kl.KERNEL_GAUSS,
src = close,
bandwidth = 32,
shapeAlpha = 1.0,
period = 1,
phase = 2,
filter = kl.FILTER_SMOOTH)
```
The dispatcher forwards to the matching typed export, so there is no performance penalty versus calling the kernel directly — it is a compile-time routing pass. Unknown kernel names raise a descriptive `runtime.error` naming every valid alternative, so typos fail loudly instead of silently returning `na`.
**Public Constants**
KernelLens exposes its string constants so callers never type the magic values by hand:
| Constant | Value |
|---|---|
| `FILTER_NONE` | `"No Filter"` |
| `FILTER_SMOOTH` | `"Smooth"` |
| `FILTER_ZEROLAG` | `"Zero Lag"` |
| `KERNEL_RQ` | `"Rational Quadratic"` |
| `KERNEL_GAUSS` | `"Gaussian"` |
| `KERNEL_PERIODIC` | `"Periodic"` |
| `KERNEL_LOCPER` | `"Locally Periodic"` |
| `KERNEL_EPA` | `"Epanechnikov"` |
| `KERNEL_TRICUBE` | `"Tricube"` |
| `KERNEL_TRIANG` | `"Triangular"` |
| `KERNEL_COSINE` | `"Cosine"` |
Using the constants in your caller code means the Pine compiler — not a runtime string compare — catches typos at edit time.
🟦 UTILITY LAYER — FIVE PROFESSIONAL HELPERS
KernelLens ships with five utility exports that complement the core estimators. They are the functions you almost always write immediately after getting a smoothed line, factored out so you don't rewrite them in every indicator.
**`slope(estimate, step)` — Discrete First Derivative**
Returns `(y_t − y_{t−step}) / step`, the normalized rate of change over `step` bars. Use it to detect whether a kernel output is trending up, flat, or down — the foundation for any trend-following signal built on top of KernelLens.
```pine
rising = kl.slope(line, 3) > 0.0
```
**`trendState(estimate, step)` — Ternary Trend Indicator**
Returns `+1` if the estimate is rising, `−1` if falling, `0` if exactly flat over the window. A single-call replacement for hand-rolled `line > line ? 1 : line < line ? -1 : 0` ladders.
**`crossSignal(fast, slow)` — Bi-directional Crossover**
Returns `+1` on the bar where `fast` crosses above `slow` (bullish), `−1` on a bearish cross, and `0` otherwise. Built on `ta.crossover` / `ta.crossunder`, so the signal is non-repainting once the bar is confirmed.
**`confidenceBand(src, estimate, window)` — Residual Standard Deviation**
Computes the rolling standard deviation of `(src − estimate)` over a user-defined window. Use the return value as the half-width of a confidence band around the estimate:
```pine
est = kl.gaussian(close, 32, 2, kl.FILTER_SMOOTH)
sigma = kl.confidenceBand(close, est, 50)
upper = est + 1.96 * sigma
lower = est - 1.96 * sigma
```
This is a computationally cheap proxy for the full kernel-weighted local variance — ideal when you need visual bands without paying for a second weighted pass.
**`silvermanBandwidth(src, window)` — Optimal ℓ Suggestion**
Returns the Silverman rule-of-thumb bandwidth:
```
h ≈ 1.06 · σ · n^(−1/5)
```
where `σ` is the rolling standard deviation of the source and `n` is the window size. This is the classical starting point for Gaussian-family bandwidths in academic texts (Silverman 1986). Because Pine requires `simple int` for kernel bandwidth, the returned value is intended for diagnostic display — plot it, read it off the chart, then hard-code the rounded integer into the kernel call.
🟦 INPUT VALIDATION — FAIL LOUDLY, FAIL EARLY
Every public function in KernelLens validates its inputs through a set of internal `_assert*` helpers. Invalid arguments never produce silent `na` fallbacks or buried zero-divisions — they raise `runtime.error` with a descriptive message identifying the function, the parameter, and the expected range.
| Helper | Checks | Raises On |
|---|---|---|
| `_assertFilter` | Filter string is `FILTER_NONE`, `FILTER_SMOOTH`, or `FILTER_ZEROLAG` | Typos like `"No FIlter"` (capital I) — a bug that exists in at least one published kernel indicator |
| `_assertBandwidth` | Bandwidth is a strictly positive integer | Negative or zero bandwidth, which would cause division by zero or infinite loops |
| `_assertPeriod` | Period is a strictly positive integer | Zero period, which would cause `sin(π·d/0)` in Periodic kernels |
| `_assertAlpha` | Rational Quadratic shape parameter is strictly positive | Zero or negative `α`, which would invert the RQ formula |
Error messages are prefixed `KernelLens:` (or `KernelLens.:`) so they are easy to spot in the PulseWire runtime log. Every message names the parameter that failed, the value that was passed, and the set of valid alternatives — so a misconfigured chart tells you exactly what to fix.
🟦 LOOP DEPTH — THE BUG FIX THAT MOTIVATED KERNELLENS
The two most popular Pine kernel libraries on PulseWire share the same fatal bug: both compute their loop depth as
```pine
_size = array.size(array.from(_src))
```
where `array.from(_src)` creates a **one-element array containing the current value of `_src`**, so `_size` is always `1`. The loop then runs `for i = 0 to 1 + startAtBar`, effectively using only `startAtBar + 2` bars — completely ignoring the user's bandwidth. Every published kernel indicator built on those libraries inherits this silent miscalculation.
KernelLens replaces the broken helper with three explicit depth selectors:
| Helper | Depth | Used By |
|---|---|---|
| `_depthInfinite(bw)` | `max(bw · 3, 4)` | Gaussian, Rational Quadratic, Locally Periodic |
| `_depthCompact(bw)` | `max(bw, 4)` | Epanechnikov, Tricube, Triangular, Cosine |
| `_depthPeriodic(bw, p)` | `max(bw · 3, p · 10, 4)` | Periodic |
For Gaussian-family kernels, the `3·ℓ` cutoff captures approximately 99.7% of the kernel mass (the three-sigma rule). For compact-support kernels, the depth equals the bandwidth exactly — the loop terminates at the kernel's natural zero point. For Periodic kernels, the depth is the larger of the scale-based and cycle-based minima, so the loop always spans enough periods to produce a stable weighted average.
The loop counter `i` runs over bar offsets starting at `_phase`, every bar lookup is NA-checked before being incorporated into the sum, and the final `num / den` division is guarded against zero denominators. On a fresh chart, the kernel gracefully returns `na` for bars where the window extends past available history, rather than producing poisoned sums from implicit NA arithmetic.
🟦 API REFERENCE
**Core Kernel Estimators — Eight Exports**
| Export | Signature |
|---|---|
| `rationalQuadratic` | `(src, bandwidth, shapeAlpha, phase, filter) → float` |
| `gaussian` | `(src, bandwidth, phase, filter) → float` |
| `periodic` | `(src, bandwidth, period, phase, filter) → float` |
| `locallyPeriodic` | `(src, bandwidth, period, phase, filter) → float` |
| `epanechnikov` | `(src, bandwidth, phase, filter) → float` |
| `tricube` | `(src, bandwidth, phase, filter) → float` |
| `triangular` | `(src, bandwidth, phase, filter) → float` |
| `cosineKernel` | `(src, bandwidth, phase, filter) → float` |
**Unified Dispatcher**
| Export | Signature |
|---|---|
| `estimate` | `(kernelType, src, bandwidth, shapeAlpha, period, phase, filter) → float` |
**Utility Layer — Five Exports**
| Export | Signature |
|---|---|
| `slope` | `(estimate, step) → float` |
| `trendState` | `(estimate, step) → int` |
| `crossSignal` | `(fast, slow) → int` |
| `confidenceBand` | `(src, estimate, window) → float` |
| `silvermanBandwidth` | `(src, window) → float` |
**Parameter Types**
| Name | Pine Type | Description |
|---|---|---|
| `src` | `series float` | Source series (close, hl2, ohlc4, or any other price-derived series) |
| `bandwidth` | `simple int` | Kernel scale `ℓ`, must be `> 0` |
| `shapeAlpha` | `simple float` | Rational Quadratic shape parameter, must be `> 0` |
| `period` | `simple int` | Periodic repetition distance, must be `> 0` |
| `phase` | `simple int` | Kernel center offset in bars, must be `≥ 0` |
| `filter` | `simple string` | One of `FILTER_NONE`, `FILTER_SMOOTH`, `FILTER_ZEROLAG` |
| `kernelType` | `simple string` | One of the eight `KERNEL_*` constants |
| `step` | `simple int` | Finite-difference step for `slope` / `trendState`, must be `≥ 1` |
| `window` | `simple int` | Rolling window for `confidenceBand` / `silvermanBandwidth`, must be `≥ 2` |
🟦 USAGE EXAMPLES
**Minimal — One Gaussian Curve**
```pine
//@version=6
indicator("KernelLens — Gaussian Demo", overlay = true)
import a_jabbaroff/KernelLens/1 as kl
line = kl.gaussian(close, 32, 2, kl.FILTER_SMOOTH)
plot(line, "Gaussian", color = color.orange, linewidth = 2)
```
**Fast / Slow Crossover System**
```pine
//@version=6
indicator("KernelLens — RQ Crossover", overlay = true)
import a_jabbaroff/KernelLens/1 as kl
fast = kl.rationalQuadratic(close, 8, 1.0, 2, kl.FILTER_NONE)
slow = kl.rationalQuadratic(close, 32, 1.0, 2, kl.FILTER_SMOOTH)
cross = kl.crossSignal(fast, slow)
plot(fast, "Fast", color = color.aqua, linewidth = 2)
plot(slow, "Slow", color = color.orange, linewidth = 2)
plotshape(cross == 1, "Bull", location = location.belowbar,
color = color.lime, style = shape.triangleup, size = size.tiny)
plotshape(cross == -1, "Bear", location = location.abovebar,
color = color.red, style = shape.triangledown, size = size.tiny)
```
**Confidence Band Envelope**
```pine
//@version=6
indicator("KernelLens — Confidence Band", overlay = true)
import a_jabbaroff/KernelLens/1 as kl
est = kl.tricube(close, 48, 2, kl.FILTER_SMOOTH)
sigma = kl.confidenceBand(close, est, 50)
k = 1.96
upper = est + k * sigma
lower = est - k * sigma
plot(est, "Estimate", color = color.orange, linewidth = 2)
p1 = plot(upper, "+1.96σ", color = color.new(color.aqua, 70))
p2 = plot(lower, "−1.96σ", color = color.new(color.aqua, 70))
fill(p1, p2, color = color.new(color.aqua, 92))
```
**Dropdown-Driven Kernel Selection**
```pine
//@version=6
indicator("KernelLens — Dropdown", overlay = true)
import a_jabbaroff/KernelLens/1 as kl
kernelType = input.string(kl.KERNEL_GAUSS, "Kernel",
options = )
bandwidth = input.int(32, "Bandwidth", minval = 2)
alphaRQ = input.float(1.0,"RQ Alpha", minval = 0.01, step = 0.25)
period = input.int(20, "Period", minval = 1)
phase = input.int(2, "Phase", minval = 0)
filter = input.string(kl.FILTER_SMOOTH, "Filter",
options = )
line = kl.estimate(kernelType, close, bandwidth, alphaRQ, period, phase, filter)
plot(line, "KernelLens", color = color.orange, linewidth = 2)
```
🟦 TIMEFRAME PRESETS — BANDWIDTH BY STYLE
Kernel bandwidth is the single most important parameter. It controls the trade-off between reactivity (small `ℓ`, tight fit, noisier) and stability (large `ℓ`, smooth curve, slower to react). The presets below are tested starting points — adjust by ±25 % to taste.
---
**SCALPER — 1m / 3m / 5m**
| Parameter | Value |
|---|---|
| Bandwidth (ℓ) | 8 |
| Phase | 1 |
| Filter | `FILTER_NONE` |
| Best Kernel | Rational Quadratic or Gaussian |
| RQ shapeAlpha | 1.0 |
**Why:** Short bandwidth means the kernel reacts within a handful of bars. `FILTER_NONE` removes the double-pass lag, so the estimate tracks price as tightly as possible. Phase 1 keeps the estimate nearly live while still avoiding the current-bar tick noise.
---
**DAY TRADER — 15m / 30m / 1H**
| Parameter | Value |
|---|---|
| Bandwidth (ℓ) | 16 |
| Phase | 2 |
| Filter | `FILTER_SMOOTH` |
| Best Kernel | Gaussian or Tricube |
| RQ shapeAlpha | 1.0 |
**Why:** Balanced reactivity — the 16-bar Gaussian is the default Silverman range for intraday price data, and `FILTER_SMOOTH` removes most of the bar-to-bar chop without significantly increasing lag. Tricube provides near-identical behaviour with strict compact support and is preferred on noisy assets where outlier bars should not influence the curve.
---
**SWING TRADER — 4H / 1D**
| Parameter | Value |
|---|---|
| Bandwidth (ℓ) | 32 |
| Phase | 3 |
| Filter | `FILTER_SMOOTH` |
| Best Kernel | Rational Quadratic |
| RQ shapeAlpha | 2.0 |
**Why:** Swing trades need structural signals, not intraday noise. Rational Quadratic with `α = 2.0` mixes medium and long length scales, producing a curve that ignores transient spikes but catches genuine regime shifts. Phase 3 shifts the estimate three bars back so each swing decision is made against a fully confirmed kernel output.
---
**POSITION / LONG-TERM — 1D / 1W / 1M**
| Parameter | Value |
|---|---|
| Bandwidth (ℓ) | 64 |
| Phase | 5 |
| Filter | `FILTER_SMOOTH` or `FILTER_ZEROLAG` |
| Best Kernel | Gaussian or Locally Periodic |
| Period (if LP) | 52 (weekly cycle) |
**Why:** Position traders care about the macro trajectory. A Gaussian with ℓ = 64 produces a curve that only turns on genuine multi-month inflections. Locally Periodic with `period = 52` is the ideal choice when a clear seasonal cycle is present — it uses both the long-range Gaussian envelope and the 52-bar periodicity to highlight cycle turns that align with trend.
---
**RESEARCH — Academic / Backtest**
| Parameter | Value |
|---|---|
| Bandwidth (ℓ) | Compute via `silvermanBandwidth(src, 200)` |
| Phase | 0 |
| Filter | `FILTER_NONE` |
| Best Kernel | Epanechnikov |
**Why:** Epanechnikov is the MSE-optimal kernel; `FILTER_NONE` keeps the estimator in its classical single-pass form; `phase = 0` centers the kernel on the bar being evaluated. This is the configuration that matches the statistical literature exactly — use it when publishing research, running Monte-Carlo studies, or calibrating against reference implementations.
🟦 BANDWIDTH SELECTION
Bandwidth `ℓ` is the single most consequential choice in kernel regression. Too small and the estimate overfits local noise; too large and it flattens real structure. KernelLens exposes two helpers to support both manual and semi-automated bandwidth selection.
**Manual — Start with ℓ ≈ √n**
A practical starting point for financial time series: set `ℓ ≈ √window_of_interest`. If you care about 100-bar structure, try `ℓ = 10`. If you care about 400-bar structure, try `ℓ = 20`. Adjust by ±25 % based on how noisy the result looks.
**Silverman's Rule of Thumb**
The closed-form optimal bandwidth for Gaussian-family kernels under Gaussian source assumptions:
```
h ≈ 1.06 · σ · n^(−1/5)
```
Call `silvermanBandwidth(src, window)` to compute this value live. Because Pine requires `simple int` bandwidth at compile time, the returned value is for diagnostic use — plot it, read the stable value off the chart, then hard-code the rounded integer into your kernel calls.
**Leave-One-Out Cross-Validation (Manual)**
For academic rigor, compute the leave-one-out mean squared error for a range of bandwidths and pick the minimum. KernelLens does not automate this (it would require `series int` bandwidth, which Pine does not support inside kernel loops), but the formula is straightforward:
```
LOOCV(ℓ) = (1/n) · Σᵢ (yᵢ − ŷᵢ⁻ⁱ(ℓ))²
```
where `ŷᵢ⁻ⁱ` is the kernel estimate at bar `i` computed without including bar `i` in the sum. Evaluate offline, pick the minimum, hard-code the result.
🟦 FILTER SELECTION — WHEN TO USE EACH
| Filter | Best For | Avoid When |
|---|---|---|
| `FILTER_NONE` | Live signal generation, research / calibration, compact-support kernels on noisy data | Choppy markets where you need extra smoothing |
| `FILTER_SMOOTH` | Swing and position trades, confidence band midlines, most day-trading setups | Scalping — the double pass adds measurable lag |
| `FILTER_ZEROLAG` | Regime detection, crossover systems that need the curve to track price tightly | Low-volume assets — Zero Lag amplifies high-frequency noise |
The three filters use the same underlying kernel with the same bandwidth, so switching between them does not require re-tuning. Default to `FILTER_SMOOTH` when in doubt — it is the best-behaved option across the widest range of assets and timeframes.
🟦 COMPATIBILITY
KernelLens targets Pine Script v6 and runs on every PulseWire chart — no exchange, asset class, or timeframe restriction.
- **Crypto** — Spot, futures, perpetual contracts
- **Forex** — All majors, minors, and exotics
- **Equities** — Stocks, ETFs, indices
- **Commodities** — Metals, energy, agriculture
- **Timeframes** — 1 minute through Monthly
The library is deterministic — given the same source and parameters, every bar of every symbol produces the same estimate. No calibration is needed across assets; the bandwidth parameter alone controls smoothness, and the kernel formulas are scale-free in the source dimension. Silverman's bandwidth helper automatically adapts to each asset's volatility.
🟦 TECHNICAL NOTES
- **Pine Script v6** — uses the modern type system, strict type checking, and the `switch` expression in the unified dispatcher
- **Non-repainting** — kernel outputs for any confirmed bar depend only on that bar's history; there is no look-ahead, no `request.security` with lookahead, and no dependency on the unconfirmed current bar unless `_phase = 0` is deliberately chosen
- **NA-safe iteration** — every bar lookup inside a kernel loop is guarded by `if not na(y)`, so chart history gaps and warm-up bars cannot poison the weighted sum
- **Division-by-zero protection** — every kernel's final division checks `den > 0.0` and returns `na` if the denominator collapses (which can only happen on truly empty windows)
- **Input validation** — every public function asserts its preconditions up front via `_assertFilter`, `_assertBandwidth`, `_assertPeriod`, `_assertAlpha`, and raises `runtime.error` with a descriptive message on misuse — no silent `na` fallbacks
- **Lazy filter evaluation** — the `"No Filter"` path never executes the second kernel pass; the `if`-branch check short-circuits, so single-pass mode is as cheap as a raw kernel call
- **Correct loop bounds** — `_depthInfinite`, `_depthCompact`, and `_depthPeriodic` compute the correct window size per kernel family, fixing the silent `_size = 1` bug that plagues every other published Pine kernel library
- **No persistent state** — the library is purely functional: no `var`, no arrays, no history buffers that grow over time; every export is a pure expression of `(inputs) → output`, so Pine's `max_*_count` limits cannot be exceeded and the library cannot leak memory
- **O(bandwidth) per bar per kernel call** — the loop depth is bounded by the constants in Section 0; there is no hidden quadratic behavior and the cost scales linearly with the user-chosen bandwidth
- **Unicode-safe comments** — the source uses academic notation (`σ`, `ℓ`, `α`, `ŷ`, `ℝ`) where it improves readability; all strings are plain ASCII for runtime compatibility
🟦 ACADEMIC REFERENCES
Every kernel and every formula in KernelLens is cited inline in the source. The combined bibliography:
- **Nadaraya, E. A. (1964).** On estimating regression. *Theory of Probability & Its Applications*, 9(1), 141–142.
- **Watson, G. S. (1964).** Smooth regression analysis. *Sankhyā: The Indian Journal of Statistics, Series A*, 26(4), 359–372.
- **Cleveland, W. S. (1979).** Robust locally weighted regression and smoothing scatterplots. *Journal of the American Statistical Association*, 74(368), 829–836. *(Tricube kernel, LOWESS.)*
- **Silverman, B. W. (1986).** *Density Estimation for Statistics and Data Analysis*. Chapman & Hall, London. *(Bandwidth rule of thumb.)*
- **Wand, M. P. & Jones, M. C. (1995).** *Kernel Smoothing*. Chapman & Hall. *(Unified treatment of all eight kernels.)*
- **MacKay, D. J. C. (1998).** Introduction to Gaussian Processes. *NIPS Tutorial*. *(Periodic and Rational Quadratic kernels.)*
- **Ehlers, J. F. (2000).** *Rocket Science for Traders*. John Wiley & Sons. *(Zero-lag smoothing trick.)*
- **Rasmussen, C. E. & Williams, C. K. I. (2006).** *Gaussian Processes for Machine Learning*. MIT Press. *(Locally Periodic and Rational Quadratic kernels.)*
🟦 VERSIONING & LICENSE
- **Version** — 1.0.0
- **Pine Script** — v6
- **License** — Mozilla Public License 2.0
- **Status** — Production-ready
KernelLens follows semantic versioning. Minor versions add new exports without breaking existing ones; patch versions fix bugs; major versions may change function signatures and will be announced in the changelog.
🟦 DISCLAIMER
KernelLens is a mathematical library for non-parametric regression on financial time series using the Nadaraya–Watson method. The library is provided solely for educational and research purposes and does not constitute financial, investment, or trading advice.
Kernel regression is a local smoothing technique. It estimates the mean of a source series in the neighborhood of the current bar based on historical data, but it does not predict future prices, does not generate trading signals on its own, and does not guarantee the profitability of any strategy built on top of its output.
Past performance of any model does not guarantee future results. Markets contain systemic risks that cannot be eliminated by any amount of mathematical rigor in the kernel itself. Responsibility for any trading decisions made using this library rests entirely with the user. Always apply sound capital management, conduct your own independent analysis, and never risk capital you are not prepared to lose.
The author assumes no liability for direct or indirect losses incurred through the use of KernelLens or any indicator built on top of it. Library

Indicator

Indicator

QuantEdge Momentum ML [PRO]🟦 QuantEdge Momentum ML PRO is a k-Nearest Neighbors driven momentum oscillator built on an adaptive machine-learning core. Unlike RSI, Stochastic, or MACD — which apply the same static formula to every asset — QE-ML PRO learns the dual-horizon RSI fingerprints that have historically led to bullish versus bearish outcomes on the exact instrument being traded, then scores the current bar against the N closest historical matches. The result is a non-parametric, self-calibrating oscillator whose decision boundary is shaped by the asset's own behaviour rather than a hard-coded curve.
The indicator integrates nine independent layers — feature engine, training sampler, k-NN predictor, WMA signal line, stdev-adjusted OB/OS bands, filtered signal dots, gradient channel, theme-adaptive dashboard, and a nine-theme palette — all rendered on a single, clean oscillator panel.
🟦 HOW THE CORE ENGINE WORKS
**Dual-Horizon RSI Feature Vector**
Each bar, the Feature Engine computes two RSI values at different lookback windows and smooths both through a shared trend-length WMA:
- `rsiFast = WMA(RSI(close, FastPeriod), TrendLength)` — reactive short-term momentum
- `rsiSlow = WMA(RSI(close, SlowPeriod), TrendLength)` — structural mid-term momentum
The pair `(rsiSlow, rsiFast)` is a 2-dimensional point in RSI feature space. Every training sample stores one such point along with a ±1 label that records whether price rose or fell since the previous sample. Over time the dataset accumulates a cloud of labelled points that maps which RSI states historically preceded up-moves versus down-moves on this exact asset.
**Training Sampler — Multi-Trigger Collector**
Three collection modes decide when to append a new labelled sample:
| Mode | Trigger | Use Case |
|---|---|---|
| **MA Crossover** | Fast WMA crosses Slow WMA | Clean, sparse samples — classic single-trigger behaviour |
| **Periodic** | Every N bars (user-set) | Fills dataset fast on new / low-history charts |
| **Hybrid** | MA crossover **OR** every N bars | Richest training set — recommended for fresh assets |
Sampling is gated by `barstate.isconfirmed` so the dataset never absorbs unconfirmed values from a flickering live bar.
**k-NN Predictor with Adaptive k**
On every bar, the predictor computes Euclidean distance in the 2D RSI feature space between the live `(rsiSlow, rsiFast)` point and every historical sample:
```
d = sqrt((rsiSlow_now - rsiSlow_hist)² + (rsiFast_now - rsiFast_hist)²)
```
The K closest historical points vote by summing their ±1 labels. The effective K is resolved adaptively using the classical statistical heuristic:
```
kEff = max(3, min(kMax, floor(sqrt(N))))
```
This means early bars — when only a handful of samples exist — use a small K, and the value stabilises as the dataset fills. On a fresh chart you never get a noisy prediction from an undersized neighborhood, and on a mature dataset K automatically scales up for smoother output.
**Bias Correction — Label-Mean Recentering**
Raw k-NN output is biased whenever the label distribution is skewed. On a trending asset, Periodic sampling fills the dataset with mostly +1 (or mostly −1) labels, pushing every prediction off zero. QE-ML PRO subtracts the expected value from the raw sum:
```
prediction = neighborLabelSum − (kEff × meanLabelAcrossDataset)
```
This keeps the mid-level visually centred at zero regardless of how trending the underlying asset has been. The correction is applied on every bar and is what makes the oscillator read cleanly on both sideways and strongly trending markets.
**Minimum Sample Gate**
Until the dataset has reached the user-defined Minimum Training Samples threshold, the predictor outputs exactly zero. This prevents unreliable readings during the warm-up phase on fresh charts.
**FIFO Rotation**
The dataset is hard-capped at Max Dataset Size. Once the cap is reached, the oldest sample is discarded on every new insertion — classical rolling window memory that keeps the k-NN scan bounded and the indicator fast on long histories.
🟦 PREDICTION LINE — FIVE VISUAL STYLES
All five styles are line-based. Only the visual effect differs — the underlying k-NN math is identical across styles.
| Style | Character |
|---|---|
| **Stratum** | Thick adaptive line with zone-based opacity: solid in extreme zones, semi-transparent in the mid zone. Layered intensity aesthetic — default |
| **Neon** | Bright core line with an outer glow halo. Cyberpunk luminous effect, best on dark backgrounds |
| **Resonance** | LRI-style gradient line that fades near the midline and brightens toward the rolling extremes |
| **Pulse** | Adaptive bull/bear color (above midline = bull, below = bear) plus the WMA signal line. The QE-ML PRO classic look |
| **Mono** | Single flat theme-bull line, no gradient, no adaptive coloring. Minimalist single-color silhouette |
🟦 SIGNAL LINE
A WMA of the raw prediction output, used as a crossover trigger line in the MACD convention. Crossovers between the prediction and signal line mark momentum regime changes.
**Two Visual Styles**
| Style | Rendering |
|---|---|
| **Neon** | Bright core line wrapped in a wider semi-transparent glow halo — cyberpunk aesthetic |
| **Flat** | Plain single-color line, no halo, no gradient — minimalist clean look |
🟦 SIGNAL DOTS — FILTERED CROSSOVER MARKERS
A two-layer neon cross-dot renderer fires on every Prediction × Signal crossover that survives the active filter mode. Four progressive filters decide which raw crosses reach the chart:
| Filter Mode | Behaviour | Signal Count |
|---|---|---|
| **All Crosses** | Every cross becomes a dot | Highest — noisy on choppy assets |
| **Zone Only** | Only crosses inside an OB or OS strip | Mean-reversion triggers — strongest reversal setups |
| **Mid Aligned** | Bull dots only above mid, bear dots only below | Trend-following — keeps you on regime side |
| **Strict** | Zone Only + Mid Aligned + extra strength multiplier on mid-zone crosses | Fewest signals, highest conviction — default |
Two additional gates filter out whipsaws:
- **Cooldown (bars)** — minimum spacing between consecutive dots, prevents cluster spam in ranges
- **Min Strength** — minimum `|prediction − signal|` separation at the moment of the cross, drops razor-thin crossovers that close back on themselves
Each dot is a two-layer plot: an outer glow halo with user-adjustable size and opacity, and a bright solid core on top — independently sized and opacity-controlled so users can dial in the exact visual weight they want.
The dot is placed at the actual cross point: bull dots at `min(prediction, signalLine)`, bear dots at `max(prediction, signalLine)`.
🟦 DYNAMIC BANDS — STDEV-ADJUSTED OB / OS ZONES
QE-ML PRO does not use fixed 80 / 20 overbought / oversold levels. Instead, the bands adapt to the actual historical range of the prediction output:
- **Channel Extremes** — rolling highest / lowest of the prediction over a user-configurable lookback
- **Stdev Band** — EMA of rolling standard deviation of the prediction, multiplied by the user's stdev length
- **OB Level** = `rangeHi − stdevBand` (inner boundary of the overbought strip)
- **OS Level** = `rangeLo + stdevBand` (inner boundary of the oversold strip)
The result is a pair of mean-reversion zones that tighten during quiet markets and widen during volatile ones — no manual recalibration needed across assets.
The strips are rendered as gradient fills anchored on the live prediction plot, so they only appear visually while the prediction is actually inside the zone.
🟦 CHANNEL GRADIENT
Two symmetric gradient fills bracket the mid line. The upper fill stretches from `midValue` to `rangeHi`, the lower fill from `midValue` to `rangeLo`. Opacity fades from full intensity at the extremes to fully transparent at the midline — a visual range meter showing how close the prediction is sitting to its historical boundaries.
Colors are pulled from the active Theme. A single opacity slider controls the gradient intensity.
🟦 DASHBOARD — LIVE DATA PANEL
A compact 2-column × 7-row monospace panel drawn on the last bar only (zero historical overhead). Every field updates in real time on the live bar.
| Row | Left | Right |
|---|---|---|
| Header | QE-ML PRO | Regime (▲ BULL / ▼ BEAR / ■ NEUTRAL) |
| Row 1 | Prediction | Raw value + trend arrow vs previous bar |
| Row 2 | Signal | WMA trigger line value |
| Row 3 | Strength | 10-block gauge of `|prediction − signal|` normalised against rolling channel |
| Row 4 | Zone | OB / MID / OS tag |
| Row 5 | Dataset | Sample count / effective k |
| Row 6 | Mode | Active Learning Mode (MA Cross / Periodic / Hybrid) |
**Theme-Aware Auto-Invert**
The panel background scaffolds auto-switch:
- **Tropic / Amber / Pastel / Cyber / Gold / Electric / Candy** → dark panel with bright theme accent text
- **Midnight / Graphite** → light panel with dark theme accent text
This guarantees legibility on every theme without breaking the theme's color identity — because Midnight and Graphite use deep dark bull tones that would drown against a black panel.
**Direction via Glyphs, Not Color**
Both columns share the same full-strength theme tone. Regime direction is conveyed by `▲ ▼ ■` glyphs rather than color shifts, which keeps the panel reading cleanly even on the most minimal themes.
🟦 NINE COLOR THEMES
One theme selector drives every colored component — Prediction line, Signal line, Channel fill, OB / OS strips, Mid-level line, Signal Dots, and Dashboard panel. No per-color manual inputs.
| Theme | Character | Bull | Bear |
|---|---|---|---|
| **Tropic** | Cyan steel + deep orange — electric contrast (default) | Cyan | Deep Orange |
| **Amber** | Warm amber + indigo blue — fire tones | Amber | Red |
| **Pastel** | Sky blue + soft lavender — cool arctic glow | Sky Blue | Lavender |
| **Cyber** | Neon lime + hot crimson — cyber terminal | Neon Green | Crimson |
| **Gold** | Bright gold + scarlet — solar warmth | Yellow Gold | Red |
| **Electric** | Electric aqua + magenta — high-voltage neon | Aqua | Magenta |
| **Candy** | Neon green + hot pink — dark energy pop | Mint Green | Hot Pink |
| **Midnight** | Deep navy + dark crimson — dark depth (auto light dashboard) | Navy Blue | Dark Red |
| **Graphite** | Near-black + silver grey — monochrome minimal (auto light dashboard) | Near Black | Grey |
🟦 ALERT SYSTEM — TEN CONDITIONS
Every alert is gated by its matching "Show X" visibility toggle — if a component is hidden from the chart, its alerts are automatically suppressed. This eliminates the mismatch between visual signals and alert signals that plagues many indicators.
| Alert | Condition | Gated By |
|---|---|---|
| Crossover OB | Prediction crosses above the overbought boundary | Show OB/OS Fill |
| Crossunder OB | Prediction crosses back down through OB | Show OB/OS Fill |
| Crossover OS | Prediction crosses up through oversold boundary | Show OB/OS Fill |
| Crossunder OS | Prediction crosses below the oversold boundary | Show OB/OS Fill |
| Crossover Mid | Prediction crosses above the mid line — bullish regime flip | Show Mid Level |
| Crossunder Mid | Prediction crosses below the mid line — bearish regime flip | Show Mid Level |
| Crossover Signal | Prediction crosses above its WMA signal line (MACD bullish) | Show Signal Line |
| Crossunder Signal | Prediction crosses below its WMA signal line (MACD bearish) | Show Signal Line |
| Bull Signal Dot | A filtered Bull Signal Dot is plotted (uses Filter Mode + Cooldown + Min Strength) | Show Signal Dots |
| Bear Signal Dot | A filtered Bear Signal Dot is plotted (uses Filter Mode + Cooldown + Min Strength) | Show Signal Dots |
🟦 SETTINGS REFERENCE
**Visual**
- Theme — nine cohesive palettes. Default: Tropic
**Machine Learning**
- Neighbors (k) — upper bound on neighbors used by the predictor. Default: 100
- Adaptive k — scales k with dataset size using the `floor(sqrt(N))` heuristic. Default: ON
- Learning Mode — MA Crossover / Periodic / Hybrid. Default: MA Crossover
- Sample Every (bars) — bar interval for the Periodic / Hybrid trigger. Default: 5
- Minimum Training Samples — warm-up gate, predictor outputs zero until reached. Default: 30
- Max Dataset Size — hard FIFO cap. Default: 500 (safe on all timeframes)
**Feature Engine**
- Trend Length — WMA smoothing applied to both RSI features. Default: 20
- RSI Fast Period — first feature dimension. Default: 5
- RSI Slow Period — second feature dimension. Default: 20
- MA Fast Period — fast WMA for the crossover training trigger. Default: 5
- MA Slow Period — slow WMA for the crossover training trigger. Default: 20
**Prediction Line**
- Show Prediction Line — master toggle. Default: ON
- Prediction Style — Stratum / Neon / Resonance / Pulse / Mono. Default: Stratum
- Prediction Width — 1 to 5. Default: 2
**Signal Line**
- Show Signal Line — toggle. Default: ON
- Signal Style — Neon / Flat. Default: Neon
- Signal Period — WMA length of the signal line. Default: 20
- Signal Width — 1 to 5. Default: 1
**Signal Dots**
- Show Signal Dots — toggle. Default: ON
- Filter Mode — All Crosses / Zone Only / Mid Aligned / Strict. Default: Strict
- Cooldown (bars) — minimum spacing between dots. Default: 5
- Min Strength — minimum `|prediction − signal|` at the cross. Default: 0.5
- Core Dot Size — 1 to 8. Default: 3
- Core Dot Opacity — 0 to 100. Default: 100
- Glow Dot Size — 1 to 12. Default: 8
- Glow Dot Opacity — 0 to 100. Default: 30
**Channel Fill**
- Show Channel Fill — toggle. Default: ON
- Channel Opacity — 0 to 100. Default: 25
- Channel Lookback — rolling highest / lowest window. Default: 500
**OB / OS Fill**
- Show OB/OS Fill — toggle. Default: ON
- Zone Stdev Length — stdev window that offsets the OB / OS boundaries inward. Default: 20
**Mid Level**
- Show Mid Level — toggle. Default: ON
- Mid Level Value — Y-value of the reference line. Default: 0
- Mid Level Style — Solid / Dashed / Dotted. Default: Dashed
**Dashboard**
- Show Dashboard — toggle. Default: ON
- Panel Position — six slots (Top/Middle/Bottom × Right/Left). Default: Middle Right
- Panel Text Size — Tiny / Small / Normal / Large. Default: Small
**Alerts**
- Ten opt-in toggles, one per alert condition. All default: ON
🟦 TRADER PRESETS — SETTINGS BY STYLE
QE-ML PRO is volatility-agnostic thanks to the adaptive bands and bias correction, but the reactivity of the predictor scales directly with the feature and sampler parameters. The four presets below are tested starting points you can drop straight into the settings panel — adjust by ±20% to taste.
---
** SCALPER — 1m / 3m / 5m**
High-frequency entries, tight stops, many signals per session. Priority is reaction speed — you want the predictor to flip states within a handful of bars of an actual move.
| Setting | Value |
|---|---|
| Trend Length | 10 |
| RSI Fast Period | 3 |
| RSI Slow Period | 14 |
| MA Fast Period | 3 |
| MA Slow Period | 10 |
| Signal Period | 8 |
| Neighbors (k) | 40 |
| Adaptive k | ON |
| Learning Mode | **Hybrid** |
| Sample Every | 2 |
| Minimum Training Samples | 20 |
| Max Dataset Size | **300** (keeps 1m charts fast) |
| Filter Mode | **All Crosses** or Zone Only |
| Cooldown | 2 |
| Min Strength | 0.3 |
| Channel Lookback | 200 |
| Zone Stdev Length | 10 |
| Prediction Style | Neon or Stratum |
**Why:** Low smoothing (Trend=10) + short RSI pair (3/14) keeps the features razor-sharp. Hybrid learning means you never wait for an MA crossover during quiet 1m sessions. Max Dataset capped at 300 protects you from the PulseWire per-bar calculation limit on long 1m histories.
---
** DAY TRADER — 15m / 30m / 1H**
Balanced reactivity and conviction — the default profile. You want clean crosses without noise spam, and signals that survive the open / close volatility spikes.
| Setting | Value |
|---|---|
| Trend Length | 20 (default) |
| RSI Fast Period | 5 (default) |
| RSI Slow Period | 20 (default) |
| MA Fast Period | 5 (default) |
| MA Slow Period | 20 (default) |
| Signal Period | 20 (default) |
| Neighbors (k) | 100 (default) |
| Adaptive k | ON |
| Learning Mode | **MA Crossover** (default) |
| Minimum Training Samples | 30 (default) |
| Max Dataset Size | 500 (default) |
| Filter Mode | **Strict** (default) |
| Cooldown | 5 (default) |
| Min Strength | 0.5 (default) |
| Channel Lookback | 500 (default) |
| Zone Stdev Length | 20 (default) |
| Prediction Style | Stratum (default) |
**Why:** Every default value was tuned for this range. Strict filter + 5-bar cooldown keeps the dot count honest on a 30m chart. MA Crossover sampling gives you clean sparse data since 15m+ charts already have enough crossover events.
---
** SWING TRADER — 4H / 1D**
Lower signal frequency, higher conviction per signal. You're holding for days or weeks — every dot needs to mean something.
| Setting | Value |
|---|---|
| Trend Length | 30 |
| RSI Fast Period | 7 |
| RSI Slow Period | 30 |
| MA Fast Period | 7 |
| MA Slow Period | 30 |
| Signal Period | 30 |
| Neighbors (k) | 150 |
| Adaptive k | ON |
| Learning Mode | MA Crossover |
| Minimum Training Samples | 50 |
| Max Dataset Size | 800 |
| Filter Mode | **Strict** |
| Cooldown | 10 |
| Min Strength | 0.8 |
| Channel Lookback | 800 |
| Zone Stdev Length | 30 |
| Prediction Style | Stratum or Mono |
**Why:** Longer feature periods mean the predictor only moves on genuine structural shifts. Larger k (150) + bigger dataset (800) gives the k-NN vote a wider base so outliers don't flip the sign. Cooldown of 10 bars on a 4H chart = 40 hours minimum between dots — exactly what a swing trader wants.
---
** POSITION / LONG-TERM — 1D / 1W / 1M**
Macro regime detection. You're looking for the handful of generational setups per year — noise is the enemy.
| Setting | Value |
|---|---|
| Trend Length | 50 |
| RSI Fast Period | 10 |
| RSI Slow Period | 40 |
| MA Fast Period | 10 |
| MA Slow Period | 40 |
| Signal Period | 40 |
| Neighbors (k) | 200 |
| Adaptive k | ON |
| Learning Mode | **Hybrid** |
| Sample Every | 3 |
| Minimum Training Samples | 40 |
| Max Dataset Size | 1000 |
| Filter Mode | **Strict** |
| Cooldown | 15 |
| Min Strength | 1.0 |
| Channel Lookback | 1000 |
| Zone Stdev Length | 40 |
| Prediction Style | Mono or Pulse |
**Why:** Weekly and monthly charts have few crossover events per year — without Hybrid mode the dataset starves. Sample Every = 3 on a weekly chart means one sample every 3 weeks, which is plenty of structural density. Min Strength 1.0 filters out every shallow cross — you only see dots on generational momentum inflections.
---
**Tuning Tip**
If the predictor feels **too reactive** → increase Trend Length and Signal Period by 25%, raise Cooldown.
If the predictor feels **too sluggish** → switch Learning Mode to Hybrid, decrease Min Samples, lower Trend Length.
If the dashboard shows **Dataset N is stuck low** → switch Learning Mode from MA Crossover to Hybrid — crossover events are too rare on your current settings.
If you see **runtime / timeout errors** on long histories → drop Max Dataset Size to 300 and Channel Lookback to 300.
🟦 COMPATIBILITY
Works on all asset classes and all timeframes in PulseWire Pine Script v6.
- **Crypto** — Spot, futures, perpetual contracts
- **Forex** — All pairs
- **Equities** — Stocks, ETFs, indices
- **Commodities** — Metals, energy, agriculture
- **Timeframes** — 1m through Monthly
The k-NN engine learns each asset's own RSI fingerprint distribution, and the stdev-adjusted bands auto-scale to the volatility of that distribution, so the indicator is truly self-calibrating across assets and timeframes — no manual recalibration required.
🟦 TECHNICAL NOTES
- Pine Script v6
- No repainting — training samples are gated by `barstate.isconfirmed` so the dataset never absorbs unconfirmed live-bar values
- Dataset is hard-capped via FIFO rotation; no unbounded memory growth
- Dashboard renders only on `barstate.islast` — zero historical overhead
- All drawing objects are stateless plots (no label / box / line object pools), so `max_*_count` limits cannot be exceeded
- k-NN distance pass is O(N), sort is O(N log N), both bounded by Max Dataset Size
- Default Max Dataset Size of 500 is tuned to stay within PulseWire's per-bar calculation budget on histories up to ~50,000 bars
- Bias correction uses a single extra accumulator pass during the distance sweep — no performance penalty
🟦 DISCLAIMER
This indicator is provided for educational and informational purposes only. It does not constitute financial advice. Past performance does not guarantee future results. The k-NN engine learns from historical patterns, but markets do not guarantee that historical patterns will repeat. Always conduct your own analysis and apply proper risk management. Indicator

Liquidity Zone Harvester [JOAT]Liquidity Zone Harvester
Introduction
Institutional order flow leaves footprints in market structure. When a large buyer or seller places a significant order, the execution of that order creates an imbalance between supply and demand at a specific price level — and markets frequently return to these levels to test whether the original interest remains. These price areas are commonly referred to as order blocks or liquidity zones, and they form one of the core concepts in institutional and Smart Money trading methodology.
The Liquidity Zone Harvester is an automated order block detection and management system that identifies these zones using statistically validated momentum signals rather than arbitrary manual placement. Instead of drawing boxes wherever a trader's eye thinks supply or demand may exist, this indicator uses Z-score cumulative impulse detection to identify when directional momentum has reached statistically significant levels — and only then marks the most recent opposing-close candle as the source order block. Volume quality gates ensure that only high-participation impulses create zones, filtering out low-conviction moves that are less likely to represent genuine institutional activity.
What sets this indicator apart from standard order block tools is what happens after zone creation. Every active zone is tracked through a dual-mechanism aging system. The Bayesian exponential decay model progressively reduces zone visual intensity over time with a configurable half-life, providing a continuous probability signal about zone freshness. Simultaneously, a Kaplan-Meier survival analysis engine — borrowed from medical statistics — estimates the probability that a given zone will survive future price tests, based on the historical survival rates of all previously observed zones in the training window. Each zone displays both its current age and its estimated survival probability directly on the chart, turning static boxes into dynamically updated probability estimates.
Core Concepts
1. Z-Score Cumulative Impulse Detection
Zone creation is triggered only when directional momentum reaches a statistically defined threshold. The system accumulates a running streak of directional closes — when consecutive bars close higher than their open, the bull accumulator grows; when consecutive bars close lower, the bear accumulator grows. The streak resets when direction reverses. This cumulative streak is then normalized against its own rolling mean and standard deviation, producing a Z-score that measures how unusual the current momentum streak is relative to recent history.
cumBull := close > open ? nz(cumBull ) + (close - open) : 0
cumBear := close < open ? nz(cumBear ) + (open - close) : 0
zBull = (cumBull - ta.sma(cumBull, zLen)) / ta.stdev(cumBull, zLen)
zBear = (cumBear - ta.sma(cumBear, zLen)) / ta.stdev(cumBear, zLen)
bullEvent = ta.crossover(zBull, zThresh) and barstate.isconfirmed and volOK
bearEvent = ta.crossover(zBear, zThresh) and barstate.isconfirmed and volOK
When a bullEvent fires (bull Z-score crosses the threshold with volume confirmation), the system looks backward to find the most recent down-close candle — the last bar where sellers were dominant before the impulse began. This becomes the demand zone. Similarly, a bearEvent marks the most recent up-close candle as the supply zone.
2. Volume Quality Gate
Not all Z-score impulses are created equal. An impulse that occurs on abnormally low volume represents weak conviction — possibly a thin-market price drift rather than genuine institutional momentum. The volume gate applies RSI to the volume series to normalize it against its own history. Only when volume RSI exceeds the configurable threshold is the volOK condition true, enabling zone creation.
volRsi = ta.rsi(volume, 14)
volOK = volRsi > volThresh
This filter meaningfully reduces the number of zones created during low-participation conditions such as pre-market sessions, lunch hours, or holiday-period trading — precisely the times when order block levels are least likely to represent significant institutional interest.
3. Order Block Zone Construction
When a signal event is confirmed, the most recent opposing candle is identified using ta.valuewhen(). For a bullEvent, the system finds the most recent bar where close was less than open (a down candle) — its high and low define the demand zone boundaries. For a bearEvent, it finds the most recent up candle — its high and low define the supply zone boundaries. A box object is created spanning from that historical bar to the current bar, with height defined by the candle's actual high-low range.
lastDnHigh = ta.valuewhen(close < open, high, 0)
lastDnLow = ta.valuewhen(close < open, low, 0)
lastDnBar = ta.valuewhen(close < open, bar_index, 0)
if bullEvent
newBox = box.new(lastDnBar, lastDnHigh, bar_index, lastDnLow, ...)
bullBoxes.push(newBox)
4. Overlap Prevention (f_no_overlap)
To avoid cluttering the chart with redundant zones that occupy the same price territory, an overlap check function evaluates whether a proposed new zone overlaps with any existing zone of the same type. The function iterates over all existing bull or bear boxes and compares the new zone's top and bottom against each existing box's top and bottom. A guard condition (nBull > 0) prevents the iteration from running on an empty array, which would cause an index -1 crash.
f_no_overlap(newTop, newBot, boxes) =>
noOverlap = true
if boxes.size() > 0
for i = 0 to boxes.size() - 1
b = boxes.get(i)
if newTop >= box.get_bottom(b) and newBot <= box.get_top(b)
noOverlap := false
noOverlap
5. Bayesian Exponential Decay
Each zone's visual transparency is driven by an exponential decay function that represents the diminishing probability of zone relevance over time. The half-life parameter (default: 75 bars) defines how quickly a zone fades. At age 0, the zone is fully opaque. At age 75 bars, the zone is at 50% opacity. At age 150 bars, 25% opacity. This continuous decay — rather than a binary active/expired switch — provides an analog probability signal directly encoded in the zone's visual intensity.
decayFactor = math.exp(-0.693 * age / halfLife)
zoneAlpha = math.round(decayFactor * 200)
box.set_bgcolor(b, color.new(zoneColor, 255 - zoneAlpha))
6. Kaplan-Meier Survival Analysis
The Kaplan-Meier estimator is a nonparametric statistical method originally developed to measure survival probabilities in clinical trial data. In this indicator, "survival" is defined as a liquidity zone remaining unmitigated (not breached by a closing price on two separate occasions). Each time a zone is mitigated, it is recorded as a "death event" at its current age. Zones that expire by age limit without mitigation are recorded as "censored events" — incomplete observations. The KM formula multiplies survival probabilities across all observed events up to a given age.
// For each completed event (death at age t_i with n_i at-risk zones):
S_t := S_t * (1.0 - d_i / n_i)
// Product over all event times <= query age
For each active zone, the indicator queries the KM estimate at the zone's current age and displays the result as a percentage label. A zone at age 40 showing "Age 40 | 72%" means that historically, 72% of zones survived to at least 40 bars without being mitigated — giving traders a quantitative assessment of how likely the zone is to hold on the next test.
Features
Z-Score Cumulative Impulse: Statistical momentum threshold using normalized cumulative directional streaks to gate zone creation.
Volume Quality Gate: Volume RSI filter ensures only high-participation impulses create zones.
Precise Order Block Identification: Most recent opposing candle (last down-close for bull event, last up-close for bear event) defines zone boundaries.
Overlap Prevention: f_no_overlap function checks all existing zones before creating a new one, preventing chart clutter from redundant levels.
Bayesian Exponential Decay: Zone opacity decays over time with configurable half-life, encoding freshness as a visual probability signal.
Kaplan-Meier Survival Analysis: Medical-statistics survival estimator applied to zone longevity, displayed as a percentage probability label on each active zone.
Dynamic Zone Extension: Box right edge extends to the current bar on every update, keeping zones visually connected to the present.
Mitigation Tracking: Zones that are closed through twice are flagged as mitigated and removed, with the event recorded for KM analysis.
Seven-Row Dashboard: Active demand count, active supply count, bull Z, bear Z, volume RSI, KM training size, and signal status.
Two Alert Conditions: Zone created alert and zone rejection (price tests and bounces back) alert.
Input Parameters
Z-Score Settings:
Z Lookback: Rolling window for Z-score normalization (default: 50)
Z Threshold: Sigma level required to trigger an impulse event (default: 2.0)
Volume Gate Settings:
Volume RSI Period: RSI lookback for volume normalization (default: 14)
Volume RSI Threshold: Minimum volume RSI for zone creation eligibility (default: 55)
Zone Management Settings:
Max Zone Age: Maximum bars a zone remains active before forced removal (default: 300)
Mitigation Count: Number of closes through a zone required for mitigation (default: 2)
Max Active Zones Per Side: Maximum simultaneous demand or supply zones displayed (default: 5)
Decay Settings:
Decay Half-Life: Number of bars at which zone opacity reaches 50% of initial value (default: 75)
KM Settings:
KM Training Window: Bar lookback for Kaplan-Meier training data collection (default: 500)
Show Survival Labels: Toggle KM probability labels on active zones (default: true)
Display Settings:
Show Demand Zones: Toggle demand (bull) zone boxes (default: true)
Show Supply Zones: Toggle supply (bear) zone boxes (default: true)
Show Dashboard: Toggle the seven-row information table (default: true)
How to Use This Indicator
Step 1: Understand Zone Creation Conditions
Zones are not created on every bar — they are created only when a statistically significant directional impulse (Z-score above threshold) occurs on above-average volume. This selectivity is intentional. In any given trading session, you will likely see only a few zone creation events, each backed by a genuine momentum surge that suggests institutional participation. When you see a new zone appear, note the Z-score values in the dashboard and the volume RSI reading — higher values on both indicate a stronger impulse and more confident zone placement.
Step 2: Prioritize Fresh, High-Survival Zones
Not all zones on the chart are equally relevant. A fresh zone (low age, full opacity) at a KM survival rate of 80% is a far stronger candidate for price reaction than an old zone (high age, near-transparent) at 30% survival probability. Use both the visual opacity and the KM label together: as a zone ages and fades, reduce your expectation that it will provide meaningful support or resistance. When price approaches a zone that is both visually fresh and shows high KM survival probability, the statistical expectation of reaction is at its highest.
Step 3: Watch for Zone Rejection Alerts
The zone rejection alert fires when price tests a zone (enters the box boundary) and then closes back away from it without mitigating it. This is the core trade setup: price returning to the institutional order block level, briefly penetrating it, and then reversing. The rejection alert provides a timely notification for potential entries in the direction of the original impulse that created the zone, with the zone's near boundary serving as the natural stop-loss reference.
Step 4: Monitor KM Training Size for Statistical Validity
The dashboard displays the KM training sample size — the number of completed zone events (both mitigated and aged-out) available for the survival analysis. With fewer than 10 training events, the KM estimate has high variance and should be treated as rough guidance. With 30 or more training events, the estimate becomes statistically stable. On instruments or timeframes where the indicator has run for extended periods, the KM estimates become increasingly reliable as the training dataset grows.
Indicator Limitations
The Z-score cumulative impulse and volume gate require sufficient chart history for the rolling normalization periods to be seeded. In the first Z-lookback bars of a new chart, zone creation signals may be less reliable as the mean and standard deviation are not yet fully established.
Kaplan-Meier survival estimates are only as reliable as the training dataset. On instruments or timeframes that have not accumulated many completed zone events, the survival probabilities should be treated as rough estimates rather than statistically precise values.
The mitigation definition (two closes through the zone) is a configurable approximation. In real order block theory, mitigation can be defined in several ways; this indicator's specific definition may not match every trader's conceptual framework.
Zones are based on the most recent opposing candle at the time of the impulse event. In fast markets where multiple large candles cluster closely together, the marked candle may not represent the most significant institutional order location.
This indicator requires volume data. On instruments where volume is unavailable or unreliable (some synthetic indices, certain forex pairs), the volume gate will not function as intended and should be disabled or its threshold lowered significantly.
The exponential decay model assumes a constant half-life across all market conditions. In reality, zone relevance can be regime-dependent — a zone formed during a trending market may remain relevant longer than one formed during a range, or vice versa.
Maximum active zones per side is a hard limit. If the limit is reached, new valid zone creation events will be rejected until an existing zone is mitigated or aged out.
Originality Statement
The Liquidity Zone Harvester is a genuinely original indicator that applies statistical and mathematical frameworks from outside the trading domain to a problem common in technical analysis.
The Z-score cumulative impulse detection — using consecutive close-open accumulation normalized against rolling sma/stdev — as the primary trigger for order block marking is an original signal architecture. Most order block indicators use visual pattern matching (e.g., a large candle followed by a gap) rather than statistical significance thresholds.
Applying the Kaplan-Meier survival estimator — a nonparametric method from biostatistics — to estimate the probability that a liquidity zone will survive future price tests is a novel application of medical statistics to market analysis. This provides a mathematically grounded probability estimate that no standard order block indicator offers.
The Bayesian exponential decay applied to zone visual transparency — using a configurable half-life to continuously encode zone freshness as opacity — is an original visual design that treats zone relevance as a continuously diminishing probability rather than a binary active/inactive state.
The overlap prevention function that iterates over all existing zone arrays before creating a new zone — with the index-crash guard for empty arrays — is a specific engineering solution to a concrete problem in box-based indicator design.
The volume RSI quality gate, applied specifically to filter Z-score impulse events rather than as a standalone signal, is an original confluence filter design that specifically addresses the problem of thin-market false signals in order block detection.
Disclaimer
The Liquidity Zone Harvester is provided for educational and informational purposes only. It is a technical analysis tool and does not constitute financial advice. Liquidity zones and order blocks are analytical constructs; they do not guarantee price reactions. Past zone behavior as encoded in Kaplan-Meier estimates does not predict future zone performance. All trading involves risk of loss. Users are solely responsible for their own trading decisions. Please consider your individual risk tolerance and consult a licensed financial professional before engaging in any trading activity.
-Made with passion by officialjackofalltrades
Indicator

Self-Aware Trend System [WillyAlgoTrader]🧠 Self-Aware Trend System (SATS) is an adaptive SuperTrend-based trend-following system that continuously measures its own operating environment through a 4-factor Trend Quality Index (TQI) and modulates band width, asymmetry, and flip logic in real time. Unlike a fixed SuperTrend — which uses the same ATR multiplier forever — SATS knows when the market is trending vs. chopping, compresses bands in clean trends to lock profit tighter, widens them in noisy conditions to avoid whipsaws, and can detect regime collapse through a "character-flip" even when price hasn't broken the band yet. Each confirmed signal comes with a full trade plan (Entry, SL, TP1/TP2/TP3 at user-defined R multiples), and the system tracks its own realized R, win rate, drawdown, and per-regime edge — building an honest, instrument-specific performance log directly on your chart.
The name "Self-Aware" refers to one specific property: the indicator measures the quality of its own environment every bar and feeds that measurement back into its band width and flip conditions. It doesn't predict the future — it reacts to present conditions with mathematically defined adaptation rules.
🧩 WHY THESE COMPONENTS WORK TOGETHER
A classic SuperTrend has one problem: its ATR multiplier is fixed. In a clean trending market the bands are too wide, giving back profit on every pullback. In a choppy market the bands are too tight, generating whipsaw after whipsaw. Traders try to fix this by manually switching multipliers per timeframe or per instrument — but that's guesswork.
SATS chains a different approach:
Market state measurement (TQI) → Non-linear band modulation → Asymmetric band widths → Character-flip detection → R-multiple trade plan → Outcome tracking → Regime-aware statistics
The TQI engine measures market quality from four independent angles each bar (efficiency, volatility regime, structure, momentum persistence). The non-linear modulation translates that quality into band width — high quality compresses bands, low quality expands them, using a power curve that avoids both over-reacting to mild fluctuations and under-reacting to severe regime changes. Asymmetric bands tighten the active side (in the direction of the trend) while loosening the passive side — creating a "ratchet with leverage" that locks in profit faster than it invalidates the trend. Character-flip detection catches regime collapses (high quality → low quality) even when price hasn't broken the band — critical for exiting stale trends before they fully reverse. And performance tracking records every signal's realized R, building a real statistical picture of how the system performs on your specific instrument and timeframe.
Without TQI, the bands are blind. Without asymmetry, profit-taking lags. Without character-flip, exits happen too late. Without performance tracking, you have no idea if the system has a real edge on your instrument. All four work together — each layer addresses a specific weakness of classic SuperTrend.
🔍 WHAT MAKES IT ORIGINAL
1️⃣ Trend Quality Index (TQI) — 4-factor continuous quality measurement.
TQI is computed every bar as a weighted combination of four independent 0..1 factors:
— 🧭 Efficiency (default weight 0.35) : Kaufman Efficiency Ratio = |close − close | / sum(|close − close |). Measures directional movement vs. total path. 1.0 = perfect straight line, 0.0 = pure noise. Default window 20 bars.
— 📊 Volatility Regime (weight 0.20) : uses Volume Z-score when volume data is available (z = (volume − sma) / stdev, mapped from to ), or falls back to ATR ratio (current ATR vs. long-baseline ATR) on volume-less instruments.
— 🏗️ Structure (weight 0.25) : price position within its recent range. pricePos = (close − lowest) / (highest − lowest). Then tqiStruct = |pricePos − 0.5| × 2. Trends pin price to one edge (1.0), chop oscillates around the midpoint (0.0). No ATR dependency.
— ⏩ Momentum Persistence (weight 0.20) : of the last N bars, what fraction moved in the same direction as the overall window change? alignedBars / N. Default 10 bars.
Final TQI = (factor1 × w1 + factor2 × w2 + factor3 × w3 + factor4 × w4) / sum(weights), clamped to 0..1. Each weight is user-configurable.
2️⃣ Non-linear band modulation with power curve.
Instead of a linear "multiplier × (1 − tqi)", SATS uses a power curve:
qualityDeviation = (1 − tqi)^curvePower
tqiMult = 1 − qStrength + qStrength × (0.6 + 0.8 × qualityDeviation)
With curvePower = 1.5 (default), mild quality drops (from 0.9 to 0.7) cause small band expansion, but severe drops (0.5 to 0.2) cause rapid expansion. This matches how traders actually think: ignore small wobbles, react strongly to clear regime changes.
3️⃣ Asymmetric band widths — ratchet with leverage.
In a strong uptrend, the lower band (active, trailing price up) tightens while the upper band (passive, not used as stop) widens:
activeMult = symMult × (1 − asymStrength × tqi × 0.3)
passiveMult = symMult × (1 + asymStrength × tqi × 0.4)
Effect: as trend quality rises, the trailing stop moves closer to price (locking profit faster) while the opposite band moves away (so an accidental pullback doesn't trigger a flip). This is the "leverage" — asymmetric response to confirmed trend strength.
4️⃣ EMA-smoothed multipliers before ratchet application.
Raw TQI can spike bar-to-bar. If those spikes fed directly into the SuperTrend ratchet logic, bands would compress at a high-TQI bar and stay stuck there (SuperTrend math never loosens active bands against the trend). SATS EMA-smooths the multipliers (alpha 0.15) before ratchet application — preventing stickiness. This is the critical fix that makes adaptive SuperTrend actually work in practice.
5️⃣ Efficiency-weighted ATR.
Used for band construction and SL/TP sizing (not for TQI itself, to avoid circular feedback):
effATR = rawATR × (0.5 + 0.5 × ER)
Clean trending volatility counts full (ER = 1.0 → effATR = rawATR). Noisy chop volatility is halved (ER = 0.0 → effATR = 0.5 × rawATR). This makes SL/TP distances proportional to "useful" volatility, not total volatility.
6️⃣ Character-flip detection with age guard.
Classic SuperTrend only flips on price breaks. But a trend can die internally — quality collapses, momentum fades — before price actually breaches the band. Character-flip catches this:
charFlipDown = prevTQI > 0.55 (high) AND currentTQI < 0.25 (low) AND trendAge ≥ minAge AND close < source
The age guard (default 5 bars) prevents whipsaw on fresh trends — a newborn trend hasn't had time to establish quality, so early TQI noise can't kill it. After the age threshold, a quality collapse triggers an immediate flip even without price break.
7️⃣ Auto-fixed TP order.
If a user accidentally sets TP1 > TP2 (or TP3 < TP2), the indicator automatically sorts them. Math: fixedMin = min(all), fixedMax = max(all), middle = sum − min − max. The three TP lines always end up in correct order on the chart regardless of user input order.
8️⃣ R-multiple trade planning with pivot-anchored SL.
On each signal:
— Entry = close at bar of confirmed flip
— SL = min(pivot − slMult×ATR, entry − slMult×ATR) for longs (mirror for shorts)
— TP1/2/3 = entry ± risk × R-multiple
The SL uses whichever is further from entry — the recent pivot (if available) or a pure ATR distance. This ensures the stop always has a minimum ATR buffer regardless of how close the nearest pivot is.
9️⃣ Performance tracking with realized R accounting.
Every signal is tracked bar-by-bar for TP hits, SL hits, and timeout (default 100 bars). On close-out, realized R is calculated assuming 1/3 position per TP:
— TP3 hit: realized = (tp1R + tp2R + tp3R) / 3 (all three filled)
— SL hit after TP1: realized = (1/3) × tp1R + (2/3) × (−1R)
— SL hit after TP1+TP2: realized = (1/3) × tp1R + (1/3) × tp2R + (1/3) × (−1R)
— Pure SL: realized = −1R
— Timeout: realized = sum of already-hit TP portions (no penalty)
Results feed a rolling buffer (up to 100 signals), which drives:
— Rolling Win Rate
— Rolling Avg R
— Rolling drawdown (window DD)
— All-time drawdown
— Current and max win/loss streaks
🔟 9-cell regime edge tracking.
Every completed signal is bucketed by the market regime at entry time: Efficiency bin (low/mid/high) × Volatility bin (low/normal/high) = 3×3 = 9 cells. Each cell accumulates its own EWMA of realized R. The dashboard shows the current regime's historical edge — e.g., "Trending + High Vol: +0.85R (23 trades)". This lets you see which market conditions the system actually profits in.
1️⃣1️⃣ Experimental self-calibration (off by default).
When enabled, the system monitors its rolling avg R and drifts the Quality Influence parameter toward the user default if recent edge is poor (below threshold). This is explicitly marked experimental — no claim of improved results — and recommended off until validated on your instrument.
⚙️ HOW IT WORKS — CALCULATION FLOW
Step 1 — TQI computation : Compute four factors (Efficiency, Volatility Regime, Structure, Momentum Persistence). Weight and combine into a single 0..1 value.
Step 2 — ATR and effective ATR : rawATR = ta.atr(len). effATR = rawATR × (0.5 + 0.5 × ER).
Step 3 — Adaptive multiplier : Apply legacy ER adaptation (optional) and non-linear TQI curve. If asymmetric bands enabled, split into active/passive multipliers.
Step 4 — EMA smoothing : Smooth both multipliers with alpha 0.15 to prevent ratchet stickiness.
Step 5 — SuperTrend bands : upperBand = source + upperMult × effATR. lowerBand = source − lowerMult × effATR. Ratchet logic: lower only rises, upper only falls, until a flip.
Step 6 — Flip detection : Price flip (close crosses opposite band) OR character-flip (TQI collapse + age guard). On flip: reset trend age, start new segment.
Step 7 — Trade plan : On confirmed flip, compute Entry/SL/TP1/TP2/TP3. Draw lines and labels. Cache the market regime (ER bin × Vol bin) for later edge attribution.
Step 8 — Outcome tracking : Each bar, check active trade for TP1/TP2/TP3/SL hits and timeout. On close-out, calculate realized R, push to history buffer, update rolling stats, drawdown, streaks, and regime cell.
Step 9 — Dashboard render : On last bar, render live state (Trend, TQI, regime, performance stats, TQI breakdown, regime edge).
📖 HOW TO USE
🎯 Quick start:
1. Add indicator — preset is "Auto" (adapts to your current timeframe)
2. Green line = bullish trend, red = bearish trend
3. Line transparency reflects TQI: bright = high quality, faded = low quality
4. ▲ BUY / ▼ SELL labels appear on confirmed flips
5. Entry, SL, TP1, TP2, TP3 lines drawn automatically at the signal
6. Copy levels to your exchange, let the dashboard track outcomes
👁️ Reading the chart:
— 🟢 Bright green line = bullish trend with high TQI — aggressive participation
— 🟢 Faded green line = bullish trend with low TQI — cautious, possible regime shift
— 🔴 Bright red line = bearish trend with high TQI
— 🔴 Faded red line = bearish trend with low TQI
— Line flip + label = new trade signal
— Dashed TP lines turning solid + "✓" = TP was hit
— Score on label (e.g., "85/102") = multi-factor confluence strength
📊 Dashboard fields:
— Preset: Auto-resolved (Scalping / Default / Swing / Crypto)
— Trend: Bullish ▲ / Bearish ▼
— TQI: current quality index (0..1)
— Q.Strength: effective Quality Influence (may drift if auto-calibration enabled)
— Signal: current bar signal (BUY / SELL / —)
— Regime: Trending / Mixed / Choppy + Low/Norm/High Vol
— ER / RSI / Vol Z: raw filter values
— TQI Components breakdown: Efficiency / Volatility / Structure / Momentum (each 0..1)
— Performance section: Win Rate, Avg R, Window DD, All-Time DD, Streak W/L, Regime Edge
🔧 Tuning guide:
— Too many whipsaws : increase Quality Influence (0.5–0.7), increase Structure weight, increase Base Band Width
— Missing moves / signals too late : decrease Quality Influence (0.2–0.3), decrease Base Band Width, increase asymmetry
— Choppy instrument : use Swing preset, enable Character-Flip, raise minAge to 10+
— Strong trending instrument : use Scalping preset, enable Asymmetric Bands with strength 0.6+
— No volume data : automatically falls back to ATR ratio for volatility regime — no action needed
⚙️ KEY SETTINGS REFERENCE
⚙️ Main:
— Preset : Auto / Custom / Scalping / Default / Swing / Crypto 24/7 (auto-adapts ATR, band width, ER window, RSI, SL multiplier)
— ATR Length (13), Base Band Width (2.0 × ATR)
📐 Trend Quality Engine:
— Enable TQI (default On)
— Quality Influence (0.4): how strongly TQI compresses/expands bands
— Quality Curve Power (1.5): non-linearity
— Smooth Adaptive Multipliers (On): critical fix for ratchet stickiness
— Asymmetric Bands (On) + Asymmetry Strength (0.5)
— Efficiency-Weighted ATR (On)
— Character-Flip (On) + Min Age (5) + High/Low TQI thresholds (0.55 / 0.25)
— TQI factor weights : ER 0.35, Volatility 0.20, Structure 0.25, Momentum 0.20
🎯 Risk:
— SL Buffer (1.5 × ATR), TP1/2/3 R-multiples (1.0 / 2.0 / 3.0), Trade Timeout (100 bars)
🤖 Self-Learning (experimental):
— Auto-calibration (default Off), calibration window, bad/good R thresholds, quality step, cooldown, floor/ceiling
— Reset Learning Memory button
📊 Dashboard: position, TQI breakdown toggle, performance stats toggle, score breakdown toggle
🔔 Alerts
— 🟢 BUY — ticker, TF, price, TQI, score, SL, TP1, TP2, TP3
— 🔴 SELL — same payload
Plain text and JSON webhook formats supported. Bar-close confirmed.
⚠️ IMPORTANT NOTES
— 🚫 No repainting. All signals require barstate.isconfirmed. SuperTrend ratchet logic is monotonic — once the trailing band moves, it cannot move back against the trend until a flip. Character-flip uses only previous-bar TQI and current-bar close, both available at bar close.
— 📊 TQI is descriptive, not predictive. It measures current market quality from 4 factors — it does not forecast future price. A high TQI reading means "the market is currently behaving like a trend" — it can still fail on the next bar.
— 📏 Performance stats are walk-forward, not backtested. The rolling buffer records signals as they happen, bar by bar. Drawdown, win rate, and regime edge are honest forward-looking statistics on your specific instrument and timeframe — not curve-fitted optimization results.
— ⚖️ The realized R accounting assumes 1/3 position per TP . This mirrors a standard "scale out at each target" approach. Traders who hold full position to a single target should interpret the R values accordingly.
— 🔄 Auto-calibration is experimental. It's off by default and should stay off until you've validated it on your specific instrument. The drift is mean-reverting (toward your user default), not profit-maximizing — no claim of improvement is made.
— 🔒 The Reset Learning Memory button clears the rolling buffer, regime cells, drawdown, and streak stats. Use when changing instruments or after significant market regime shifts.
— 🛠️ SATS is a decision-support and trade-planning tool , not an automated bot. It identifies trend conditions, measures environmental quality, provides structured trade plans with R-based targets, and tracks outcomes — trade decisions and execution remain yours.
— 🌐 Works on all markets and timeframes. Volume-dependent features (Volume Z in TQI) auto-fall-back to ATR-based measurement when volume data is unavailable. Indicator

Golden Pocket Syndicate Mini (GPSM)This indicator is an overlay toolkit that combines multi-timeframe Golden Pocket-style zones (Fibonacci-derived ranges between user-defined high/low ratios), optional GP-anchored VWAPs that reset when price interacts with the matching zone, and a confluence framework with optional visuals (signals, divergences, order-block-style markers, sweeps, trails). It is intended to help traders see where higher-timeframe ranges and optional filters overlap on the chart—not to automate trading or promise outcomes.
What it does
Pulls prior completed higher-timeframe highs/lows via request.security() and derives upper/lower pocket levels from your fib inputs.
Plots pocket bands (and fills where used) for the timeframes you enable.
Optionally plots volume-weighted averages anchored to touches of the corresponding pocket.
Combines user-toggled filters into a confluence score and optional bull/bear markers; all signal logic can be turned off in settings.
How to use
Open settings, enable only the pocket timeframes and visuals you need. Adjust fib inputs, touch tolerance, and filter groups to match your process. If you use alerts, treat them as notifications only—confirm every trade in your own plan.
Important limitations
This is not financial, investment, or tax advice. Markets involve risk; past or hypothetical chart behavior does not guarantee future results.
Higher-timeframe data and request.security() behavior depend on symbol, session, and chart timeframe. Validate outputs on your instruments before relying on them.
Scripts cannot execute orders; you are responsible for compliance, sizing, and risk.
Companion
For separate 1H / 4H / 8H pocket bands (to reduce plot limits when combined with heavy scripts), use the author’s “Golden Pocket Syndicate mini” (GPSM) publication if offered.
Golden Pocket Syndicate mini (GPSM) — public description
Use this in the publication description field (English first).
GPSM is a lightweight companion overlay focused on 1-hour, 4-hour, and 8-hour Golden Pocket-style zones: two fib ratios applied to the prior completed bar’s range on each timeframe, with optional filled bands and optional GP-anchored VWAPs (off by default) that reset when price touches the matching pocket. The 1-hour band can optionally switch color using a simple prior closed 1H close vs EMA rule so you can see a regime-style split at a glance.
What it does
Uses request.security() on "60", "240", and "480" minute timeframes with the same prior-bar anchoring idea as the author’s main GPS Pro script.
Keeps the script small so it can run alongside heavier indicators without hitting Pine’s plot limits as quickly.
How to use
Add it to your chart, toggle 1H/4H/8H zones and fills, then optionally enable individual VWAPs. Match fib settings to your main workflow if you use GPS Pro on the same chart.
Important limitations
Not financial advice. No performance or profitability claims. Past chart behavior does not predict future prices.
HTF behavior varies by symbol and session (especially 8H). Confirm levels on your market.
You are solely responsible for trading decisions and risk.
Relationship to GPS Pro
GPSM does not duplicate the full confluence, SMC filters, or alerts stack from GPS Pro; it is meant as a focused HTF pocket + optional VWAP add-on. Indicator

Pulse Trend Radar [WillyAlgoTrader]⦿ Pulse Trend Radar is an overlay indicator built on a Kaufman Adaptive Moving Average (KAMA) core with median-ATR volatility bands — producing an adaptive trend system that speeds up in trending markets and slows down in noise. Every trend flip generates a signal scored by a 4-factor quality engine (0–100) with letter grades (A+ through C). The indicator also detects and visualizes liquidity zones from pivot highs/lows, marks order blocks from the last opposite candle before each trend flip, tracks real-time P&L with a live trade tracker, and monitors win/loss outcomes — creating a complete trend-following framework with Smart Money context.
🧩 WHY THESE COMPONENTS WORK TOGETHER
A trend indicator alone tells you direction — but not whether the entry is near a liquidity pool (where stops cluster), not whether there's institutional supply/demand nearby (order blocks), not how strong the signal is (all flips treated equally), and not how the system performs over time (no feedback).
This indicator layers four analysis dimensions onto the adaptive trend core:
KAMA adaptive trend + median ATR bands → Trend direction and flip detection
Liquidity zones from pivots → Where stop-hunts and liquidity grabs are likely
Order blocks from pre-flip candles → Where institutional supply/demand was established
4-factor signal scoring → Quality filtering — not all flips are equal
Win/loss tracker → Performance feedback on this instrument and timeframe
The KAMA core adapts its speed via the Efficiency Ratio — in a strong trend, the MA tracks price closely and the bands tighten, producing early signals. In choppy conditions, the MA barely moves and the bands widen, filtering out noise. The liquidity zones show where clusters of stops sit (above pivot highs, below pivot lows) — entries near these zones have higher follow-through because the liquidity grab fuels the move. The order blocks mark the institutional footprint before each trend change — these zones often act as support/resistance on retests. And the signal score combines trend strength, volume delta, efficiency acceleration, and liquidity proximity into a single quality metric — letting you prioritize A+ setups over C-grade ones.
🔍 WHAT MAKES IT ORIGINAL
1️⃣ Kaufman Adaptive Moving Average (KAMA) trend core.
The KAMA computes a smoothing constant from the Efficiency Ratio:
ER = |price − price | / sum(|price − price |, N)
fastSc = 2 / (fastLen + 1), slowSc = 2 / (slowLen + 1)
sc = (ER × (fastSc − slowSc) + slowSc)²
KAMA = KAMA + sc × (price − KAMA )
When ER → 1 (pure trend): sc approaches fastSc² → KAMA tracks price tightly. When ER → 0 (pure noise): sc approaches slowSc² → KAMA barely moves. This produces a line that accelerates into trends and goes flat in chop — without any manual period switching.
2️⃣ Median ATR volatility bands.
Instead of standard ATR (arithmetic mean of true ranges), the indicator uses a median of recent true ranges computed via a ring buffer over the volatility lookback (default 50 bars). The median is more robust to outlier spikes (gap bars, flash wicks) than the mean — producing smoother, more stable band widths.
Bands: upper = KAMA + medianATR × multiplier, lower = KAMA − medianATR × multiplier. Trend flips when the previous bar's source price crosses beyond a band: source > upper → bullish, source < lower → bearish. The active band (lower in uptrend, upper in downtrend) is plotted as the trend line.
3️⃣ Displacement-based gradient fill.
The fill between the trend line and price is not a fixed transparency — it scales with displacement: displacement = |price − KAMA| / (medianATR × multiplier). The further price stretches from KAMA, the more intense the fill becomes (transparency decreases from 95 to 60). This creates a visual "heat map" effect: faint fill near KAMA (low extension), bright fill far from KAMA (overbought/oversold). This gives immediate visual feedback on how extended the current move is without needing a separate oscillator.
4️⃣ Liquidity zone detection and sweep tracking.
Pivot highs and lows (configurable lookback, default 4 bars) are marked as liquidity zones:
— Above pivot highs → bearish liquidity (buy stops cluster above swing highs — potential sell-side liquidity)
— Below pivot lows → bullish liquidity (sell stops cluster below swing lows — potential buy-side liquidity)
Each zone extends rightward as a thin box (height = 0.15× medianATR). Zones are automatically removed when price sweeps through them (high crosses above bearish zone top, or low crosses below bullish zone bottom) — representing the liquidity grab event. Up to 15 zones per side (configurable).
The signal scoring engine measures the nearest liquidity zone distance on each trend flip — entries closer to a liquidity pool receive a higher quality score because the stop-hunt provides fuel for the ensuing move.
5️⃣ Order block detection on trend flips.
When the trend flips, the previous bar is marked as an order block:
— Bullish flip → demand order block (the last bearish candle before the reversal — where institutional buying absorbed selling pressure)
— Bearish flip → supply order block (the last bullish candle before the drop — where institutions distributed)
Each OB is drawn as a box from the previous candle's high to low, extending rightward. OBs are automatically invalidated (deleted) when price closes beyond the opposite edge after 3+ bars — indicating the zone has been broken. Up to 10 OBs per side (configurable).
6️⃣ 4-factor signal quality scoring (0–100).
Each trend flip is scored on four factors:
— 📐 Trend strength (25 pts) : combined from ER (directional efficiency) and displacement from KAMA — measures how strong the trend is at the moment of the flip
— 📊 Volume delta alignment (25 pts) : buy volume vs sell volume accumulated during the previous trend leg — bullish flip with positive volume delta scores higher (smart money was accumulating)
— ⚡ Efficiency acceleration (25 pts) : current ER minus previous ER — positive acceleration means the trend is gaining momentum, not losing it
— 💧 Liquidity proximity (25 pts) : distance to the nearest liquidity zone — closer = higher score (the flip is near a liquidity grab point)
Grades: A+ (≥ 80), A (≥ 60), B (≥ 40), C (< 40). Signal labels display "Long A+" / "Short B" etc.
7️⃣ OBV-based volume regime detection.
On Balance Volume (OBV) delta = OBV − SMA(OBV, 20). Classified as:
— Accumulation : OBV delta > 0 — more volume on up-moves than down-moves (institutional buying)
— Distribution : OBV delta < 0 — more volume on down-moves (institutional selling)
Displayed in the dashboard with directional coloring. Auto-displays "N/A" on instruments without volume data.
8️⃣ Live trade tracker with P&L.
On each signal: a dashed entry line extends horizontally, a vertical connector line tracks from entry to current price, and a P&L label updates in real-time showing percentage gain/loss. Green = profit, red = loss. Replaced on each new signal.
9️⃣ Win/loss markers + win rate tracking.
Each signal is tracked as a mini-trade: entry at signal close, SL at entry ± medianATR × SL multiplier, TP1 at entry ± risk × TP1 multiplier. If TP1 is reached before SL → green ● marker at the signal bar (win). If SL is reached first → red ● marker (loss). Running win rate displayed in the dashboard as "67% (4W/2L)".
🔟 ATR-based TP/SL with hit tracking.
Three take-profit levels as risk multiples (default 1.0/2.0/3.0 × risk) plus SL (default 3× medianATR from entry). Lines extend rightward with labels showing price + percentage. Labels update with ✓ on hit (green) or ✗ on SL hit (red). Active until the next signal replaces them.
⚙️ HOW IT WORKS — CALCULATION FLOW
Step 1 — KAMA: Efficiency Ratio from configurable lookback → adaptive smoothing constant → KAMA line that accelerates in trends, goes flat in chop.
Step 2 — Median ATR bands: True ranges stored in ring buffer → median computed → upper/lower bands = KAMA ± median × multiplier.
Step 3 — Trend detection: Previous bar's source > upper band → bullish flip. Source < lower band → bearish flip. Active band plotted as trend line. Gradient fill scales with displacement.
Step 4 — Liquidity zones: Pivot highs/lows → boxes above/below. Swept zones auto-deleted.
Step 5 — Order blocks: On flip → previous candle becomes OB. Invalidated when price closes beyond opposite edge.
Step 6 — Signal scoring: 4 factors (trend strength, volume delta, ER acceleration, liquidity proximity) → 0–100 → A+/A/B/C grade.
Step 7 — Trade tracking: SL/TP placed, lines extend, win/loss evaluated per trade.
📖 HOW TO USE
🎯 Quick start:
1. Add the indicator — adaptive trend line, liquidity zones, and order blocks appear
2. "Long A+" / "Short B" labels = trend flip signals with quality grade
3. Green/red liquidity zone boxes = where stops cluster (potential sweep targets)
4. Green/red order blocks = institutional supply/demand zones
5. SL/TP lines auto-appear with P&L tracker
👁️ Reading the chart:
— 🟢 Green trend line = bullish (lower band active)
— 🔴 Red trend line = bearish (upper band active)
— 🟢/🔴 Gradient fill = displacement from KAMA (brighter = more extended)
— 🟢 Small boxes below price = bullish liquidity zones (buy-side stops)
— 🔴 Small boxes above price = bearish liquidity zones (sell-side stops)
— 🟢 Larger boxes = demand order blocks (institutional buying zone)
— 🔴 Larger boxes = supply order blocks (institutional selling zone)
— 🟢 ● = win (TP1 reached), 🔴 ● = loss (SL hit)
— Dashed line + PnL label = live trade tracker
📊 Dashboard fields:
— Trend: ▲ Bullish / ▼ Bearish
— Last Signal: BUY/SELL with grade
— Score: 0–100 quality rating
— Strength: trend strength percentage
— P&L: current trade percentage
— Win Rate: wins/losses with percentages
— SL / TP1: current trade levels with ✓/✗ status
— Vol Regime: Accumulation / Distribution
— Vol Delta: buy vs sell volume percentage
— Efficiency: current ER percentage
🔧 Tuning guide:
— Too many signals: increase Band Multiplier (2.0–2.5) or ER Length (15–20)
— Too few signals: decrease Band Multiplier (1.2–1.5) or ER Length (8–10)
— Signals too late: decrease Slow Smoothing (15–20), decrease Volatility Length (20–30)
— Stops too tight: increase SL ATR Multiplier (2.5–4.0)
— Want only A+/A signals: monitor grades in dashboard, skip B/C entries
⚙️ KEY SETTINGS REFERENCE
⚙️ Main:
— Efficiency Ratio Length (default 13): KAMA lookback — higher = smoother
— Fast/Slow Smoothing (default 2/30): KAMA acceleration/deceleration
— Band Multiplier (default 1.8): band width in median ATR
— Volatility Length (default 50): median ATR ring buffer size
🎯 SL/TP:
— SL (× ATR) (default 3): stop distance in median ATR
— TP1/TP2/TP3 (× risk) (default 1.0/2.0/3.0): R:R multiples
💧 Liquidity:
— Pivot Lookback (default 4) / Max Zones (default 15)
🟧 Order Blocks:
— Max Order Blocks (default 10)
🎨 Visual:
— Gradient fill, trade tracker, win/loss markers (all toggleable)
— Configurable signal label size (Tiny–Large)
— Configurable dashboard font size (Tiny–Normal)
— Auto / Dark / Light theme
🔔 Alerts
— 🟢 BUY / 🔴 SELL — ticker, price, TF, SL, TP1, TP3
All support plain text and JSON webhook format. Bar-close confirmed.
⚠️ IMPORTANT NOTES
— 🚫 No repainting. All signals require barstate.isconfirmed. Trend flips use the previous bar's source vs the previous bar's band value — the signal fires on the bar after the crossing bar closes. KAMA and band values are deterministic once a bar is confirmed.
— 📐 The median ATR is more robust than standard ATR . A single flash wick or gap bar shifts the mean (standard ATR) significantly but barely affects the median. This produces more stable band widths and fewer false flips during anomalous bars.
— 📊 Volume delta is accumulated within each trend leg and resets on every trend flip. It represents the buy/sell balance during the specific move — not the overall volume profile. The pre-reset delta value is used for the signal score (capturing the exiting leg's character).
— 💧 Liquidity zones are automatically swept and removed when price touches them. This prevents stale zones from cluttering the chart. If a zone disappears, it means price swept through it — the liquidity has been taken.
— 🟧 Order blocks are invalidated after 3+ bars if price closes beyond the opposite edge. This prevents old OBs that have clearly failed from persisting.
— ⚖️ The 4-factor score uses the volume delta from before the trend reset (preResetVolDelta) — not the current leg's delta, which would be zero at the moment of the flip. This correctly captures whether the previous leg had accumulation or distribution behind it.
— 📏 Win/loss tracking evaluates TP1 vs SL only — if TP1 is reached before SL, it's a win. The trade closes on the first event and is not re-evaluated.
— 🛠️ This is a trend-following signal and analysis tool , not an automated trading bot. It provides adaptive trend detection, liquidity context, order block zones, and signal quality grading — trade decisions remain yours.
— 🌐 Works on all markets and timeframes. Volume features auto-adapt to instruments without volume data (OBV and volume delta show "N/A"). Indicator
