Crypto Sniper Pro Smart Trend Range Filter Strategy Hariss 369It is a trend-following strategy designed to identify high-probability entries while filtering out sideways market conditions. It combines multi-timeframe trend confirmation with momentum and liquidity concepts to improve trade quality and reduce noise.
Strategy Features
• Multi-timeframe EMA trend confirmation
• Built-in range filter to avoid low-volatility consolidation
• Liquidity sweep detection for potential reversals
• Momentum breakout confirmation
• ATR-based dynamic Stop Loss and Take Profit
• Optional trading session filter
• Clean and lightweight strategy optimized for backtesting
Entry Logic
Long Entry
Price is above both the lower-timeframe EMA and higher-timeframe EMA.
The market is not inside a detected range.
At least one of the following conditions is satisfied:
Liquidity sweep to the downside followed by recovery
Bullish momentum breakout
Bullish continuation candle
Short Entry
Price is below both the lower-timeframe EMA and higher-timeframe EMA.
The market is not inside a detected range.
At least one of the following conditions is satisfied:
Liquidity sweep to the upside followed by rejection
Bearish momentum breakdown
Bearish continuation candle
Risk Management
The strategy uses ATR-based Stop Loss and Take Profit, allowing risk to automatically adjust to changing market volatility.
Best Markets
Cryptocurrency
Forex
Index CFDs
Stocks
Commodities
Recommended Timeframes
5 Minutes
15 Minutes
1 Hour
4 Hours
Notes
This strategy is intended for educational and research purposes. Always validate performance using TradingView's Strategy Tester before applying it in live markets, and adjust inputs to suit the characteristics of the asset and timeframe you trade.
## Disclaimer
This strategy is provided for educational and research purposes only. It does not constitute financial, investment, or trading advice. Past performance does not guarantee future results, and all trading involves substantial risk, including the potential loss of capital.
The strategy has been designed to assist with market analysis and backtesting. Performance may vary depending on the asset, timeframe, market conditions, broker, commissions, slippage, and user-defined settings. Users are encouraged to thoroughly test and optimize the strategy before using it in live trading.
The author makes no guarantees regarding profitability, accuracy, or suitability for any particular purpose. By using this strategy, you acknowledge that all trading decisions are made at your own risk, and the author shall not be held liable for any financial losses or damages arising from its use.
Stratégie

MACD Momentum Entry Engine [trade_w_samet]🎯 MACD Momentum Entry Engine
MACD Momentum Entry Engine is a structured momentum-analysis and visual trade-model indicator designed to help traders study confirmed MACD events, momentum quality, directional persistence, market regime, trend alignment, candle confirmation, and multi-target risk references directly from one coordinated workflow.
The script is built around one central idea:
A MACD event should not automatically become an entry signal.
Instead of treating every MACD crossover as equally meaningful, the engine first identifies the type of momentum event, then evaluates its strength, expansion, slope, acceleration, market environment, candle quality, directional persistence, and optional trend alignment before a permanent LONG or SHORT setup is accepted.
The indicator includes:
• Configurable MACD fast, slow, and signal lengths
• EMA, SMA, RMA, and WMA calculation options
• Early Trigger and Momentum Confirmed entry timing
• Reversal, Continuation, Zero-Line Reclaim, and Momentum Expansion setups
• A transparent 0–100 Momentum Quality Score
• Alignment, histogram strength, expansion, slope, and acceleration scoring
• Loose, Balanced, Strict, and Off quality modes
• A separate 0–100 Anti-Chop Market Regime Score
• ADX, price efficiency, EMA separation, and volatility-expansion analysis
• A separate 0–100 Entry Qualification Score
• Candle body, close location, MACD separation, persistence, impulse, and trigger-context analysis
• A final composite setup score
• A+, A, B, and C internal setup grades
• Optional chart EMA, confirmed higher-timeframe EMA, and combined trend bias
• Confirmed higher-timeframe calculations
• Zero-line directional filtering
• ATR-normalized absolute histogram-strength filtering
• Internal signal cooldown and same-bar re-entry protection
• One-active-trade-at-a-time visual management
• ATR-based and XAUUSD fixed-pip risk models
• Three visual take-profit levels
• Stop First and Targets First same-bar assumptions
• Equal-third internal trade-model accounting
• Active Entry, TP1, TP2, TP3, and SL lines
• Active reward and risk boxes on the main chart
• TP3-only historical trade-model preservation
• Separate SL, Closed TP1, Closed TP2, and TP3 result labels
• Adjustable LONG, SHORT, and result-label sizes
• MACD histogram, line, signal line, momentum background, and anti-chop background
• Neon LONG and SHORT dots directly on the MACD line
• A compact main-chart dashboard
• XAUUSD symbol verification and mismatch warning
• Static TradingView alert conditions
• Detailed dynamic alert() messages
• Data Window diagnostics
• Confirmed-close permanent signals
The purpose of this script is to provide a structured way to study when a MACD event is supported by broader momentum and market context.
It is not financial advice.
It is not an automated trading system.
It does not guarantee profitable trades.
It does not execute broker orders.
It does not replace personal analysis, position sizing, or risk management.
━━━━━━━━━━━━━━━━━━━━━━
📌 OVERVIEW
━━━━━━━━━━━━━━━━━━━━━━
At a high level, MACD Momentum Entry Engine does the following:
• Calculates a configurable MACD using the selected average types.
• Separates the visual histogram scale from the calculation scale.
• Detects confirmed MACD crossovers and zero-line events.
• Identifies Reversal, Continuation, Zero-Line Reclaim, and Expansion setup types.
• Optionally accepts the event immediately through Early Trigger mode.
• Optionally arms the setup and waits for renewed momentum through Momentum Confirmed mode.
• Measures momentum alignment, histogram strength, histogram expansion, MACD slope, and acceleration.
• Produces separate bullish and bearish 0–100 Momentum Quality Scores.
• Measures market regime using ADX, directional efficiency, EMA separation, and volatility expansion.
• Produces a separate 0–100 Market Regime Score.
• Evaluates candle direction, body quality, close location, MACD separation, persistence, and price impulse.
• Produces separate bullish and bearish Entry Qualification Scores.
• Combines momentum, regime, and entry quality into a final composite score.
• Assigns an internal A+, A, B, or C grade.
• Applies optional chart EMA and confirmed higher-timeframe EMA bias.
• Applies zero-line, absolute-strength, cooldown, and trade-slot controls.
• Confirms permanent LONG and SHORT signals only after candle close.
• Opens one visual trade model from the confirmed signal-bar close.
• Calculates Entry, Stop Loss, TP1, TP2, and TP3.
• Tracks targets and stop events from the next candle onward.
• Applies the selected same-bar processing assumption.
• Preserves completed TP3 models when historical display is enabled.
• Removes trade drawings after SL, Closed TP1, or Closed TP2 outcomes.
• Converts the original entry label into the final result for non-TP3 outcomes.
• Adds a separate electric-purple FULL TARGET label for TP3 outcomes.
• Displays Momentum, Trend, Regime, Trade, Last Result, and Protection states in the bottom-right dashboard.
• Provides static and dynamic alert options.
• Exposes diagnostic values through TradingView’s Data Window.
The indicator does not use machine-learning prediction.
Its scores are not probabilities.
Its labels do not promise future direction.
The script is a rule-based educational momentum framework that explains how a raw MACD event becomes an accepted or rejected setup.
━━━━━━━━━━━━━━━━━━━━━━
🧠 CORE IDEA
━━━━━━━━━━━━━━━━━━━━━━
The core idea behind MACD Momentum Entry Engine is that a crossover alone contains limited context.
A basic crossover only confirms that one MACD line has moved through another.
It does not automatically explain:
• whether the histogram is expanding
• whether momentum is accelerating
• whether the move is occurring in a directional or choppy market
• whether the signal candle supports the direction
• whether MACD separation is meaningful relative to recent behavior
• whether momentum has persisted
• whether price is aligned with an optional trend filter
• whether a recent signal already occurred
• whether a visual trade model is already active
The engine therefore uses a staged sequence:
MACD event
→ setup classification
→ momentum-quality scoring
→ optional trend-bias validation
→ anti-chop regime scoring
→ entry qualification
→ additional signal filters
→ confirmed signal
→ visual trade model
→ TP / SL lifecycle
→ result handling
For bullish conditions, the script studies upward MACD transitions, positive histogram alignment, renewed expansion, positive slope, positive acceleration, bullish candle behavior, and directional persistence.
For bearish conditions, the same process is mirrored.
The purpose is not to find the largest possible number of signals.
The purpose is to make the acceptance process visible, configurable, and understandable.
━━━━━━━━━━━━━━━━━━━━━━
🧩 WHY THIS SCRIPT IS NOT A SIMPLE BUY/SELL INDICATOR
━━━━━━━━━━━━━━━━━━━━━━
MACD Momentum Entry Engine is not designed to be used as a blind buy/sell system.
A raw MACD event must move through multiple stages:
A crossover or momentum event appears
→ the event is classified
→ the momentum-quality layer is evaluated
→ the trend-bias layer is evaluated
→ the anti-chop layer is evaluated
→ the candle and entry-quality layer is evaluated
→ zero-line and absolute-strength filters are checked
→ cooldown and active-trade restrictions are checked
→ the setup must remain valid at candle close
→ a permanent LONG or SHORT setup is printed
→ Entry, SL, TP1, TP2, and TP3 are projected
→ the trade model is monitored from the following candle
→ the model closes at TP3 or Stop
→ the final chart result is preserved or cleaned
Each module serves a different purpose.
The MACD core defines the momentum relationship.
The setup engine identifies what kind of event occurred.
The momentum-quality engine measures the internal strength of that event.
The anti-chop engine measures whether the broader environment is directional enough for the selected mode.
The entry-qualification engine evaluates the signal candle and immediate price response.
The trend-bias engine optionally restricts direction.
The trade engine standardizes the visual risk framework.
The dashboard explains the current engine state.
This makes the script a coordinated momentum-analysis workflow rather than a basic crossover marker.
━━━━━━━━━━━━━━━━━━━━━━
⚙️ HOW THE SCRIPT WORKS
━━━━━━━━━━━━━━━━━━━━━━
The script operates through connected calculation stages.
First, it calculates every supported moving-average type on every candle.
The selected average type is then used for the fast MACD average, slow MACD average, and signal average.
The MACD line is the difference between the selected fast and slow averages.
The histogram is the difference between the MACD line and the signal line.
fastAverage = f_selectMa(macdMaType, fastEma, fastSma, fastRma, fastWma)
slowAverage = f_selectMa(macdMaType, slowEma, slowSma, slowRma, slowWma)
macdLine = fastAverage - slowAverage
signalLine = f_selectMa(signalMaType, signalEma, signalSma, signalRma, signalWma)
histogram = macdLine - signalLine
The histogram visual multiplier changes only the displayed column length.
It does not change:
• the MACD line
• the signal line
• the histogram used by calculations
• quality scores
• setup detection
• trade results
After the MACD core is calculated, the engine measures:
• absolute histogram strength
• one-bar histogram expansion
• MACD slope
• momentum acceleration
• adaptive baselines for each measurement
The setup engine then checks the enabled event types.
The quality, trend, regime, qualification, and additional-filter stages determine whether the setup is eligible.
A final permanent signal is accepted only after the candle closes and every enabled condition remains valid.
━━━━━━━━━━━━━━━━━━━━━━
🟢 BULLISH MACD MOMENTUM LOGIC
━━━━━━━━━━━━━━━━━━━━━━
A bullish setup begins with one of four enabled event types.
Bullish Reversal
A bullish MACD crossover occurs while the MACD line remains below zero.
This represents a momentum turn from the negative side of the zero line.
Bullish Continuation
A bullish MACD crossover occurs while the MACD line is at or above zero.
This represents renewed bullish alignment on the positive side.
Bullish Zero-Line Reclaim
The MACD line crosses above zero while:
• MACD is above the signal line
• the histogram is positive
• the bar is confirmed
Bullish Momentum Expansion
The histogram resumes positive expansion after a short contraction while:
• MACD remains above the signal line
• MACD slope is positive
• no new crossover is being used on the same bar
• no new zero-line cross is being used on the same bar
The event must then pass the active momentum-quality requirement.
When enabled, it must also pass:
• chart EMA bias
• confirmed higher-timeframe EMA bias
• EMA slope confirmation
• ATR distance from the trend EMA
• anti-chop regime requirement
• entry qualification
• bullish candle direction
• minimum MACD separation
• momentum persistence
• zero-line direction
• absolute histogram strength
• cooldown
• active-trade availability
The final signal uses confirmed-bar logic.
bullishSignal =
barstate.isconfirmed and
bullishEntryCandidate and
bullishZeroLinePass and
absoluteStrengthPass and
bullishQualityPass and
bullishTrendPass and
antiChopPass and
bullishQualificationPass and
bullishCandlePass and
separationPass and
bullishPersistencePass and
cooldownPass and
tradeSlotAvailable
When every active rule passes, the script can display:
• a neon green dot on the MACD line
• a LONG label on the main chart
• setup type, grade, and score information
• a visual Entry, SL, TP1, TP2, and TP3 model
This confirms that the configured bullish momentum conditions were valid at candle close.
It does not mean price must continue upward.
━━━━━━━━━━━━━━━━━━━━━━
🔴 BEARISH MACD MOMENTUM LOGIC
━━━━━━━━━━━━━━━━━━━━━━
A bearish setup mirrors the bullish process.
Bearish Reversal
A bearish MACD crossover occurs while the MACD line remains above zero.
This represents a momentum turn from the positive side of the zero line.
Bearish Continuation
A bearish MACD crossover occurs while the MACD line is at or below zero.
This represents renewed bearish alignment on the negative side.
Bearish Zero-Line Reclaim
The MACD line crosses below zero while:
• MACD is below the signal line
• the histogram is negative
• the bar is confirmed
Bearish Momentum Expansion
The histogram resumes negative expansion after a short contraction while:
• MACD remains below the signal line
• MACD slope is negative
• no new bearish crossover is being used on the same bar
• no new bearish zero-line cross is being used on the same bar
The setup must then pass the same quality, trend, regime, candle, separation, persistence, strength, cooldown, and trade-slot controls.
A permanent SHORT signal appears only when all active conditions remain valid at candle close.
The script can then display:
• a neon red dot on the MACD line
• a SHORT label on the main chart
• setup type, grade, and score information
• Entry, SL, TP1, TP2, and TP3 references
This confirms that the configured bearish momentum conditions were valid at candle close.
It does not guarantee continued downside movement.
━━━━━━━━━━━━━━━━━━━━━━
💎 MACD MOMENTUM QUALITY FILTER SYSTEM
━━━━━━━━━━━━━━━━━━━━━━
The script includes a separate bullish and bearish Momentum Quality Score.
The quality layer evaluates five components.
Alignment — maximum 20 points
Bullish alignment requires:
• MACD above the signal line
• positive histogram
Bearish alignment requires:
• MACD below the signal line
• negative histogram
Histogram Strength — maximum 25 points
The absolute histogram value is compared with an adaptive EMA baseline.
This measures whether current separation is meaningful relative to recent MACD behavior.
Histogram Expansion — maximum 20 points
The engine measures the one-bar change in absolute histogram strength.
Points are awarded only when the histogram is expanding in the setup direction.
MACD Slope — maximum 20 points
Bullish setups require positive slope for this component.
Bearish setups require negative slope.
The slope magnitude is compared with its own adaptive baseline.
Momentum Acceleration — maximum 15 points
Acceleration measures the change in MACD slope.
Positive acceleration supports bullish scoring.
Negative acceleration supports bearish scoring.
bullishQualityScore = f_clamp(
bullishAlignmentScore +
bullishHistogramStrengthScore +
bullishExpansionScore +
bullishSlopeScore +
bullishAccelerationScore,
0.0,
100.0
The available quality modes are:
Off
Removes the minimum Momentum Quality Score restriction.
Loose
Requires a minimum score of 45.
Balanced
Requires a minimum score of 60.
Strict
Requires a minimum score of 75 and is the default.
The score is not a win rate.
It is not a probability.
It measures how closely the current MACD event matches the engine’s momentum-strength framework.
━━━━━━━━━━━━━━━━━━━━━━
📏 VOLATILITY / ATR NORMALIZATION FILTER
━━━━━━━━━━━━━━━━━━━━━━
The indicator uses ATR normalization to compare certain values across changing volatility conditions.
The Absolute Strength Filter calculates:
Absolute Histogram Strength = |Histogram| / ATR × 100.
This value is used as an additional minimum-strength condition.
The default settings are:
• Normalization ATR Length: 14
• Minimum Absolute Strength: 1.0
• Use Absolute Strength Filter: enabled
ATR normalization helps reduce dependence on the raw numerical scale of a market.
For example, a raw MACD histogram value cannot be compared directly across instruments with very different prices and volatility.
Normalization places the histogram in relation to the instrument’s recent ATR.
The same ATR framework is also used by:
• optional price-to-EMA trend buffers
• EMA-separation regime measurement
• price-impulse scoring
• ATR-based trade management
ATR normalization does not make one configuration universal.
Symbols, sessions, exchanges, and data feeds can still behave differently.
━━━━━━━━━━━━━━━━━━━━━━
🕯️ DISPLACEMENT QUALITY FILTER
━━━━━━━━━━━━━━━━━━━━━━
The entry-qualification engine evaluates whether the signal candle shows enough directional response.
The Candle component contributes up to 25 points.
It is divided into:
Directional Body — maximum 12.5 points
For bullish setups, the engine measures the positive candle body relative to the full candle range.
For bearish setups, it measures the negative body.
Close Location — maximum 12.5 points
Bullish setups receive more points when the close is nearer the candle high.
Bearish setups receive more points when the close is nearer the candle low.
Price Impulse contributes up to 15 additional points.
The engine compares the one-bar directional price movement with ATR.
A bullish price impulse measures positive close-to-close displacement.
A bearish price impulse measures negative close-to-close displacement.
This layer does not predict the next candle.
It measures whether the completed signal candle supports the direction of the MACD event.
━━━━━━━━━━━━━━━━━━━━━━
📊 REACTION STRENGTH FILTER
━━━━━━━━━━━━━━━━━━━━━━
The engine includes a separate Entry Qualification Score.
Its components are:
Candle Quality — maximum 25 points
Combines directional body and close location.
MACD Separation — maximum 25 points
Measures current histogram separation relative to its adaptive baseline.
Momentum Persistence — maximum 20 points
Measures how long directional MACD and histogram alignment has remained active.
Price Impulse — maximum 15 points
Measures directional close-to-close movement relative to ATR.
Trigger Context — maximum 15 points
Confirms that an eligible setup event is currently active.
The total is limited to 0–100.
Available modes are:
Off
Removes the minimum Entry Qualification Score restriction.
Loose
Requires a minimum score of 45.
Balanced
Requires a minimum score of 60.
Strict
Requires a minimum score of 75 and is the default.
The final signal also uses internal candle-direction, separation, and persistence requirements.
These internal parameters remain active in the background to keep the public settings menu cleaner.
The Entry Qualification Score is not a verified accuracy figure.
It describes the quality of the completed entry context according to the script’s rules.
━━━━━━━━━━━━━━━━━━━━━━
🧼 CONFIRMED SIGNAL FILTER
━━━━━━━━━━━━━━━━━━━━━━
Permanent LONG and SHORT signals wait for candle close.
The engine uses confirmed-bar checks on:
• MACD crossovers
• zero-line crossings
• expansion triggers
• momentum confirmation
• final LONG and SHORT conditions
The higher-timeframe trend layer also uses previous completed higher-timeframe values.
htfConfirmedClose = request.security(
syminfo.tickerid,
higherTimeframe,
close ,
gaps = barmerge.gaps_off,
lookahead = barmerge.lookahead_on
)
htfConfirmedEma = request.security(
syminfo.tickerid,
higherTimeframe,
ta.ema(close, trendLength) ,
gaps = barmerge.gaps_off,
lookahead = barmerge.lookahead_on
)
This approach prevents an unfinished higher-timeframe candle from becoming the permanent trend reference.
Entry Timing provides two workflows.
Early Trigger
Uses the confirmed setup event directly.
Momentum Confirmed
Arms the setup and waits for a later confirmed candle with:
• continued MACD alignment
• directional histogram
• renewed histogram expansion
• directional MACD slope
The confirmation opportunity is temporary.
If renewed momentum does not appear inside the internal window, the armed setup expires.
The script does not plot final signals into earlier candles.
Historical results can still change when:
• settings change
• symbol data changes
• timeframe changes
• the data provider revises history
• the available chart-history range changes
━━━━━━━━━━━━━━━━━━━━━━
🎯 ENTRY MODEL
━━━━━━━━━━━━━━━━━━━━━━
When a final LONG or SHORT setup passes every enabled condition, the trade engine can create a visual trade model.
The Entry reference is the close of the confirmed signal candle.
For a LONG model:
• Stop is below Entry
• TP1 is above Entry
• TP2 is above TP1
• TP3 is above TP2
For a SHORT model:
• Stop is above Entry
• TP1 is below Entry
• TP2 is below TP1
• TP3 is below TP2
tradeEntryPrice := close
tradeStopPrice := tradeEntryPrice - selectedStopDistance
tradeTp1Price := tradeEntryPrice + selectedTp1Distance
tradeTp2Price := tradeEntryPrice + selectedTp2Distance
tradeTp3Price := tradeEntryPrice + selectedTp3Distance
The model begins checking TP and SL from the following candle.
This prevents the signal candle’s earlier high or low from being treated as though it occurred after the close-based entry.
The engine stores:
• direction
• entry bar
• entry price
• stop price
• TP1 price
• TP2 price
• TP3 price
• initial risk
• target R values
• TP1 and TP2 progress
• setup type
• setup grade
• risk model
• original signal label
The displayed model is an educational chart reference.
It is not a broker order.
━━━━━━━━━━━━━━━━━━━━━━
🛑 ATR STOP-LOSS MODEL
━━━━━━━━━━━━━━━━━━━━━━
The indicator includes two risk models.
ATR Based
Stop distance is calculated as:
ATR × ATR Stop Multiplier.
The default settings are:
• ATR Length: 14
• ATR Stop Multiplier: 1.50
• TP1: 0.50R
• TP2: 1.00R
• TP3: 1.50R
The minimum distance is protected by the symbol’s minimum tick.
XAUUSD Fixed Pips
Stop and target distances use:
Selected Pips × XAUUSD Pip Size.
The default settings are:
• Pip Size: 0.01
• Stop Loss: 1000 pips
• TP1: 500 pips
• TP2: 1000 pips
• TP3: 1500 pips
Under the common 0.01 convention, those values correspond to:
• Stop distance: 10.00 price units
• TP1 distance: 5.00 price units
• TP2 distance: 10.00 price units
• TP3 distance: 15.00 price units
Broker conventions can differ.
Users should verify their symbol specification before relying on fixed-pip distances.
The XAUUSD protection system checks the symbol.
The dashboard shows:
• ✅ XAUUSD VERIFIED when XAUUSD Fixed Pips is used on a recognized XAUUSD symbol
• ⚠️ CHECK SYMBOL when the mode is used on another symbol
• 🛡️ ATR MODE when ATR Based is selected
The warning does not block calculations.
It tells the user to verify pip size and target distances.
━━━━━━━━━━━━━━━━━━━━━━
🎯 TAKE-PROFIT RR MODEL
━━━━━━━━━━━━━━━━━━━━━━
The visual model contains three take-profit levels.
ATR Based mode calculates targets from the initial stop distance:
TP1 Distance = Initial Risk × TP1 RR.
TP2 Distance = Initial Risk × TP2 RR.
TP3 Distance = Initial Risk × TP3 RR.
XAUUSD Fixed Pips mode uses independent fixed target distances.
The script enforces the following order:
TP1 < TP2 < TP3.
If a selected value would violate that order, the next target is moved at least one minimum tick beyond the prior target.
The trade model internally treats the position as three equal portions.
Each target represents one-third of the model.
If Stop is reached after TP1 or TP2, the script calculates an internal net-R result from:
• the portions already modeled as closed at reached targets
• the remaining portion or portions modeled at Stop
This internal calculation supports Data Window counters.
It is not broker-verified performance.
It does not account for:
• spread
• commission
• slippage
• latency
• partial-fill differences
• financing
• order rejection
• execution venue behavior
━━━━━━━━━━━━━━━━━━━━━━
📦 ACTIVE TP / SL BOX SYSTEM
━━━━━━━━━━━━━━━━━━━━━━
When a confirmed trade model opens, the script can draw on the main chart:
• Entry line
• TP1 line
• TP2 line
• TP3 line
• Stop Loss line
• TP1 reward box
• TP2 reward box
• TP3 reward box
• SL risk box
• LONG or SHORT label
The Entry line is white.
The TP lines are green and initially dashed.
The SL line is red and solid.
The SL box uses a solid border.
When a target is reached:
• the corresponding box becomes more visible
• the corresponding target line becomes solid
• the target line becomes thicker
• the dynamic target alert can fire
When TP3 is reached:
• the complete model closes
• the original LONG or SHORT label remains
• a separate electric-purple TP3 FULL TARGET label appears
• the trade model can remain historically visible
When the model closes at Stop before TP3:
• all active boxes are deleted
• all active trade lines are deleted
• the original LONG or SHORT label is converted into the final result
• the final result becomes SL, CLOSED TP1, or CLOSED TP2
Only TP3 outcomes can retain completed historical boxes and lines.
This is a chart-cleanliness decision.
It does not imply that other outcomes did not occur.
━━━━━━━━━━━━━━━━━━━━━━
🚦 ONE ACTIVE TRADE AT A TIME
━━━━━━━━━━━━━━━━━━━━━━
The script uses one-active-trade-at-a-time visual management.
When the trade engine is enabled:
• a new trade model cannot open while another model is active
• a new trade cannot open on the same candle that closed the previous model
• the internal setup engine continues calculating
• permanent signals are restricted by trade-slot availability
This prevents overlapping Entry, TP, and SL structures.
It also keeps the trade lifecycle easier to interpret.
When the trade engine is disabled, qualified signals can still be evaluated without opening a visual trade model.
The one-active-model rule is a visual and analytical design choice.
It does not restrict the user’s personal trading activity.
━━━━━━━━━━━━━━━━━━━━━━
⚠️ SAME-CANDLE TP / SL HANDLING
━━━━━━━━━━━━━━━━━━━━━━
Trade monitoring begins after the entry candle.
If a later historical candle touches both Stop and one or more targets, standard OHLC data does not reveal the exact intrabar sequence.
The indicator therefore provides two assumptions.
Stop First
If Stop and a target are both touched on the same candle, Stop is processed first.
This is the default and more conservative assumption.
Targets First
Reached targets are processed before Stop.
If TP3 is reached, the model closes at TP3.
Otherwise, remaining portions can close at Stop.
Neither mode reconstructs tick-level execution.
The indicator does not know:
• whether the high occurred before the low
• the bid/ask path
• actual fill sequence
• spread at the time
• slippage
• queue priority
• partial fills
The selected same-bar rule is a modeling assumption required by the limits of OHLC candles.
━━━━━━━━━━━━━━━━━━━━━━
🏷️ MACD MOMENTUM LABELS
━━━━━━━━━━━━━━━━━━━━━━
The indicator uses separate entry and result labels.
Entry labels display:
🚀 LONG
or:
🔴 SHORT
Entry Label Content provides:
Direction Only
Displays only LONG or SHORT.
Grade
Displays direction and setup grade.
Score + Grade
Displays direction, grade, and rounded composite score.
The default is Score + Grade.
LONG and SHORT label sizes can be adjusted independently.
Both default to Small.
The label tooltip contains:
• setup direction
• setup type
• setup grade
• composite score
• Momentum Quality Score
• Entry Qualification Score
• Market Regime Score
• trend-bias state
Result labels include:
🛑 SL
⚠️ CLOSED TP1
✅ CLOSED TP2
🏆 TP3 HIT
✅ FULL TARGET
SL, Closed TP1, and Closed TP2 transform the original entry label.
TP3 creates a separate result label and preserves the original entry label.
All chart-label text uses bold and italic formatting.
━━━━━━━━━━━━━━━━━━━━━━
📍 MACD DISPLAY MODES
━━━━━━━━━━━━━━━━━━━━━━
The indicator operates in a separate MACD pane while selected trade visuals, entry labels, and the dashboard are forced onto the main price chart.
The MACD pane can display:
MACD Line
A white line representing the difference between the selected fast and slow averages.
Signal Line
A red line representing the selected signal smoothing.
Histogram
Color changes communicate momentum condition:
• stronger green for bullish expansion
• softer green for bullish contraction
• stronger red for bearish expansion
• softer red for bearish contraction
Histogram Visual Length
The default multiplier is 1.60.
This changes visual column length only.
It does not affect calculations.
Neon Signal Dots
Qualified LONG setups produce a neon green glow and center dot on the MACD line.
Qualified SHORT setups produce a neon red glow and center dot.
Momentum Background
The pane background changes according to strong or weak bullish and bearish momentum states.
Anti-Chop Background
A neutral gray background can identify conditions blocked by the Anti-Chop Engine.
Each major visual element can be shown or hidden independently.
━━━━━━━━━━━━━━━━━━━━━━
🧹 SETUP INVALIDATION
━━━━━━━━━━━━━━━━━━━━━━
Not every raw MACD event remains eligible.
A setup can be rejected or expire because:
• its momentum score is below the selected threshold
• trend bias does not permit the direction
• the market regime is below the active Anti-Chop threshold
• the Entry Qualification Score is insufficient
• candle direction does not support the setup
• MACD separation is insufficient
• directional persistence is insufficient
• the zero-line filter blocks the direction
• normalized histogram strength is too low
• the signal cooldown is active
• another visual trade is active
• a trade closed on the current candle
• Momentum Confirmed mode does not receive renewed expansion in time
• an opposite raw setup replaces the armed direction
The internal cooldown is eight bars.
Momentum Confirmed mode uses a temporary internal confirmation window.
These background controls are intentionally not exposed as advanced public inputs.
They remain part of the engine’s consistency rules.
A rejected event is not displayed as a permanent entry signal.
━━━━━━━━━━━━━━━━━━━━━━
📟 DASHBOARD
━━━━━━━━━━━━━━━━━━━━━━
The indicator includes a compact dashboard in the bottom-right corner of the main price chart.
The dashboard displays:
Momentum
Possible states include:
• STRONG LONG
• LONG
• STRONG SHORT
• SHORT
• NEUTRAL
Trend
Possible states include:
• BULLISH
• BEARISH
• NEUTRAL
• OFF
Regime
Possible states include:
• TRENDING
• DEVELOPING
• CHOP
• OFF
Trade
Possible states include:
• WAITING
• LONG ACTIVE
• LONG TP1 REACHED
• LONG TP2 REACHED
• SHORT ACTIVE
• SHORT TP1 REACHED
• SHORT TP2 REACHED
Last
Displays the most recent closed model result:
• SL
• CLOSED TP1
• CLOSED TP2
• TP3
Protection
Displays:
• ATR MODE
• XAUUSD VERIFIED
• CHECK SYMBOL
The dashboard is not TradingView Strategy Tester.
It does not display audited brokerage results.
Its states are based on the indicator’s own rule-based calculations.
━━━━━━━━━━━━━━━━━━━━━━
🚨 ALERT SYSTEM
━━━━━━━━━━━━━━━━━━━━━━
MACD Momentum Entry Engine includes static TradingView alert conditions for:
• MACD Momentum LONG
• MACD Momentum SHORT
• TP1
• TP2
• TP3
• Stop Loss
• XAUUSD Mode Warning
The XAUUSD warning condition is limited to a qualified entry bar when Fixed Pips mode is active on a non-XAUUSD symbol.
The script also includes detailed dynamic alert() messages.
Dynamic Entry messages can include:
• direction
• symbol
• timeframe
• setup type
• setup grade
• composite score
• risk model
• Entry
• Stop Loss
• TP1
• TP2
• TP3
• XAUUSD mismatch warning when relevant
Dynamic target messages can include:
• target name
• direction
• symbol
• timeframe
• reached target price
• Entry
• Stop Loss
• TP1
• TP2
• TP3
Dynamic stop messages can include:
• final result
• direction
• symbol
• timeframe
• Entry
• exit price
• Stop Loss
• whether TP1 or TP2 was reached first
Alerts are monitoring tools.
They do not place or manage broker orders.
━━━━━━━━━━━━━━━━━━━━━━
🔔 HOW TO USE ALERTS
━━━━━━━━━━━━━━━━━━━━━━
For static conditions:
1. Add MACD Momentum Entry Engine to the chart.
2. Open TradingView’s Create Alert window.
3. Select the indicator as the condition.
4. Choose LONG, SHORT, TP1, TP2, TP3, SL, or XAUUSD Mode Warning.
5. Select a frequency appropriate for confirmed-candle monitoring.
6. Test the alert before relying on it.
For detailed dynamic messages:
1. Enable Detailed Dynamic Alerts in the indicator settings.
2. Open TradingView’s Create Alert window.
3. Select MACD Momentum Entry Engine .
4. Select Any alert() function call.
5. Configure the delivery method.
6. Test the complete message format.
Alert delivery can depend on:
• TradingView servers
• the selected symbol
• the selected timeframe
• market-data availability
• realtime feed status
• user alert configuration
• webhook or external-service availability
Creating an alert does not guarantee broker execution.
━━━━━━━━━━━━━━━━━━━━━━
🧪 HOW TO USE THE INDICATOR
━━━━━━━━━━━━━━━━━━━━━━
A practical workflow:
1. Add MACD Momentum Entry Engine to a standard candlestick chart.
2. Begin with the default MACD values of 12, 26, and 9.
3. Keep Entry Timing on Early Trigger while learning the setup types.
4. Keep Momentum Quality on Strict for the default selective profile.
5. Keep Anti-Chop on Strict.
6. Keep Entry Qualification on Strict.
7. Observe whether the event is Reversal, Continuation, Zero Reclaim, or Expansion.
8. Review the MACD histogram, line relationship, and neon signal dot.
9. Review the main-chart LONG or SHORT label.
10. Open the label tooltip to inspect the scores and setup type.
11. Review Momentum, Trend, Regime, Trade, Last Result, and Protection in the dashboard.
12. Verify the selected risk model.
13. When using XAUUSD Fixed Pips, confirm XAUUSD VERIFIED.
14. Treat Entry, SL, TP1, TP2, and TP3 as planning references.
15. Use alerts for monitoring rather than blind execution.
16. Compare every setup with personal structure, session, volatility, and risk rules.
17. Test the exact symbol, timeframe, session, and data feed personally used.
The indicator is designed for structured review.
It should not be treated as an automatic decision-maker.
━━━━━━━━━━━━━━━━━━━━━━
⚙️ SETTINGS REFERENCE
━━━━━━━━━━━━━━━━━━━━━━
⚙️ MACD Core
Calculation Source
Selects the price source used by the MACD calculation.
Fast Length
Controls the fast average.
Default: 12.
Slow Length
Controls the slow average.
Default: 26.
Signal Length
Controls signal-line smoothing.
Default: 9.
MACD Average Type
Selects EMA, SMA, RMA, or WMA for the fast and slow averages.
Signal Average Type
Selects EMA, SMA, RMA, or WMA for the signal line.
━━━━━━━━━━━━━━━━━━━━━━
🎯 Entry Engine
Entry Timing
Early Trigger accepts the confirmed setup event directly.
Momentum Confirmed waits for renewed directional histogram expansion and MACD continuation after the setup is armed.
━━━━━━━━━━━━━━━━━━━━━━
🧠 Momentum Quality Engine
Quality Filter
Selects Off, Loose, Balanced, or Strict.
Strict is the default.
The score combines:
• alignment
• histogram strength
• histogram expansion
• MACD slope
• momentum acceleration
━━━━━━━━━━━━━━━━━━━━━━
📈 Trend Bias Engine
Trend Bias Mode
Selects:
• Off
• Chart EMA
• Higher Timeframe EMA
• Combined EMA
Off is the default.
Trend EMA Length
Controls the chart and higher-timeframe EMA.
Default: 200.
Chart EMA Slope Lookback
Controls the chart-bar lookback used to evaluate EMA direction.
Require EMA Slope Confirmation
Requires a rising EMA for LONG and falling EMA for SHORT.
Higher Timeframe
Selects the confirmed higher-timeframe context.
Default: 60 minutes.
Price-to-EMA ATR Buffer
Requires an optional minimum ATR-normalized distance between price and the trend EMA.
Zero disables the distance requirement.
━━━━━━━━━━━━━━━━━━━━━━
🧱 Anti-Chop Engine
Anti-Chop Filter
Selects Off, Loose, Balanced, or Strict.
Strict is the default.
The regime score combines:
• ADX — 35 points
• price efficiency — 30 points
• EMA separation — 20 points
• volatility expansion — 15 points
━━━━━━━━━━━━━━━━━━━━━━
✅ Entry Qualification Engine
Enable Reversal Setups
Allows MACD crossovers on the opposite side of zero.
Enable Continuation Setups
Allows MACD crossovers on the directional side of zero.
Enable Zero-Line Reclaims
Allows confirmed MACD zero-line crossings with aligned histogram and signal-line conditions.
Enable Momentum Expansions
Allows renewed histogram expansion after contraction while MACD alignment remains valid.
Entry Qualification Filter
Selects Off, Loose, Balanced, or Strict.
Strict is the default.
The score combines:
• candle quality
• MACD separation
• persistence
• price impulse
• trigger context
━━━━━━━━━━━━━━━━━━━━━━
💼 Trade Management Engine
Enable Trade Engine
Enables the one-active-trade-at-a-time visual model.
Risk Model
Selects ATR Based or XAUUSD Fixed Pips.
XAUUSD Fixed Pips is the default.
ATR Length
Controls ATR for the adaptive model.
ATR Stop Multiplier
Controls stop distance in ATR mode.
ATR TP1 Risk/Reward
Controls TP1 distance in ATR mode.
ATR TP2 Risk/Reward
Controls TP2 distance in ATR mode.
ATR TP3 Risk/Reward
Controls TP3 distance in ATR mode.
XAUUSD Pip Size
Controls the price-unit value of one selected pip.
XAUUSD Stop-Loss Pips
Controls fixed Stop distance.
XAUUSD TP1 Pips
Controls fixed TP1 distance.
XAUUSD TP2 Pips
Controls fixed TP2 distance.
XAUUSD TP3 Pips
Controls fixed TP3 distance.
Same-Bar Resolution
Selects Stop First or Targets First.
Show Active TP / SL Zones
Shows Entry, targets, Stop, boxes, and lines on the main chart.
Keep Historical TP3 Zones
Preserves completed TP3 models.
Historical TP3 Trade Limit
Limits completed TP3 models retained on the chart.
Trade Result Labels
Enables SL, Closed TP1, Closed TP2, and TP3 result labels.
SL Label Size
Controls SL result size.
Closed TP1 Label Size
Controls Closed TP1 result size.
Closed TP2 Label Size
Controls Closed TP2 result size.
TP3 Label Size
Controls the separate FULL TARGET label size.
━━━━━━━━━━━━━━━━━━━━━━
🛡️ Signal Filters
Zero-Line Filter
Off allows both sides of zero.
Trend Direction requires LONG above zero and SHORT below zero.
Trend Direction is the default.
Use Absolute Strength Filter
Enables ATR-normalized minimum histogram strength.
Normalization ATR Length
Controls normalization.
Minimum Absolute Strength
Controls the required normalized histogram value.
━━━━━━━━━━━━━━━━━━━━━━
🎨 Visual Settings
Show MACD Line
Shows or hides the MACD line.
Show Signal Line
Shows or hides the signal line.
Show Histogram
Shows or hides histogram columns.
Histogram Visual Length
Changes histogram display scale without changing calculations.
Show MACD Neon Signal Dots
Shows qualified LONG and SHORT dots on the MACD line.
Show Momentum Background
Shows directional momentum background states.
Highlight Blocked Chop Conditions
Shows a neutral background when Anti-Chop blocks entries.
Show LONG / SHORT Labels
Shows or hides main-chart entry labels.
Entry Label Content
Selects Direction Only, Grade, or Score + Grade.
LONG Label Size
Controls LONG label size.
SHORT Label Size
Controls SHORT label size.
━━━━━━━━━━━━━━━━━━━━━━
📟 Mini Dashboard
Show Mini Dashboard
Shows or hides the compact bottom-right main-chart dashboard.
━━━━━━━━━━━━━━━━━━━━━━
🔔 Dynamic Alerts
Enable Detailed Dynamic Alerts
Enables runtime alert() messages.
For these messages, create the TradingView alert using:
Any alert() function call.
Input values are hidden from the status line.
MACD plot values are also prevented from creating status-line or price-scale labels, while diagnostic values remain available in the Data Window.
━━━━━━━━━━━━━━━━━━━━━━
🧠 WHAT MAKES THIS SCRIPT ORIGINAL
━━━━━━━━━━━━━━━━━━━━━━
MACD, moving averages, ATR, ADX, and trend filters are familiar technical-analysis concepts.
These concepts are not unique by themselves.
The originality of MACD Momentum Entry Engine lies in the coordinated process applied to a MACD event:
Configurable MACD event
→ setup-type classification
→ adaptive momentum-strength baselines
→ five-component Momentum Quality Score
→ optional confirmed trend-bias layer
→ four-component Anti-Chop Regime Score
→ five-component Entry Qualification Score
→ final composite score and grade
→ zero-line and normalized-strength validation
→ confirmed-close signal
→ one-active multi-target trade lifecycle
→ TP3-only historical preservation
→ non-TP3 visual cleanup
→ dynamic alerts
→ main-chart diagnostic dashboard
→ XAUUSD mode verification
Distinctive implementation features include:
• four separate setup families
• different logic for Reversal and Continuation crossovers
• zero-line reclaim detection
• renewed expansion detection without requiring a fresh crossover
• adaptive baselines for strength, expansion, slope, and acceleration
• separate bullish and bearish scoring
• a Momentum Quality Score independent from Entry Qualification
• an Anti-Chop Score independent from momentum quality
• confirmed previous higher-timeframe EMA values
• a 70/30 final composite structure
• A+, A, B, and C grades
• visual-only histogram scaling
• equal-third multi-target internal accounting
• same-candle processing assumptions
• XAUUSD symbol verification
• separate result behavior for TP3 and non-TP3 outcomes
• detailed Data Window diagnostics
The script is not a simple combination of unrelated indicators.
Every module supports the same objective: determining whether a confirmed MACD event has enough momentum, market, and entry context to become a permanent visual setup.
━━━━━━━━━━━━━━━━━━━━━━
⚠️ IMPORTANT PRACTICAL NOTES
━━━━━━━━━━━━━━━━━━━━━━
Signal frequency depends on:
• fast, slow, and signal lengths
• selected average types
• Entry Timing
• enabled setup families
• Momentum Quality mode
• Trend Bias mode
• EMA length
• higher timeframe
• EMA slope requirement
• price-to-EMA buffer
• Anti-Chop mode
• Entry Qualification mode
• zero-line filter
• absolute-strength threshold
• symbol
• timeframe
• session
• volatility
• available history
• data provider
• active-trade state
Strict modes reduce accepted signals.
They do not guarantee better results.
Trend Bias Off allows the momentum engine to evaluate both directions without EMA permission.
Higher Timeframe EMA and Combined EMA should use a timeframe meaningfully above the chart timeframe.
XAUUSD Fixed Pips is designed around a selectable pip convention.
The default 0.01 value may not match every broker or synthetic symbol.
Momentum Confirmed produces later and potentially fewer signals than Early Trigger.
Histogram Visual Length does not alter logic.
Changing settings recalculates historical signals and trade models.
A setup that looks different after changing the chart range may be affected by available historical data and adaptive baselines.
━━━━━━━━━━━━━━━━━━━━━━
⚠️ LIMITATIONS AND SHORTCOMINGS
━━━━━━━━━━━━━━━━━━━━━━
This script has important limitations:
It does not guarantee profitable trades.
It does not predict future price movement.
It does not execute orders.
It does not place broker stops or targets.
It does not include spread.
It does not include commission.
It does not include slippage.
It does not include latency.
It does not model partial fills.
It does not model financing or swap.
It uses bar-based OHLC data.
Historical candles do not reveal exact intrabar order.
Stop First and Targets First are assumptions.
The setup score is not a win probability.
A+ is not a guaranteed outcome.
The Anti-Chop Score cannot identify every ranging condition.
Trend filters can delay or block valid reversals.
Trend Bias Off can allow countertrend signals.
ATR normalization does not make settings universal.
Fixed-pip conventions can differ between brokers.
XAUUSD symbol detection cannot verify a broker’s contract specification.
The dashboard is not TradingView Strategy Tester.
Data Window counters are not audited account performance.
The internal R model assumes three equal portions.
The internal model does not represent real position sizing.
One-active-trade logic is a visual-management rule.
Alert delivery depends on TradingView and user configuration.
Changing settings changes historical calculations.
Changing symbol, exchange, session, timeframe, or feed can change signals.
Adaptive baselines depend on available chart history.
Confirmed higher-timeframe values reduce unfinished-HTF changes but introduce delay.
Permanent signals wait for candle close and therefore do not capture the earliest intrabar moment.
For these reasons, the indicator should be used as an educational decision-support tool, not as a standalone automated strategy.
━━━━━━━━━━━━━━━━━━━━━━
👤 WHO THIS SCRIPT MAY BE USEFUL FOR
━━━━━━━━━━━━━━━━━━━━━━
This script may be useful for traders who:
• already understand basic MACD behavior
• want more context than a raw crossover
• study momentum expansion and contraction
• distinguish reversal, continuation, zero-line, and expansion events
• want transparent setup scoring
• want an anti-chop layer
• want optional chart and higher-timeframe trend context
• prefer confirmed-close signals
• want Entry, SL, and three target references
• use XAUUSD and want configurable fixed-pip distances
• want symbol-mismatch warnings
• want a compact dashboard
• want detailed alerts
• want diagnostic Data Window values
• prefer one active visual model at a time
It may be less suitable for users who:
• want guaranteed signals
• want a fully automated trading bot
• want every MACD crossover displayed
• expect a score to equal probability
• expect one setting to work on every market
• require exact tick-level execution
• want Strategy Tester results from an indicator
• want the indicator to replace personal judgment
• expect alerts to execute broker orders automatically
━━━━━━━━━━━━━━━━━━━━━━
🧭 BEST PRACTICE SUGGESTIONS
━━━━━━━━━━━━━━━━━━━━━━
For the default selective profile:
• use standard candlesticks
• begin with MACD 12 / 26 / 9
• keep Entry Timing on Early Trigger
• keep Momentum Quality on Strict
• keep Anti-Chop on Strict
• keep Entry Qualification on Strict
• keep the Zero-Line Filter on Trend Direction
• keep Absolute Strength enabled
• keep all four setup families enabled while learning
• use the dashboard to identify blocked regime conditions
• verify the selected risk model before reviewing trade levels
• use Stop First for conservative historical same-bar handling
• confirm XAUUSD VERIFIED when using Fixed Pips
• use alerts for monitoring rather than blind execution
For additional frequency:
• change Momentum Quality from Strict to Balanced
• change Anti-Chop from Strict to Balanced
• change Entry Qualification from Strict to Balanced
• disable the Zero-Line Filter
• disable Absolute Strength
• keep Trend Bias Off
• use Early Trigger
For additional directional restriction:
• use Chart EMA, Higher Timeframe EMA, or Combined EMA
• enable EMA slope confirmation
• add a Price-to-EMA ATR Buffer
• use a higher timeframe above the chart timeframe
• use Momentum Confirmed instead of Early Trigger
Always:
• wait for the setup candle to close
• review the setup type
• review the score components
• verify market structure independently
• review session and volatility
• verify the stop distance
• use personal position sizing
• test the exact symbol and timeframe
• understand the same-bar assumption
• treat all projected levels as analytical references
━━━━━━━━━━━━━━━━━━━━━━
🔓 PUBLICATION NOTE
━━━━━━━━━━━━━━━━━━━━━━
MACD Momentum Entry Engine is published as an educational momentum-analysis and visual trade-model tool.
The purpose of this description is to explain:
• how the configurable MACD core is calculated
• how average types affect the MACD and signal lines
• how setup events are classified
• how Reversal setups work
• how Continuation setups work
• how Zero-Line Reclaim setups work
• how Momentum Expansion setups work
• how Early Trigger and Momentum Confirmed differ
• how the Momentum Quality Score is constructed
• how adaptive momentum baselines work
• how the Anti-Chop Score is constructed
• how the Entry Qualification Score is constructed
• how final composite scores and grades are assigned
• how chart and confirmed higher-timeframe trend filters work
• how zero-line and absolute-strength filters work
• when permanent signals appear
• how the one-active-trade model works
• how Entry and Stop are calculated
• how TP1, TP2, and TP3 are calculated
• how same-candle ambiguity is handled
• how historical TP3 visuals are retained
• how non-TP3 visuals are cleaned
• how result labels behave
• what the dashboard displays
• how XAUUSD protection works
• what static and dynamic alerts contain
• what diagnostic values are available
• what the timing limitations are
• what the model does not simulate
• why familiar MACD concepts are organized into an original workflow
The script is designed to support structured analysis.
It does not promise profitable results.
It does not remove market risk.
It does not execute trades.
It should not be used as a blind LONG/SHORT system.
MAIN CHART SCREENSHOT PLAN
Use one clean standard candlestick chart.
Show the indicator with its default settings.
The screenshot should contain:
• complete symbol and timeframe information
• the indicator name
• visible standard price candles
• one clear LONG or SHORT label
• one active or completed Entry / TP / SL model
• the white Entry line
• green TP1, TP2, and TP3 levels
• the red SL area and solid SL line
• the MACD pane
• the white MACD line
• the red signal line
• the green/red histogram
• one neon MACD signal dot
• the bottom-right main-chart dashboard
• the Protection state
Do not include:
• other indicators
• manual drawings
• unrelated labels
• social-media links
• pricing information
• promotional claims
• account-profit screenshots
• win-rate claims
• non-standard candles
• hidden symbol or timeframe information
• excessive zoom
• decorative graphics unrelated to the script
The screenshot should demonstrate normal default behavior and make the relationship between the MACD event, main-chart signal, trade model, and dashboard easy to understand.
━━━━━━━━━━━━━━━━━━━━━━
🛡️ DISCLAIMER
━━━━━━━━━━━━━━━━━━━━━━
MACD Momentum Entry Engine is provided for educational and informational purposes only.
It does not constitute financial, investment, trading, legal, or tax advice.
No indicator can guarantee future results.
Markets are uncertain.
Momentum changes.
Volatility changes.
Liquidity changes.
Historical chart behavior does not ensure future performance.
Every user is responsible for their own:
• analysis
• validation
• risk management
• position sizing
• alert configuration
• trading decisions
• broker execution
• legal obligations
• tax obligations
The MACD line, signal line, histogram, momentum states, setup types, quality scores, regime scores, entry scores, composite scores, grades, trend states, LONG and SHORT labels, Entry references, Stop Loss levels, take-profit levels, boxes, result labels, Data Window values, dashboard states, internal counters, and alerts are visual analysis tools only.
The displayed Entry is not a guaranteed fill.
The displayed Stop Loss is not a broker order.
The displayed TP1, TP2, and TP3 levels are not guaranteed objectives.
The Momentum Quality Score is not a win probability.
The Entry Qualification Score is not a probability.
The Market Regime Score is not a guarantee that a market is trending.
The A+, A, B, and C grades are not promises of performance.
The internal trade model does not include spread, commissions, slippage, latency, order-book conditions, contract specifications, or partial fills.
Use this script as a structured MACD momentum-review and decision-support framework, not as a promise of profitability or a substitute for independent judgment. Indicateur

DAX Universe Relative Strength [JS]DAX Universe Relative Strength
This indicator compares the current stock with an equal-weighted German stock market benchmark consisting of DAX, MDAX, SDAX and TecDAX.
Instead of comparing a stock only with one single index, the script creates a broader DAX Universe benchmark by calculating the average performance of the four major German equity indices over a selected lookback period.
The goal is to identify whether a stock is showing relative strength or relative weakness versus the broader German stock universe.
How it works:
1. The script measures the performance of the current stock over the selected comparison period.
2. It measures the performance of DAX, MDAX, SDAX and TecDAX over the same period.
3. It calculates the equal-weighted average performance of these four indices.
4. It compares the stock’s performance with this benchmark.
5. The result is plotted as a relative strength line.
Interpretation:
- RS above 0:
The stock is outperforming the DAX Universe benchmark.
- RS below 0:
The stock is underperforming the DAX Universe benchmark.
- RS above its moving average:
Relative strength is improving.
- RS below its moving average:
Relative strength is weakening.
- Strong RS signal:
The stock is above the benchmark, above its RS moving average, and the RS moving average is rising.
This indicator is designed as a filter, not as a standalone buy or sell signal.
For pullback and swing trading, I use it to identify stocks that are stronger than the broader German market. A strong RS reading does not mean that a stock should be bought immediately. It only means that the stock deserves attention and may be worth adding to a watchlist.
A complete trade setup should also include:
- constructive trend structure
- price above important moving averages
- controlled pullback
- declining selling pressure
- clear pivot or trigger
- defined stop-loss
- attractive risk/reward ratio
The indicator includes:
- relative strength line
- moving average of the RS line
- zero line
- histogram
- background highlighting
- interpretation label
- alert conditions for RS changes
Suggested use cases:
- screening German stocks
- comparing DAX, MDAX, SDAX and TecDAX stocks
- identifying potential market leaders
- filtering pullback candidates
- avoiding stocks with persistent relative weakness
Important:
This script is for educational and analytical purposes only. It does not provide investment advice, buy signals or sell signals. Always combine relative strength analysis with your own chart analysis, risk management and trading plan. Indicateur

Indicateur

Dual Log Regression Channels [BigBeluga]Dual Log Regression Channels is a highly advanced multi-timeframe mathematical modeling terminal engineered for TradingView. It maps, projects, and blends two independent logarithmic regression channels directly onto your asset layout screen to deliver an institutional-grade perspective on trend structure, market cycles, and structural volume distributions.
By separating price discovery parameters into a long-term Macro Channel and an execution-focused Short Term Channel, this tool effectively resolves the classic trader conflict of assessing structural trend directions while looking for immediate micro execution setups. Rather than treating market space as flat, standard geometric lines, this engine runs an advanced curve-fitting algorithm over your data to follow the exponential nature of capital expansion and distribution.
🔵 INTUITIVE SYSTEM ARCHITECTURE & ENGINE FEATURES
1. Logarithmic Regression Curve Optimization
Non-Linear Structural Tracking: Standard linear regression struggles with volatile crypto or high-growth equity trends over massive lookback structures. This script continuously converts incoming data matrices into mathematical log-space, computes a best-fit ordinary least squares (OLS) linear progression, and converts the output back into exponential value curves.
Dual Horizons Convergence Layer: Tracks an extensive trend anchor block (defaulting to 300 bars) simultaneously with a highly responsive, high-velocity swing lookback matrix (defaulting to 50 bars). This exposes localized micro contractions occurring right at major macro boundary extremes.
Visual Deviation Spacing Bands: Channels automatically map out distinct volatility boundaries based on real-time Standard Deviation multipliers. This defines predictable mathematical risk corridors where asset expansions typically exhaust and snap back toward the median baseline.
2. Predictive Channel Extension & Real-Time Trend Direction Arrows
Dynamic Origin Trend Arrows: The engine processes a dedicated directional diagnostic framework at the precise historical start (origin node) of each lookback channel. It generates sharp, high-visibility glyph trend arrows ( ⇗ for structural uptrends and ⇘ for structural downtrends). These arrows offer an instant, real-time assessment of the mathematically calculated baseline slope, entirely bypassing visual guesswork when channels run relatively flat.
Forward-Projected Space Models: When enabled, both the Macro and Short-Term structural bands project forward into the future chart space blank zone (e.g., 50 bars ahead for Macro, 20 bars for Short-Term). This lets you visually identify intercept locations and major trend crossroads long before price action arrives.
3. Adaptive Embedded Channel Volume Profiles (VP)
Integrated Block Volume Binning Matrix: Moving beyond basic fixed or visible range volume profiles, this module segments and collects transacted volume profiles exclusively inside the exact coordinate boundaries of each respective channel.
Dynamic Coordinate-Aligned Shading Bars: The volume profile rows scale and project outward utilizing advanced polyline geometry arrays, maintaining structural alignment with the slope of the moving channel boundaries.
Point of Control (POC) Trailing Baselines: Automatically tracks and renders a crisp, high-visibility solid horizontal baseline ( POC Line ) marking the exact price bin location that attracted the highest volume concentration throughout that lookback phase.
4. Volumetric Delta Tracking Panels
Buy vs. Sell Volume Accumulation Blocks: Aggregates total execution volume during the lookback period, classifying volume based on bar polarity.
Net Order Flow Delta Percentages: Computes and prints the precise net mathematical buying/selling pressure delta inside the channel. This reveals quiet accumulation behavior or hidden distribution trends directly alongside your spatial boundary drawings.
🔵 SYSTEMATIC EXECUTION STRATEGIES & RISK INTERPRETATION
Confluence Zone Intercept Trading: Look for setups where the Short Term Channel’s outer standard deviation boundaries align directly with the Macro Channel's major structural lines. When a high-velocity micro asset trend exhausts itself at a long-term macro floor or ceiling, it marks a highly efficient, asymmetric inflection zone for trend continuation entries or macro reversals.
Volume Profile POC Mean Reversion Matrix: The volume profile POC lines show where massive institutional blocks shifted hands inside that channel's lifespan. If the market stretches thin near an upper outer boundary but net volumetric volume indicators begin shifting toward seller control, look for a swift mean-reversion move down toward the high-liquidity POC baseline node.
Trend Acceleration vs. Overextended Breakouts: When an asset forces a candle close completely outside the projected log channel boundaries, it flags an exceptional shift in trend velocity. If the Volume Delta percentage prints an explosive spike in that direction, it supports a trend acceleration play. If volume is thin, it warns you of a predatory, overextended fakeout structure that is likely to snap back into the central channel values.
🔵 INTERFACE CONFIGURATION AND PARAMETERS
Lookback & Deviation Tuning Blocks: Customize historical calculation boundaries and volatility widths separately for both trend layers to match any asset class or time frame preference.
Volume Profile Customization: Control the precise resolution of the volume profile by adjusting row count bins and max bar widths to match your specific layout.
Clean Workspace Overrides: Toggle visibility filters to hide median baselines, remove raw background asset lines, or completely customize color theme hex codes to fit cleanly within your setup without causing visual clutter.
Transform your charting environment from basic straight lines into an exponential, volume-weighted structural map with the Dual Log Regression Channels terminal. Indicateur

UT Bot v2 - ATR Trailing StopIf you're familiar with the original UT Bot: the core logic is the same. This version focuses on cleaner visuals, improved code quality, better customization, built-in alerts, and integrated strategy support, while preserving the underlying ATR trailing stop methodology.
UT Bot v2 is a modernized implementation of the original UT Bot, built around the same ATR-based trailing stop logic that made the original popular.
The indicator uses an adaptive trailing stop based on the Average True Range (ATR). When price crosses the stop level, the trend state flips and a new trailing stop begins to form in the opposite direction.
Rather than changing the algorithm, this release focuses on making it clearer, easier to configure, and more practical for everyday use.
Features
Classic ATR trailing stop logic
Clean and intuitive trend visualization
Buy and sell signal markers
Configurable ATR period and multiplier
Customizable price source
Built-in TradingView alerts
Integrated strategy for backtesting
Lightweight and easy to understand
Methodology
UT Bot v2 is not a predictive indicator. It does not attempt to forecast future price movements or identify exact market tops and bottoms.
Instead, it is a trend-following and risk management tool that dynamically adjusts its trailing stop using market volatility measured by ATR.
Like most trend-following systems, it tends to perform best during sustained directional moves and may generate whipsaws during ranging or low-volatility conditions.
Philosophy
The goal of UT Bot has always been to provide a simple, transparent, and systematic trailing stop framework, rather than a "holy grail" trading system.
This version preserves that philosophy while improving readability, customization, visualization, and integration with TradingView alerts and strategy testing. Stratégie

Market Cycle Wave [Gabremoku]Market Cycle Wave is a price-based cycle indicator built to map broad market phases into a readable oscillator and a price-anchored overlay.
Instead of relying on a single signal, the script combines trend, momentum, volatility, and range-position data into a composite cycle score. That score is normalized and smoothed to create an intermediate Cycle Wave, while a slower Secular line provides broader context.
The script has two main views:
- an oscillator pane with the score histogram, Cycle Wave, Secular baseline, and major Cycle Peak / Cycle Trough labels.
- a price overlay with a cycle line, gradient aura, and a thinner secular context line.
The regime model classifies market conditions into Debt Accumulation, Deleveraging, Reflation, and Transition. The goal is not to generate standalone buy/sell signals, but to help traders read where price may sit inside a broader market cycle structure.
How to use it
This indicator works best on broad indices and diversified equity ETFs, where cycle behavior is usually cleaner than on highly erratic single names.
Typical use:
- Daily chart: monitor intermediate cycle shifts
- Weekly chart: study broader regime transitions
Practical reading:
- A rising blue cycle wave can suggest constructive expansion conditions
- A yellow rollover after a mature advance can suggest a weakening cycle structure
- Deep negative readings followed by green recovery can suggest reflation or post-stress repair
- The secular line helps show whether the shorter cycle is moving with or against the broader backdrop
The dashboard summarizes the current regime, state, direction, score, risk posture, and color legend directly on the chart.
How it works
The cycle model uses eight price-based factors:
- Fast EMA vs slow EMA relationship
- Fast EMA slope
- RSI momentum regime
- RSI extremes
- Position inside the rolling yearly range
- Distance from yearly extremes
- ATR volatility regime
- Price position vs the slow EMA
Each factor contributes to a composite score. That score is then normalized, smoothed, and accumulated over a rolling memory window to build a bounded cycle wave around a midpoint.
A second and slower baseline is built through longer smoothing to represent secular context. This creates two distinct layers:
- Cycle Wave: the intermediate cycle, more reactive to market swings
- Secular Baseline: the broader context, slower and less sensitive
Recent Cycle Peak and Cycle Trough labels are pivot-based, so the latest labels need confirmation from future bars. Indicateur

Adaptive Trend Expansion Bands [BigBeluga]Adaptive Trend Expansion Bands is an advanced, volatility-scaled mathematical modeling terminal engineered for TradingView. It operates as a dynamic trend-following corridor system that maps asset extension, mean-reversion horizons, and structural exhaustion thresholds across four distinct mathematical volatility tiers.
Rather than relying on static channels or fixed-percentage envelopes, this system uses an adaptive algorithmic architecture. It combines a selectable baseline smoothing core (such as an EMA or HMA) with standard Average True Range (ATR) step multipliers. This approach maps predictable, gradient-shaded risk corridors that expand and contract in perfect synchronization with real-time market volatility.
🔵 SYSTEM ARCHITECTURE & EXECUTING CORE ENGINES
1. Smooth Multi-Engine Core Baseline
Selectable Mathematical Foundations: The central anchor line runs your preferred moving average smoothing type ( SMA, EMA, WMA, or HMA ). This allows you to tailor the script to act as a responsive high-velocity scalp line or an institutional trend tracking system.
Volatility Expansion Envelopes: Spawns four upper and four lower risk bands symmetrically off the baseline. Driven by the asset's raw ATR Length , these bands act as a multi-layered support and resistance map, defining exactly where price action transitions from normal distribution into extreme variance.
2. Asymmetric Structural Trend Inversion Locking
Zone 3 Structural Threshold Flipped Tracking: The script utilizes a structural state machine that changes color parameters only when a candle successfully forces a crossover above the upper Zone 3 band ( Bullish Lock ) or a crossunder below the lower Zone 3 band ( Bearish Lock ).
Clean Workspace Overwrites: Once a trend direction is verified, the engine overwrites your primary layout candle bars with clear, customized hex-theme presets ( Bullish/Bearish Base Colors ) to maintain absolute structural awareness.
Dynamic Zone-Tier Mapping Labels: When a structural trend shift occurs, the system prints crisp zone indicators ( +1 to +4 or -1 to -4 ) directly in the background spaces to immediately define the volatility tiers.
3. High-Variance Exhaustion Spotting (Zone 4 Hits)
Counter-Trend Spike Identifiers: The terminal flags moments when an active trend experiences a sudden, high-velocity counter-trend surge into deep premium or discount territory ( Zone 4 Extreme Target Layers ).
Localized Inversion Candlestick Highlights: The exact candle that spikes into a Zone 4 level is instantly recolored with a high-visibility contrast override ( Zone 4 Hit Candle Color ). This provides immediate visual warning of exhaustion before any pullback begins.
Anti-Overlap Cooldown Guardrails: Built-in index buffer logic ( Zone 4 Label Bar Gap ) prevents the system from cluttering your workspace with consecutive text labels during high-velocity runs.
4. Automatic Order-Tracking Boxes & Escape Latches
Historical Low/High Sizing Brackets: The moment a Zone 4 anomaly is logged, the graphical engine automatically anchors a structural box tracking the recent 3-bar high/low territory.
Dynamic Trailing Tracker Dashed Lines: Extends crisp upper and lower horizontal tracker boundaries from the exhaustion point. These dashed lines track the consolidation range and remain active until the market breaches either boundary, triggering a directional arrow glyph ( ▲ or ▼ ) to mark the breakout.
🔵 SYSTEMATIC EXECUTION STRATEGIES & RISK INTERPRETATION
Counter-Trend Overextension Inversions: When an asset is structurally trading in a downtrend but experiences an aggressive squeeze that spikes into the upper Zone 4 envelope, it triggers a Zone 4 exhaustion print. This alerts you that buyers have pushed deep into an illiquid mathematical ceiling. Look for short-side setups as price targets a mean-reversion move back down toward the primary baseline.
Zone Range Breakdown Continuations: Monitor the horizontal dashed tracking lines spawned by a Zone 4 hit. If price action consolidates inside these boundaries and then prints a strong close outside the high/low bracket, look to trade the breakout in that direction, using the opposite dashed line as a hard risk invalidation level.
Trend Health Assessment via Gradient Fills: Use the layered background fills to gauge trend strength. Healthy, sustainable trends typically ride smoothly along the Zone 1 and Zone 2 channels. When price aggressively pierces into Zone 3 or Zone 4, it signals a climax state, warning you to tighten trailing protective lines or take profits before a mean-reversion event.
🔵 INTERFACE CONFIGURATION AND PARAMETERS
Core Mathematical Tuning: Easily adjust baseline types, lookback periods, and baseline multipliers to optimize the indicator for any asset class, volatility cycle, or chart time frame.
Exhaustion Label Cleanliness Filters: Customize the bar index gap parameters to keep your layout workspace clean and legible during highly volatile market conditions.
Visual Theme Customization Modifiers: Fully adjust color properties for bullish states, bearish states, and exhaustion candle overrides to blend seamlessly into your dark or light charting interface.
Transform your charting layout from flat geometric indicators into a highly responsive, volatility-scaled risk map with the Adaptive Trend Expansion Bands terminal. Indicateur

Sweep Runover Trend CandleEnglish Version
Title: Sweep Runover System
Description:
The Ultimate Sweep Runover System is a complete, all-in-one trading toolkit designed to detect liquidity sweeps, confirm structural shifts, and manage your risk automatically. Whether you are trading forex, crypto, or indices, this indicator visually guides you through the entire lifecycle of a trade from setup to take profit.
Key Features:
Liquidity Sweep Detection: Automatically plots structural highs/lows and marks liquidity sweeps with customizable lines and labels (default 'X').
Trend Confirmation (Hollow Candles): Filters out fake-outs by waiting for a candle close beyond the setup. Once confirmed, the trend changes dynamically, painting beautiful neon hollow candles (Green for Bullish, Red for Bearish).
Advanced Stop Loss & R:R Targets: Automatically calculates your Stop Loss based on either the Recent Swing or the Trigger Candle. It instantly plots customizable Risk-to-Reward (R:R) Target lines (T1, T2) directly on the chart with exact price labels.
MTF Dashboard: A sleek, customizable table that tracks the real-time trend status across your current timeframe and up to 4 higher timeframes simultaneously.
Session Killzones: Optional time filters allow you to only hunt for setups during specific high-volume trading sessions (e.g., London or NY Open).
Pro Alert System: Fully integrated with custom JSON Webhook alerts, making it plug-and-play ready for auto-trading bots (3Commas, PineConnector, etc.).
Beautiful Custom UI: Every visual element—from neon colors and line styles to label distances and historical line cleanup—can be easily customized in a highly organized settings menu.
How to Use:
Wait for the indicator to mark a sweep (X). If price confirms the runover, the candles will change color, and your SL/TP lines will appear. Manage the trade using the automatically plotted R:R targets and keep an eye on the MTF Dashboard for higher timeframe confluence!
Tamil Version (தமிழ்)
தலைப்பு: Sweep Runover System
விளக்கம்:
Ultimate Sweep Runover System என்பது மார்க்கெட்டில் நடக்கும் லிக்விடிட்டி ஸ்வீப்களை (Liquidity Sweeps) கண்டறிந்து, ட்ரெண்ட் (Trend) மாறுவதை உறுதிசெய்து, உங்கள் ரிஸ்க்கை (Risk) ஆட்டோமேட்டிக்காக நிர்வகிக்க உருவாக்கப்பட்ட ஒரு முழுமையான இண்டிகேட்டர் ஆகும். ஃபாரெக்ஸ், கிரிப்டோ அல்லது ஸ்டாக்ஸ் என எதில் ட்ரேட் செய்தாலும், என்ட்ரி முதல் டேக் ப்ராஃபிட் (Take Profit) வரை இந்த சிஸ்டம் உங்களை சரியாக வழிநடத்தும்.
முக்கிய அம்சங்கள்:
Liquidity Sweep Detection: மார்க்கெட் ஸ்ட்ரக்சரை அனலைஸ் செய்து, லிக்விடிட்டி ஸ்வீப்களை எளிதாகக் கண்டறிந்து குறியீடுகள் (X) மூலம் காட்டுகிறது.
Trend Confirmation (Hollow Candles): ஃபேக்-அவுட்களை (Fake-outs) தவிர்ப்பதற்காக, கேண்டில் க்ளோஸ் (Candle Close) ஆகும் வரை காத்திருந்து ட்ரெண்டை உறுதி செய்கிறது. ட்ரெண்ட் மாறியதும், அழகான நியான் ஹாலோ கேண்டில்களாக (Bullish-க்கு பச்சை, Bearish-க்கு சிவப்பு) நிறம் மாறும்.
Advanced Stop Loss & R:R Targets: உங்களின் ஸ்டாப் லாஸை Recent Swing அல்லது Trigger Candle அடிப்படையில் இதுவே கணக்கிட்டுக்கொள்ளும். மேலும், உங்களுடைய Risk-to-Reward (R:R) அடிப்படையில் டார்கெட் லைன்களை (T1, T2) சரியான விலையுடன் சார்ட்டிலேயே வரைந்து காட்டும்.
MTF Dashboard: நீங்கள் பார்த்துக்கொண்டிருக்கும் டைம்ஃபிரேம் மட்டுமின்றி, கூடுதலாக 4 பெரிய டைம்ஃபிரேம்களின் (Higher Timeframes) ட்ரெண்ட் நிலையை ஒரே டேஷ்போர்டில் உடனுக்குடன் தெரிந்துகொள்ளலாம்.
Session Killzones: மார்க்கெட்டில் வால்யூம் அதிகமாக இருக்கும் நேரங்களில் (எ.கா. London / NY Session) மட்டுமே ட்ரேட் செய்ய, பிரத்யேக டைம் ஃபில்டர்கள் (Time filters) கொடுக்கப்பட்டுள்ளன.
Pro Alert System: ஆட்டோ-ட்ரேடிங் பாட்களை (Auto-trading bots) பயன்படுத்துபவர்களுக்காகவே Custom JSON Webhook அலர்ட் வசதி கொடுக்கப்பட்டுள்ளது.
Beautiful Custom UI: நிறங்கள், லைன் ஸ்டைல்கள், மற்றும் டேஷ்போர்டு டிசைன் என அனைத்தையும் செட்டிங்ஸில் உங்களுக்கு ஏற்றவாறு எளிதாக மாற்றியமைத்துக் கொள்ளலாம்.
எப்படி பயன்படுத்துவது?
இண்டிகேட்டர் ஸ்வீப்பை (X) மார்க் செய்யும் வரை காத்திருங்கள். ட்ரெண்ட் பிரேக்-அவுட் ஆனதும் கேண்டில்களின் நிறம் மாறும், கூடவே உங்களின் SL மற்றும் டார்கெட் லைன்கள் சார்ட்டில் தோன்றும். ஆட்டோமேட்டிக்காக வரையப்படும் R:R டார்கெட்டுகளைப் பயன்படுத்தி ட்ரேடை வெற்றிகரமாக முடியுங்கள். MTF டேஷ்போர்டை கவனித்து மார்க்கெட்டின் பெரிய ட்ரெண்டோடு இணைந்து பயணியுங்கள்! Indicateur

The Boy Plunger | AnonycryptousThe Boy Plunger | Anonycryptous
Description & user manual
Why is this indicator different?
Most breakout indicators do one thing: they draw a line and fire a signal when price crosses it. They do not ask whether the move is real. They do not ask whether the volume confirms it. They do not ask whether the broader trend supports it. They just fire.
The Boy Plunger is built on a different philosophy. It does not look for crossings. It looks for proof.
Every signal in this indicator requires the market to pass through a series of gates before anything fires. A key structural level must be present. Price must approach it with observable intent. Volume must confirm participation. The body of the breakout candle must show conviction. The ribbon must be aligned with the move. Only when all required conditions are satisfied does a signal appear.
This is confirmation trading in its strictest form. It produces fewer signals than most indicators. That is not a weakness. That is the point.
Most indicators on TradingView that claim to be based on Livermore's method are either a single pivot high/low scanner or a basic breakout line. None of them implement the full confirmation philosophy — the waiting zone, the volume proof, the structural gate, the failed breakout detection. This indicator does all of that in a single tool, across all markets and timeframes, with a modular seven-preset system that lets you trade pure Livermore methodology or adapt it to modern intraday conditions.
A tribute to Jesse Lauriston Livermore (1877-1940)
He started with five dollars and a notebook. No connections, no capital, no safety net — just the ability to read price and the discipline to wait. By 1929 he had turned that into an estimated one hundred million dollars, shorting the crash while the rest of the world burned.
He defined what it means to trade with conviction. Wait for the decisive point. Watch how the market behaves around key levels. Demand proof before committing. Exit without hesitation when the market proves you wrong.
He called these moments pivot points — not a formula, but a philosophy. The market reveals its hand when it breaks away from structure with strength and volume. Everything before that is noise.
But Livermore also lost it all. Four times. He broke his own rules, overtraded, let emotion overrule his system. The man who made one hundred million dollars was declared bankrupt in 1934. On November 28, 1940, he took his own life in a New York hotel. His farewell note read: "My life has been a failure."
It wasn't. He gave traders a language to describe what markets do. A century later, his observations are still the foundation of how serious traders think about price.
This indicator is built on his principles:
- structure defines the battlefield
- volume confirms the move
- trend determines the direction
- proof before entry, always
What you do with it is your decision.
1. Overview
The Boy Plunger is a multi-engine confluence indicator built for traders who want to trade with structure, confirmation, and discipline. It works on all markets and timeframes — equities, crypto, futures, forex, indices. Nothing is hardcoded to a specific instrument.
The indicator contains seven engines that work together:
- Silk ribbon — multi-strand MA system for macro trend
- Htf levels — higher timeframe pivot structure as key levels
- Volume engine — spike detection with delta confirmation
- Signal gate — preset-based multi-condition filter
- Fvg engine — fair value gap detection for entry refinement
- Htf reversal radar — multi-timeframe warning system
- Trade block — locked entry, stop, and take profit management
All seven engines are visible simultaneously on the main chart. The dashboard gives you a real-time read of every active condition. The trade block locks the moment a signal fires and does not move until the trade is resolved.
2. The waiting zone system
This is the core visual innovation of the indicator. Rather than coloring elements only when a signal fires, every component communicates the current stage of a developing setup:
Scanning — price is away from any key level. The ribbon is grey and dimmed. No setup is developing.
Watching — price has entered the proximity zone around a key htf level (within a configurable ATR distance). The level turns gold. The waiting zone is active. This is the "I am watching" state that Livermore described — the market is approaching the decisive point but has not proven anything yet.
Confirmed — price breaks the level with volume spike and body conviction. Everything fires to full color. The signal candle is highlighted. If the preset requires it, the signal fires.
This three-state system means the chart is always telling you something — not just when a signal happens, but what stage of development you are in. Scanning means relax. Watching means pay attention. Confirmed means decide.
3. Presets
The indicator has seven presets that define which gates are required for a signal to fire. You change the preset in the settings under the preset group.
Livermore
The purest implementation of his method. No EMA gate — he did not use EMAs. Level proximity required. Volume spike required. Body conviction required. This preset is designed for traders who want to apply his original philosophy as closely as possible to modern markets. The recommended cooldown is 10 bars based on testing across multiple instruments — long enough to avoid noise, short enough to catch valid retests of confirmed levels. Best results observed on 15m and above.
Boy plunger
The intraday adaptation. Macro trend gate added via the ribbon (HMA 8/21 by default). Level required. Volume required. Body required. Cooldown shorter by default. Built for scalp-oriented traders who want Livermore's structure logic on faster timeframes. The HMA is used instead of EMA because of its faster response and cleaner directional read on lower timeframes.
Ribbon
Uses the MA cross as the primary gate. The level acts as a structural filter rather than a requirement. Best for trend-following traders who want ribbon-confirmed entries near key structure.
Sensitive
Level and volume spike only. No trend gate, no body filter. Produces more signals. Use when you want maximum opportunity detection and prefer to filter visually yourself.
Balanced
Trend, level, and volume. The middle ground between sensitivity and selectivity. Recommended starting point if you are new to the indicator.
Fvg entry
Balanced gates plus a requirement that price is inside an active fair value gap at signal time. This produces the tightest entries and smallest stop distances. Note: fair value gaps are not part of Livermore's original methodology. This preset is for modern traders who combine his structural philosophy with imbalance-based entry timing.
Custom
All engine gates become individual toggles. You build your own preset. Every toggle has a tooltip explaining its function and its relationship to Livermore's original method.
4. The silk ribbon
The ribbon consists of seven MA strands between your fast and slow periods, with gradient fills between them. The MA type applies to all strands simultaneously.
Available types: EMA, HMA, DEMA, TEMA, ZLEMA.
HMA is recommended for intraday scalping. EMA is more stable for swing setups. DEMA and TEMA reduce lag further but can be noisy on short timeframes. ZLEMA minimizes lag while maintaining smoothness.
The ribbon colors purely based on trend direction:
- Green when fast strand is above slow strand (bull)
- Red when fast strand is below slow strand (bear)
- Grey when flat
The color intensity and fill transparency are controlled by a single transparency slider. The fast strand width is separately configurable.
Cross signals (tiny circles) fire when the fast and slow strands cross. These are early warnings of potential trend change, not entry signals by themselves.
5. Htf levels
The indicator pulls pivot highs and lows from a higher timeframe of your choice using request.security. This means the levels you see on your 1m or 5m chart are actual structural levels from the 4h or daily chart — not redrawn approximations.
You can set a separate count for resistance levels and support levels. The nearest-only toggle reduces this to one resistance and one support — the most relevant levels on each side of price.
Each level has three visual states that match the waiting zone system described above. Scanning levels are dimmed. Watching levels turn gold. Confirmed breakout levels turn green or red.
An optional current timeframe overlay adds the pivots from your active chart at high transparency. This gives structural context without cluttering the main htf levels.
The failed breakout marker fires when price confirms a level, then returns through it within a configurable number of bars. This is the direct implementation of Livermore's rule: if the market moves back against you after a breakout, exit quickly with a small loss.
6. Volume engine
The volume engine has two components:
Spike detection: volume must exceed the configurable-period SMA multiplied by the spike multiplier. Default is 1.5x — meaning volume must be at least fifty percent above average to qualify.
Body conviction: the candle body must represent at least a configurable percentage of the total candle range. Default is 55%. This filters out doji candles and wick-heavy indecision candles from being counted as confirmed breakouts.
The volume halo appears on the chart for every spike bar. Its height scales with the volume ratio — a 3x spike produces a taller halo than a 1.5x spike. The halo color uses delta logic:
- Green for bull body with conviction (buying commitment)
- Red for bear body with conviction (selling commitment)
- Gold for high-volume doji or mixed candle (institutional activity, unclear direction)
The ratio text inside the halo shows the exact multiple (2.1x, 3.4x, etc.). Its opacity scales with strength — a weak spike shows faint text, a strong spike shows full text. This means glancing at the halo tells you both the direction and magnitude of institutional participation at that bar.
7. Htf ghost candles
The ghost candle engine projects the last N closed higher timeframe candles to the right of your chart, plus the current live (unfinished) htf candle. This gives you the htf price structure in candle form without switching timeframes.
The ghost candle timeframe is independent from the htf level timeframe. You can show 4H structural levels while projecting 1H ghost candles, or combine them however fits your workflow.
Closed candles are drawn left to right, oldest to newest. Each candle consists of a body box and a wick line. Bull candles are green, bear candles are red. No time labels appear on any candle — pure price structure only.
The live candle (the current unfinished htf bar) is drawn rightmost in a gold tint to distinguish it from closed candles. As the htf bar develops, this candle updates in real time.
Optional OHLC labels show the high, low, and close price to the right of each candle. The close label uses the candle direction color (green or red). High and low labels are grey.
Configurable settings:
- Ghost candle timeframe (independent from htf level TF)
- Number of closed candles to show (1-8)
- Right offset from last bar
- Candle width in bars
- Gap between candles
- OHLC labels on/off
- Bull, bear, wick, and live candle colors
8. Fair value gaps
Fair value gaps are three-bar imbalances where the middle candle leaves a gap between the high of the first candle and the low of the third candle (for bullish gaps) or the reverse. They represent areas where price moved too fast to fill orders on both sides.
In this indicator, fvgs are disabled by default in all presets except fvg entry. This is intentional — they are not part of Livermore's method and were not available to him. They are provided as an optional tool for traders who use modern imbalance concepts alongside structural analysis.
When enabled, fvgs show partial mitigation as price fills them progressively. Fully mitigated gaps are either removed or shown in a dimmed grey depending on your settings. The max visible fvg count prevents the chart from becoming cluttered on instruments with frequent gaps.
9. Htf reversal radar
The reversal radar monitors three configurable higher timeframes simultaneously for potential reversal conditions. A warning fires when two or more timeframes show:
- An EMA cross in the opposite direction to the current trend, or
- An RSI extreme exit (above 70 crossing back down, or below 30 crossing back up)
The warning appears as a small diamond plotshape and is reflected in the dashboard. It does not block signals — it is contextual information that something may be changing on higher timeframes while you are looking at a lower timeframe setup.
10. Rsi divergence
The divergence engine compares price pivot highs/lows to RSI pivot highs/lows. Bullish divergence fires when price makes a lower low but RSI makes a higher low. Bearish divergence fires when price makes a higher high but RSI makes a lower high.
Lines are drawn connecting the pivots that form the divergence. A small "div" text label appears at the endpoint. Line width and colors are separately configurable.
Divergence does not gate signals in any preset. It is contextual information — a potential warning that momentum is weakening even as price extends.
11. Signal quality filters
Three additional filters apply across all presets:
Cooldown: a minimum number of bars must pass between signals. This prevents multiple signals from firing on the same setup as it develops. Recommended: 10 bars as a starting point. Adjust based on your timeframe and how often valid setups appear. The dashboard shows either "ready" or the number of bars remaining.
Max ATR distance: if price is too far extended from the ribbon fast strand, the signal is blocked. This prevents entries on moves that are already largely done. Default is 3 ATR from the ribbon.
Pullback gate: an optional filter that requires price to return toward the ribbon after a breakout before confirming an entry. This is the cleanest implementation of Livermore's preferred entry timing — let the level break, let the market prove it wants to go, then enter on the retest rather than the initial breakout. Fewer signals, better risk to reward.
12. Trade block
The trade block appears only when a trade is active. It locks the moment a signal fires and does not move until the trade closes.
Components:
- Entry line with label showing price and direction
- Stop line (ATR, swing high/low, or hybrid of the two)
- Three take profit lines at configurable R multiples
- Risk zone box between entry and stop
- Reward boxes between entry and each TP
- Phase label above TP3 showing preset and direction
- R:R ratio and win rate displayed in the reward zone
TP lines dim when not yet reached and become fully saturated when hit. This gives you an immediate visual read of where you are in the trade without looking at the dashboard.
When the trade closes, a labeled exit appears at the exit candle:
- tp1, tp2, tp3 in green with dark text
- sl in red with dark text
- trail in gold with dark text
These labels remain on the chart after the trade closes so you can review the history.
Stop loss modes:
- ATR: stop at entry plus or minus ATR multiplied by a configurable value
- Swing: stop at the recent swing high or low
- Hybrid: the wider of the two — provides the most structure-aware placement
Trail stop activates after TP1 is hit. After TP1, the stop moves to breakeven. After TP2, the stop trails behind the ribbon fast strand with a configurable buffer.
13. Dashboard reference
The dashboard updates every bar at the latest bar. All values are live.
Htf — the timeframe driving the structural levels
Macro trend — ribbon direction (bull / bear)
Ribbon — active MA type
Active level — nearest htf pivot level to current price
Level state — scanning / watching / confirmed up / confirmed down
Volume ratio — current bar volume relative to the SMA (e.g. 1.8x avg or spike 2.3x)
Body ratio — current candle body as percentage of total range
Fvg active — count of active unmitigated bull and bear fvgs
Divergence — bull div or bear div if active, otherwise --
Htf radar — number of higher timeframes showing reversal conditions
Signal gate — active preset name
Last signal — most recent signal direction and whether trade is active
Tp progress — three dots showing current trade's TP hit status (o unlit, ^ hit)
Tp1 rate — percentage of total trades that reached TP1
Tp2 rate — percentage of total trades that reached TP2
Tp3 rate — percentage of total trades that reached TP3
Failed breakouts — cumulative count of failed breakout signals
Long win rate — TP1 hit rate on long signals only
Short win rate — TP1 hit rate on short signals only
Cooldown — bars remaining before next signal is allowed, or "ready"
14. Settings overview
Preset group
- Signal gate preset (7 options)
- Custom gate toggles (active only in custom preset)
- Signal cooldown on/off and bar count
- Pullback gate on/off and window
- Max ATR distance on/off and multiplier
Silk ribbon group
- Show ribbon on/off
- MA type
- Fast and slow periods
- Ribbon transparency slider
- Fast strand width
- Show cross signals on/off
- Bull and bear cross colors
Htf levels group
- Htf timeframe
- Pivot length
- Max resistance levels shown (1-8)
- Max support levels shown (1-8)
- Nearest only toggle
- Level line width
- Resistance, support, watching, and confirmed colors
- Show current TF levels on/off
- Current TF pivot length
- Watching zone ATR distance
- Failed breakout lookback bars
Volume engine group
- Show volume halo on/off
- Volume SMA length
- Spike multiplier
- Min body ratio
- Halo height ATR multiplier
Htf ghost candles group
- Show ghost candles on/off
- Ghost candle timeframe
- Number of candles to show
- Right offset, width, and gap between candles
- Show OHLC labels on/off
- Bull, bear, wick, and live candle colors
Fvg group
- Show fvgs on/off (off by default except in fvg entry preset)
- Max visible fvg count
- Min gap size in ATR
- Extend to right on/off
- Keep mitigated gaps on/off
- Bull, bear, and mitigated colors
Htf reversal radar group
- Enable radar on/off
- Three radar timeframes
Divergence group
- Show divergence on/off
- Pivot left and right lookback
- Max bars between pivots
- Show divergence lines on/off
- Line width
- Bull and bear divergence colors
Trade block group
- Show trade block on/off
- Show exit labels on/off
- Exit label colors (TP, SL, trail)
- SL source (ATR, swing, hybrid)
- ATR stop multiplier
- Swing lookback
- TP1, TP2, TP3 R multiples
- Trail stop on/off
- Trail buffer ATR multiplier
- Project bars (width of the trade block)
Dashboard group
- Show dashboard on/off
- Position (four corners)
- Size (tiny, small, normal)
15. How to use — beginners
If you are new to technical analysis and confluence-based trading, start here.
Step 1: add the indicator and set the preset to "balanced."
Step 2: set your htf timeframe to something higher than the chart you are watching. If you are on a 5m chart, use 1H. If you are on a 15m chart, use 4H.
Step 3: watch the dashboard. When level state changes from "scanning" to "watching," that means price is approaching a key level. This is your cue to pay close attention.
Step 4: wait. Do not act on "watching." Wait for volume to confirm. Wait for the ribbon to be aligned. Wait for the body ratio to show a conviction candle. When the level state changes to "confirmed," that is when the indicator agrees a signal may be valid.
Step 5: if a triangle signal appears below or above a candle, that means all preset gates passed simultaneously. The trade block will lock your entry, stop, and targets automatically.
Step 6: manage the trade with the trade block. Watch the TP progress dots in the dashboard. When dots light up, TPs are being hit.
Step 7: after the trade closes, look at the exit label on the chart. This tells you how the trade resolved — tp1, tp2, tp3, sl, or trail.
Step 8: over time, watch the dashboard metrics. TP1 rate above 60% on your chosen preset and timeframe is a solid foundation. If it is below 50%, try adjusting the cooldown, the volume multiplier, or the htf level pivot length.
16. How to use — experienced traders
For traders who understand confluence and want to customize the indicator for their own methodology:
The custom preset gives you individual control over every gate. Use this if you have a specific condition combination that the named presets do not cover.
The pullback gate is the highest-value optional filter in the indicator. Enable it if you find that your signals are entering too early on breakout candles and getting caught in the initial wick. It waits for price to retrace toward the ribbon before confirming entry.
The ribbon period settings matter significantly on lower timeframes. For 1m and 5m, test HMA 8/21. For 15m, HMA 13/34 or EMA 21/55. For 1H and above, EMA 21/89 gives cleaner swing context without too much noise.
The volume spike multiplier should be adjusted by instrument. Crypto and oil tend to have more frequent spikes than equity index futures. Start at 1.5x and move up to 2.0x if you are getting too many false spikes.
The failed breakout lookback (default 3 bars) can be extended to 5-8 bars on higher timeframes where reactions take longer to develop.
For multi-timeframe setups, use the htf reversal radar with timeframes one step above your normal analysis chain. If you trade on 15m, set the radar to 1H, 4H, and daily. A warning on two or more of those while a signal fires on your 15m is meaningful context.
17. Performance notes from testing
The Livermore preset on 15m across multiple instruments (MNQ, BTC futures, micro gold, crude oil) showed the following general ranges across several hundred signals. These are not guarantees and will vary by instrument and market conditions.
TP1 rate: 66-75% depending on instrument
TP2 rate: 27-45%
TP3 rate: 14-25%
Long win rate (TP1 as measure): 68-80%
Short win rate (TP1 as measure): 55-70%
The gap between long and short rates reflects the natural long bias of most risk assets over time. Instruments with persistent directional trends tend to show higher rates in the direction of that trend.
A 10-bar cooldown showed better results than 5 bars or 50 bars in testing. At 5 bars, too many signals clustered around the same level. At 50 bars, valid retests were missed entirely. At 10 bars, the indicator captures the initial breakout and the first meaningful retest while filtering pure noise.
These numbers should be treated as starting points for your own testing, not as targets to optimize around. Your instrument, timeframe, and current market regime will all affect them.
18. Alerts
The indicator includes eight alert conditions accessible through TradingView's alert system:
- Long signal confirmed
- Short signal confirmed
- Failed breakout detected
- Htf bear reversal warning (2+ timeframes)
- Htf bull reversal warning (2+ timeframes)
- Bull divergence detected
- Bear divergence detected
- Level watching (price approaching key htf level)
Set the alert on "once per bar close" for the cleanest signals without repainting on the current bar.
19. Compatibility
Works on all instruments: equities, ETFs, crypto, forex, futures, indices, commodities.
Works on all timeframes from 1m to monthly.
No hardcoded tick sizes, contract specifications, or session times.
No repainting on closed bars. The current bar may repaint as it develops, which is expected behavior for any indicator.
Pine Script v6. Requires TradingView Essential plan or above for the best performance due to the multiple request.security calls used for htf levels.
20. What this indicator does not do
- Does not connect to any broker
- Does not place trades automatically
- Does not guarantee any level of profitability
- Does not predict future price movement
- Does not work without price data — it needs bars to calculate
- Does not replace your own market analysis and judgment
The indicator provides structured visual context and a confirmation framework. The decision to enter, manage, and exit a trade remains entirely yours.
21. Disclaimer
This indicator is provided for educational and informational purposes only. Nothing in this document constitutes financial advice or any form of recommendation to buy or sell any financial instrument.
All trading decisions are made entirely by the user. Trading financial instruments involves substantial risk of loss. Past indicator performance on historical data is not indicative of future results. You may lose all of your invested capital.
Anonycryptous accepts no responsibility or liability for any trading losses incurred as a result of using this indicator.
Indicateur

Artemis Adaptive RSI🟦 Artemis Adaptive RSI is a Pine v6 self-tuning RSI workbench. Instead of shipping with a fixed period and fixed thresholds — and forcing the trader to babysit the inputs across regimes (14 / 70 / 30 on stocks, 7 / 80 / 20 on crypto, 21 / 60 / 40 in trends) — a 60-candidate optimisation grid scores Supersmoother-filtered RSI variants against their own forward-return performance on a rolling window, then picks the variant whose threshold trips deliver the cleanest mean-reversion edge on the current market. The active period, smoothing, and OB / OS thresholds update online, and a five-state regime label tells you why the optimiser chose what it chose.
The indicator integrates seven analytical layers — Supersmoother-filtered RSI core, online candidate optimiser, hysteresis-locked regime classifier, Stochastic-Extreme-style multi-band zone visual, pivot-based Regular + Hidden divergence detection with a Smart AI Filter, adaptive trigger markers, theme-adaptive bar painter, and a PRO 8-row dashboard — each operating independently and rendered on a single, clean oscillator panel.
🟦 CREDITS & ATTRIBUTION
The adaptive optimisation CORE — Supersmoother-filtered RSI fleet, rolling-window incremental scorer, champion selection with hysteresis, and the five-state regime classifier — is derived from the open-source work of **GoodBadBitcoin** and published under the same MPL-2.0 license. Full respect to the original author for the design and the open release; this project would not exist without that groundwork.
- Source script — [Adaptive Modern RSI ]()
- Original author — (www.tradingview.com)
Everything else — the Stochastic-Extreme-style multi-band zone UI, the twelve-theme palette system, the pivot-based divergence engine, the Smart AI Filter, the PRO dashboard, the hover-tooltipped regime badge, the theme-aware bar painter, and the curated nine-channel alert pack — is original work added on top.
🟦 HOW THE CORE ENGINE WORKS
**Supersmoother**
Each bar, the per-bar close change is split into two streams — positive (gains) and negative (losses) — and each stream is fed through an Ehlers two-pole Butterworth low-pass filter. The Supersmoother removes high-frequency noise without piling on the phase lag that naive EMA / RMA pre-smoothing chains accumulate. The filtered gain / loss streams then feed the classical Wilder RSI ratio:
rsi = 100 − 100 / (1 + smoothedGains / smoothedLosses)
**Candidate Fleet**
15 RSI variants are precomputed in parallel — every combination of:
| Axis | Values |
|---|---|
| RSI length | 7 / 10 / 14 / 21 / 28 |
| Supersmoother smoothing | 6 / 10 / 16 |
Combined with 4 threshold tiers (15-85 / 20-80 / 25-75 / 30-70), this gives the 60-slot fleet the optimiser grades against.
**Online Optimiser (Rolling-Edge Scorer)**
Every bar, each of the 60 slots is evaluated:
1. **Trigger detection** — for the slot's threshold pair, did the bar produce an OS-entry (RSI crossed down through OS) or an OB-exit (RSI crossed back down through OB)?
2. **Forward-return scoring** — if a trigger fired, score it by `close / close − 1` (signed by trigger direction).
3. **Rolling bookkeeping** — each slot maintains its own running mean over a sliding `scoreWindow`-bar window. Returns enter on add, exit on subtract, mean recomputed in O(1) per slot per bar — no rescans, no naive sum-of-products drift.
After every bar's update, the slot with the highest mean return wins — subject to two gates:
- **Min Triggers per Candidate** — under-sampled slots are disqualified
- **Switch Margin (%)** — a new champion must beat the current incumbent by this hysteresis margin before it actually takes over
This protects against bar-by-bar leadership flapping when two candidates trade marginal scores.
**Regime Classifier**
The crowned champion's shape (length-index, smoothing-index, level-index, mean-return) is read each bar and the market is tagged as one of five phases:
| Glyph | Phase | Meaning |
|---|---|---|
| ◐ | Adapting | Cold start — optimiser not yet armed (default RSI in use) |
| ✸ | Noisy | Score collapsed, no exploitable edge — sit out |
| ➜ | Trending | Long period + relaxed thresholds — trend dominates, avoid OB/OS reversals |
| ▣ | Range | Short period + strict thresholds — RSI's sweet spot, triggers reliable |
| ⊠ | Calm | Middling parameters — mild swings, use as light confluence |
The raw tag stream is then locked through a two-stage hysteresis machine: the displayed phase only updates after the underlying classification holds for `Regime Confirmation Bars` in a row. This keeps the floating badge from twitching on every minor optimiser jitter.
🟦 MULTI-BAND ZONE UI
A Stochastic-Extreme-style six-band visual at 100 / 80 / 70 / 50 / 30 / 20 / 0. The active OB / OS thresholds overlay as steplines that move as the optimiser updates. Zone fills key off the *adaptive* thresholds so the visual escalation tracks the actual signal logic, not a fixed 70 / 30 line.
The fills are tiered — when the RSI line plus the live champion's mean-return both confirm a zone state, the fill intensifies; otherwise the band shows a lighter tint. The 40 / 60 reference dotted lines and the 50 zero line are decorative — they are NOT the triggers.
**RSI line colour**
| Zone | Colour |
|---|---|
| Above 60 | theme-bull (price-strength bias) |
| Between 40 and 60 | neutral |
| Below 40 | theme-bear (price-weakness bias) |
These 40 / 60 bands are FIXED — they are NOT the adaptive OS / OB. The adaptive thresholds drive the triggers; the 40 / 60 bands just colour the RSI line for at-a-glance bias reading.
🟦 TRIGGER MARKERS
Triangle markers fire at the bar of OS entry / OB exit on the *adaptive* thresholds — the events the optimiser is actually scoring:
- ▲ **OS Entry Trigger** — RSI just crossed down through the adaptive OS threshold (mean-reversion long opportunity)
- ▼ **OB Exit Trigger** — RSI just crossed back down through the adaptive OB threshold from above (rejection / short opportunity)
Markers use `location.absolute` with fixed Y coordinates (10 / 90) so they stay glued to the same visual spot every bar — no drift between candles, no shift when zone fills update. Each visible triangle is paired with an invisible `label.style_circle` carrying a hover tooltip with live RSI value, active threshold, active period, and active smoothing — `plotshape()` does not support tooltips natively, so the dual-track rendering is required for hover content.
🟦 DIVERGENCE DETECTION
Pivot-based detection for the four classical divergence flavours:
| Type | Price | RSI | Signal |
|---|---|---|---|
| Regular Bull (D▲) | Lower Low | Higher Low | Potential reversal up |
| Regular Bear (D▼) | Higher High | Lower High | Potential reversal down |
| Hidden Bull (H▲) | Higher Low | Lower Low | Uptrend continuation |
| Hidden Bear (H▼) | Lower High | Higher High | Downtrend continuation |
Pivots are sampled on raw price (high / low) using `Pivot Arm` bars on each side (symmetric). Each pivot bar's RSI value is read **dynamically from the current active RSI series** via bar-index lookup — so when the optimiser switches champions between pivots, the comparison stays internally consistent (both endpoints come from the SAME series). This is a subtle but critical fix vs. naive divergence ports.
Regular Divergence labels (D▲ / D▼) use bracketed glyphs with solid styling — these are the reversal signals.
Hidden Divergence labels (H▲ / H▼) use the same bracket scheme — these are the continuation signals.
Each label hovers a tooltip with the price change, RSI change, and the pivot bar distance.
**Smart AI Filter**
An optional pre-filter that rejects low-quality divergences before they render. Three independent gates:
1. **Min RSI Swing** — minimum RSI difference between the two pivots (default: 5 points). Drops noise-level differences where RSI barely moved between pivots.
2. **Min Price Swing (%)** — minimum price swing between pivots as a percentage of the recent (80 bars) price range (default: 0.3%). Drops divergences where price barely moved relative to recent volatility.
3. **Zone Confirmation** — RSI at the current pivot must sit in the matching adaptive reversion half:
- Bullish divergence → RSI ≤ midpoint(liveOs, 50) (moderate-to-deep oversold)
- Bearish divergence → RSI ≥ midpoint(50, liveOb) (moderate-to-deep overbought)
The zone gate is adaptive — it tightens or loosens as the optimiser updates the live OS / OB thresholds. This encodes the classical "best divergences form at extremes" rule using the live adaptive thresholds, not a fixed 30 / 70.
When the master toggle is OFF (default), all detected divergences render. When ON, only divergences that clear all three gates survive. The filter applies identically to both chart rendering and alert conditions — no mismatch between visual and alert signals.
🟦 REGIME BADGE
A floating label pinned to the LATEST bar, extending rightward into the chart's right-margin / future area. The `label.style_label_left` style places the arrow tip on the LEFT of the box so it visually "points back" to the active RSI data without overlapping the oscillator line.
The badge shows:
- **Glyph + phase name** (e.g. `▣ Range`)
- **Bars stable** (how long the current phase has held)
- **Action note** (e.g. "RSI's sweet spot — triggers work well")
The background colour pulls from the theme palette — Range = theme-bull tint, Trending = theme-bear tint, Adapting / Noisy = theme-neutral tint, Calm = theme-signal tint — so the badge meaning is reinforced by the palette consistency.
**Hover tooltip**
Hovering the badge surfaces a comprehensive phase legend explaining all five glyphs, what each means, what action to take in each, and how to read the "bars stable" counter.
**Position**
User-selectable: Top (y = 80, upper third), Middle (y = 50, centre, default), Bottom (y = 20, lower third). The Y resolver maps the dropdown onto fixed pane-fraction coordinates so the badge stays parked at the same visual spot regardless of RSI value.
🟦 BAR COLORING
Two mutually exclusive modes apply a state-driven colour to every price bar on the chart:
| Mode | Behavior |
|---|---|
| None | Leave bars untouched (default) |
| RSI Zone | Theme-bear when RSI in OB zone, theme-bull when in OS zone, theme-neutral otherwise |
Uses the *adaptive* OB / OS thresholds, not fixed 30 / 70. The bar painter pulls directly from the active threshold state — when the optimiser switches candidates, the bar colour rule updates accordingly with no lag.
🟦 DASHBOARD
A compact 2-column, 8-row PRO data panel renders on the last bar when enabled. Every value derives from variables already computed upstream, so the dashboard adds zero overhead until the final bar.
| Row | Left | Right |
|---|---|---|
| Header | Artemis A-RSI | ▲ OB / ▼ OS / ■ Neutral (current bias) |
| Phase | Phase | ◐ ✸ ➜ ▣ ⊠ glyph + name (current regime) |
| Period | Period | Active RSI length (e.g. 14) |
| Smooth | Smooth | Active Supersmoother smoothing (e.g. 10) |
| OS Level | OS | Active adaptive OS threshold (e.g. 20) |
| OB Level | OB | Active adaptive OB threshold (e.g. 80) |
| Score | Score | Champion's mean forward return (in %) |
| Last Div | Last Div | Most recent divergence within last 50 bars (D▲ / D▼ / H▲ / H▼ / —) |
**Theme-Adaptive Chrome**
The dashboard auto-inverts its layout based on the active theme:
- **Dark themes** (Tropic, Amber, Pastel, Cyber, Helios, Electric, Candy, Bloomberg, Solar, Royal): header and footer use a faint `thBull` tint, middle rows stay solid dark, text uses full-saturation `thBull`. Border uses `thBull` at 20% transparency for strong theme presence.
- **Light themes** (Midnight, Graphite): backgrounds flip to white, text stays `thBull` (which is itself dark on these themes), border uses `thBull` at 40% transparency.
This guarantees text legibility against every palette without per-theme manual tuning.
**Position & Size**
Six anchor slots (Top / Middle / Bottom × Left / Right) and four text sizes (Tiny / Small / Normal / Large).
🟦 COLOR THEMES
Twelve cohesive palettes, each resolving to four axis colors. The whole script reads through these four variables — nothing below the theme resolver references a raw hex literal, so a single dropdown selection drives every plot, fill, stepline, divergence line, dashboard cell and badge.
| Theme | Character | Bull | Bear |
|---|---|---|---|
| Tropic | Cyan steel + deep orange | #00bcd4 | #ff6d00 |
| Amber | Warm amber + indigo blue | #ff9800 | #e53935 |
| Pastel | Sky blue + soft lavender | #4fc3f7 | #9575cd |
| Cyber | Neon lime + hot crimson | #00e676 | #ff1744 |
| Helios | Bright gold + scarlet | #ffd600 | #ef5350 |
| Electric | Electric aqua + magenta | #00e5ff | #e040fb |
| Candy | Neon green + hot pink | #69F0AE | #FF4081 |
| Bloomberg | Terminal orange + cyan | #ff8c00 | #00b0ff |
| Solar | Solarized olive + crimson | #859900 | #dc322f |
| Royal | Imperial gold + deep purple | #ffd700 | #6a0dad |
| Midnight | Deep navy + dark crimson | #0d47a1 | #b71c1c |
| Graphite | Near-black + silver grey | #1a1a1a | #757575 |
🟦 ALERT SYSTEM
Seven user toggles drive nine alert messages, all using `alert.freq_once_per_bar_close`:
| Toggle | Alert(s) | Condition |
|---|---|---|
| OS Entry Trigger | OS Entry | RSI crossed down through adaptive OS |
| OB Exit Trigger | OB Exit | RSI crossed back down through adaptive OB |
| Regime Change | Phase Flip | Locked regime label updates (post-hysteresis) |
| Regular Divergence | D▲ + D▼ | Reversal divergences detected (respects Smart AI Filter) |
| Hidden Divergence | H▲ + H▼ | Continuation divergences detected (respects Smart AI Filter) |
| RSI Mid Cross Up | Mid ↑ | RSI crossed above 50 |
| RSI Mid Cross Down | Mid ↓ | RSI crossed below 50 |
Each alert fires through `alert()` so the message body carries live context — current RSI value, the active adaptive threshold that triggered, active period and smoothing, and (for Regime Change) the previous phase's hold duration. Divergence alerts respect the Smart AI Filter — if the filter is ON and a divergence is rejected visually, the alert will also not fire.
🟦 SETTINGS REFERENCE
**Visual**
- Theme — 12 palette options. Default: Tropic
**Adaptation Core**
- Optimization Lookback (bars) — 100–1000. Default: 300
- Forward-Return Eval Horizon — 2–20. Default: 5
- Min Triggers per Candidate — ≥ 2. Default: 5
- Switch Margin (%) — 0–50, step 2.5. Default: 10
**Regime Label**
- Show Regime Label — Toggle. Default: ON
- Regime Label Size — Tiny / Small / Normal / Large / Huge. Default: Normal
- Regime Confirmation Bars — 1–100. Default: 10
- Regime Label Position — Top / Middle / Bottom. Default: Middle
**Zones & Levels**
- Show Adaptive Levels — Toggle. Default: ON
- Show Zone Fills — Toggle. Default: ON
- Show Trigger Signals — Toggle. Default: ON
**Divergence**
- Regular Divergence — Toggle. Default: ON
- Regular Opacity — 0–100. Default: 80
- Hidden Divergence — Toggle. Default: ON
- Hidden Opacity — 0–100. Default: 80
- Pivot Arm — 2–50. Default: 5
- Label Size — Tiny / Small / Normal / Large. Default: Tiny
- Smart AI Filter — Master toggle. Default: OFF
- Min RSI Swing — 1.0–50.0. Default: 5.0
- Min Price Swing (%) — 0.1–5.0. Default: 0.3
- Require Zone Confirmation — Toggle. Default: ON
**Bar Coloring**
- Bar Color Mode — None / RSI Zone. Default: None
**Dashboard**
- Show Dashboard — Toggle. Default: ON
- Panel Position — 6 anchor slots. Default: Middle Right
- Panel Text Size — Tiny / Small / Normal / Large. Default: Small
**Alerts**
- OS Entry Trigger — Default: ON
- OB Exit Trigger — Default: ON
- Regime Change — Default: ON
- Regular Divergence — Default: ON
- Hidden Divergence — Default: OFF
- RSI Mid Cross Up — Default: OFF
- RSI Mid Cross Down — Default: OFF
🟦 COMPATIBILITY
Works on all asset classes and all timeframes in TradingView Pine Script v6.
- Crypto: Spot, futures, perpetual contracts
- Forex: All pairs
- Equities: Stocks, ETFs, indices
- Commodities: Metals, energy, agriculture
- Timeframes: 1m through Monthly
Because the engine self-tunes its RSI period, smoothing, and OB / OS thresholds online, the same default settings work on a 5-second BTC chart and a weekly index chart without retuning. The optimiser sees the asset's actual reversion behaviour and adapts — no per-asset preset library needed.
🟦 TECHNICAL NOTES
- Pine Script v6
- `max_lines_count = 500`, `max_labels_count = 500`, `max_bars_back = 1000`
- No repainting — all values calculated on bar close. Pivot-based divergence results appear `Pivot Arm` bars late by design (standard Pine pivot confirmation behaviour)
- The adaptive RSI line is internally consistent across optimiser switches — divergence pivots read RSI dynamically via `activeRsi `, so both endpoints come from the SAME (current) RSI series even when the champion changes between pivots
- The Supersmoother filter relies on `var float lpY = 0.0` private state per call-site — Pine v6 issues one independent state slot per call-site, so the 15 fleet entries below produce 30 (15 × 2 streams) independent filter histories with zero cross-talk
- Champion switch is hysteresis-gated by `Switch Margin (%)` and an eligibility floor (`Min Triggers per Candidate`) — protects against bar-by-bar flapping when two candidates trade marginal scores
- Regime tag is doubly hysteresis-gated — first the candidate must hold, then the displayed phase only flips after `Regime Confirmation Bars` of stable tagging
- Trigger markers use `location.absolute` with fixed Y coordinates (10 / 90) for visual stability — no slide on zoom or candle-spacing changes
- Trigger marker tooltips piggy-back on invisible `label.style_circle` parallel renders — `plotshape()` does not natively support the `tooltip` argument
🟦 DISCLAIMER
This indicator is provided for educational and informational purposes only. It does not constitute financial advice. Past performance does not guarantee future results. Always conduct your own analysis and apply proper risk management. Indicateur

TRIX Chart DivergenceTRIX Chart Divergence is based on one of my favorite oscillators.
The main feature of this indicator is that TRIX divergences are drawn not only in the oscillator pane, but also directly on the price chart.
This makes divergence much easier to read, especially for intraday trading and scalping. Instead of looking back and forth between price and the oscillator, you can immediately see where price made a new high or low and where TRIX failed to confirm that move.
For me, this is the most useful way to work with TRIX.
A bullish divergence appears when price makes a lower low, but TRIX does not confirm that move and forms a higher low. A bearish divergence appears when price makes a higher high, but TRIX does not confirm it and forms a lower high.
This type of divergence can warn about a possible correction or trend reversal. I especially like watching TRIX divergences on higher timeframes, because they can mark important exhaustion points. The indicator includes alerts for bullish and bearish divergences, so you can monitor multiple instruments and timeframes without watching every chart all the time.
I also use TRIX on the 1-minute gold chart for intraday trading. On lower timeframes, I use it together with my own setups, price action, levels and other confirmation tools.
TRIX is simple and clean. When the TRIX line crosses the signal line in the lower area, it can show a possible bullish momentum shift. When the cross appears in the upper area, it can show a possible bearish momentum shift. In this indicator, bullish and bearish TRIX crosses are marked with small green and red dots.
TRIX does not have fixed overbought and oversold levels like RSI or Stochastic. That is why I added adaptive range levels. These levels show where TRIX is trading compared to its recent range. When TRIX moves outside this adaptive range, it can highlight stronger momentum extremes.
The adaptive range levels are optional. You can use the indicator in the classic way without them, or keep them on as an additional visual guide.
Main features:
- TRIX and signal line
- Histogram
- Small green and red dots on TRIX crossovers
- Bullish and bearish TRIX divergences
- Divergence lines in the oscillator pane
- Optional divergence lines directly on the price chart
- Optional adaptive TRIX range levels
- Alerts for TRIX crosses and divergences
Settings:
TRIX Length / Signal Length
Controls the basic TRIX calculation and signal line. Lower values make the oscillator more sensitive. Higher values make it smoother.
Adaptive Range Levels
Optional dynamic levels that show where TRIX is trading compared to its recent range. They can help identify stronger momentum extremes. You can turn them off if you prefer the classic TRIX view.
Range Lookback Bars
Defines how many previous bars are used to calculate the adaptive range. A larger value makes the range smoother and more stable. A smaller value makes it react faster.
Range Smoothing
Smooths the adaptive range levels.
TRIX Pivot Sensitivity
Controls how sensitive divergence detection is. Lower values find more divergences. Higher values show fewer but cleaner divergences.
Price Search Radius
Allows the script to search around the TRIX pivot and find the closest price high or low for drawing the divergence line.
Max Bars Between Points
Defines the maximum distance between two TRIX pivot points used for divergence detection.
Draw divergence line on TRIX
Shows the divergence line in the oscillator pane.
Draw divergence line on price chart
Shows the same divergence directly on the price chart.
Important:
This indicator is not a standalone trading system.
TRIX crosses and divergences are designed to help identify momentum shifts, exhaustion points and possible correction zones.
For best results, use it together with price action, support and resistance, trend structure, higher timeframe context and your own confirmation setup.
A divergence can warn about a possible correction or reversal, but it does not mean that price must reverse immediately. Indicateur

Kinetic Momentum Vectors [BigBeluga]Kinetic Momentum Vectors is a high-performance analytical framework that reimagines price action as a physical system. By calculating the "mass" (volume) and "velocity" (rate of change), the script identifies the Kinetic Energy driving a trend. Instead of traditional lagging oscillators, this tool projects momentum as external "propulsion vectors" anchored to a trend baseline, allowing you to see exactly when a move is fueled by institutional conviction or retail exhaustion.
🔵 THE PHYSICS OF MOMENTUM
Energy Normalization (0-1 Engine): The indicator processes volume-weighted price movement through a Min-Max normalization scaler. This isolates the most explosive "Kinetic Spikes" within your chosen lookback period, ensuring you only react to the most significant institutional surges.
Propulsion Fuel Candles: Momentum is visually detached from price and plotted as "fuel candles" relative to a central EMA. Bullish energy accelerates downward from the baseline, while bearish energy expands upward, creating a "momentum vacuum" that reveals the true strength of a trend's engine.
Kinetic Spike Anchors: When normalization hits the "Spike Threshold," the script locks in a structural vector. These are the exact price levels where maximum work was performed by the market, serving as high-probability pivots for future support and resistance.
🔵 STRUCTURAL INTELLIGENCE
Refining Vector Levels: Unlike static lines, these levels feature a 3-bar confirmation window . The script dynamically updates the vector to the absolute high or low of the momentum event, ensuring your structural anchors are pixel-perfect.
Adaptive Level States: Vectors transition from solid to dashed the moment they are breached. This "Style-Override" logic provides an instant visual alert that a momentum barrier has failed and a potential "S/R Flip" is in progress.
Auto-Scaling ATR Visuals: The vertical height of the momentum candles is governed by current volatility (ATR). This ensures that the visual data remains legible and proportional, whether you are trading a low-volatility Asian session or a high-volatility New York open.
🔵 CORE UTILITY
Identifying "Empty" Trends: A healthy trend requires increasing Kinetic Fuel. If price continues to climb while the fuel candles shrink back toward the baseline, you are looking at a "low-kinetic" divergence—a primary warning sign of a trend reversal.
Institutional S/R Mapping: Use the Kinetic Spike labels as "hard" targets. Because these levels are generated by high-volume price displacement, they represent areas where big players have already shown their hand.
Momentum Breakout Confirmation: Enter trades when a price breakout is accompanied by a full-sized kinetic vector. If the fuel candles remain small during a breakout, it lacks the "mass" required to sustain the move.
The Baseline Magnet: The trend baseline acts as the gravitational center. When price overextends and kinetic energy hits a 1.0 spike, look for a mean-reversion move back toward the EMA baseline.
Kinetic Momentum Vectors strips away the noise of standard technical analysis to reveal the raw energy moving the market. By monitoring the fuel behind the price, you can trade with the flow of institutional kinetic energy and avoid the traps of exhausted trends. Indicateur

Tension Flow Trend [BigBeluga] - Historical RRTension Flow Trend is a high-performance trend-following framework that treats price action like a reactive elastic system. By moving beyond static averages, this indicator introduces "Price Tension"—a sophisticated measurement of how overstretched a trend is relative to its baseline—now enhanced with a live Historical RR (Risk:Reward) backtesting engine.
By combining the ultra-low-lag properties of the Hull Moving Average (HMA) with real-time Z-Score volatility analysis, this indicator visualizes not just the direction of the market, but the mathematical "exhaustion" of every move.
🔵 THE ELASTICITY FRAMEWORK
The Ultra-Responsive HMA Baseline: At the heart of the system is a 50-period Hull Moving Average. Specifically engineered to eliminate the lag found in traditional SMAs, the HMA provides a "true north" that reacts instantly to structural shifts without the usual delay.
Price Tension (Z-Score Engine): The indicator measures the vertical distance between price and the HMA, normalizing it using standard deviation. This Z-Score represents the "Tension" of the trend—showing you exactly when the market has deviated too far from its mean.
Dynamic Transparency Feedback: As price enters an extreme Z-Score range, the trend ribbon’s transparency increases. A bright, solid ribbon indicates compressed, high-probability energy, while a fading ribbon warns that the "elastic band" is stretched to its limit.
🔵 PERFORMANCE & RISK INTELLIGENCE
Automated RR Projection: Upon every "START" signal, the script automatically plots dynamic Risk:Reward boxes. It calculates an ATR-based stop loss and projects a take-profit target based on your custom RR ratio, visualizing the trade's path in real-time.
Rolling Performance Tracker: The indicator features a built-in backtester that tracks the win/loss history of the most recent trades. It calculates your Win Rate based on a rolling sample size, allowing you to see how the strategy is performing under current market conditions.
Signal Cooldown Logic: To eliminate "whipsaw" noise, a configurable cooldown engine ensures that signals only trigger during significant structural shifts. This prevents signal clustering in sideways or choppy markets.
🔵 DUAL-DASHBOARD SYSTEM
Energy Monitor (Bottom-Right): Tracks the numerical Z-Score and categorizes the market status. "Strong" indicates healthy momentum, while "Overextended" warns of an imminent mean-reversion risk.
RR Performance Table (Top-Right): Provides an institutional-grade breakdown of your strategy performance, including total Wins, Losses, and the current Win Rate percentage for the specified trade window.
🔵 STRATEGIC APPLICATION
The Momentum Breakout: Look for "START" labels that appear when the HMA slope aligns with a price crossover. These represent the birth of a new trend cycle where tension is low and expansion is likely.
Managing Trend Exhaustion: When the ribbon begins to fade and the Energy Dashboard hits "Overextended," it is time to tighten stops or take partial profits. High tension usually precedes a sharp snap-back to the baseline.
Confirming with Win Rate: Use the Performance Dashboard to gauge market regime. If the rolling Win Rate is high, the market is respecting the trend envelopes; if it drops, the market may be entering a consolidation phase where you should wait for better alignment.
Mean Reversion Targets: For contrarian traders, the HMA baseline serves as a natural "magnet." When price is significantly overextended, look for price to be pulled back into the HMA "Neutral Zone."
Tension Flow Trend transforms your chart into a map of market stress and opportunity. By visualizing the tension behind every candle and providing real-time performance feedback, it ensures you stay on the right side of the trend while trading with professional-grade risk management. Indicateur

Indicateur

Liquidity-Anchored Trailing Stop [BigBeluga]Liquidity-Anchored Trailing Stop is a comprehensive volatility and structural framework designed to provide a protective "heatmap" around price action. By fusing multi-layered ATR-based trailing logic with a dynamic Volume Profile, this indicator identifies where market momentum is accelerating and where institutional liquidity is "anchored."
Instead of a single line, this tool provides a graded risk-mitigation zone that adapts to market noise, ensuring you remain in the trend during healthy pullbacks while identifying the exact structural peaks where volume was most concentrated.
🔵 THE DUAL-ENGINE FRAMEWORK
Volatility Heatmap (Trailing Stop): The indicator calculates four distinct levels of trailing protection (Stop 1 through Stop 4). These are anchored to the trend’s direction and volatility, creating a "safety buffer" that narrows or expands based on the Average True Range (ATR).
Trend-Relative Volume Profile (Right Side): Unlike static volume profiles, this engine focuses specifically on the current trend segment. It visualizes the total relative volume transacted at each price bin since the last trend flip, highlighting where the real "meat" of the move occurred.
High Volume Nodes (HVNs): The script automatically detects peaks in the volume distribution. These High Volume Nodes represent structural anchors where the market has spent significant time, serving as high-probability zones for support or resistance.
🔵 CORE ARCHITECTURE
Liquidity Anchoring: By plotting HVN levels (Structural Peaks), the indicator shows you exactly where liquidity is sitting. When a trailing stop aligns with a volume peak, it creates a "Hard Anchor"—a level that is significantly harder for price to break through.
Adaptive Stop Logic: The trailing stops (ts1-ts4) use a ratchet mechanism. In an uptrend, the stops only move up; in a downtrend, they only move down. This prevents the "stop-loss creep" that often leads to giving back profits.
Dynamic Gradient Heatmap: The space between the four trailing bands is filled with a color-coded gradient. Saturated colors represent the core trend, while the outer bands represent the "exhaustion zone" where the trend is at risk of structural failure.
🔵 FEATURES
Granular Profile Rows: Fully adjustable vertical resolution (Profile Rows) allows you to define how detailed you want the volume distribution to be, ranging from broad structural areas to precise price levels.
Peak Level Detection: Horizontal structural lines are automatically drawn across the trend range at major HVNs, providing immediate visual targets and pivot points.
Smart Trend Labels: Clean UI labels (Bull/Bear) mark the exact bar where the trend flips and the volatility bands reset, ensuring you never miss a shift in market regime.
Visual Clarity Toggle: Includes options to show or hide the Volume Profile and Peak Levels, allowing you to use the tool as a pure volatility stop or a full-scale market structure map.
🔵 STRATEGIC APPLICATION
Trailing with the Heatmap: Use the innermost band (Stop 1) for aggressive scalping or tight management, and the outermost band (Stop 4) for macro trend following. If price closes beyond Stop 4, the trend is officially considered "broken."
HVN Confluence: Look for instances where the Trailing Stop aligns with a High Volume Node. These "Anchored Stops" are the most robust areas to place your actual exchange orders, as they are backed by both volatility and historical volume.
Volatility Breakouts: When the ATR bands (Heatmap) contract significantly and then price breaks out, look to the Volume Profile to see if the breakout is supported by a surge in volume at the new price bins.
Targeting Structural Peaks: In a trending market, use the volume peaks on the right side of the chart as natural take-profit targets or areas to expect temporary price stalls.
Liquidity-Anchored Trailing Stop transforms traditional stop-loss logic into a multi-dimensional map of risk and liquidity. By understanding where volume is anchored and how volatility is breathing, you can stay in winning trades longer and exit with precision when the structure finally fails. Indicateur

ATR Fibonacci Trend Envelopes [BigBeluga]ATR Fibonacci Trend Envelopes is a professional-grade trend-following and mean-reversion framework. It combines the volatility-filtering power of Average True Range (ATR) with the mathematical precision of the Fibonacci Golden Ratio to define high-probability "buy/sell pockets" within an established trend.
Equipped with a live Multi-Timeframe (MTF) dashboard, this indicator allows traders to monitor trend alignment across four different time horizons simultaneously, ensuring that local entries are always supported by the broader market structure.
🔵 THE DUAL-ENGINE FRAMEWORK
Volatility-Adjusted Trend Engine: The indicator uses a customizable Moving Average (SMA, EMA, HMA, etc.) combined with an ATR multiplier to create dynamic envelopes. This filters out market noise and only signals a trend change when price decisively breaks the volatility boundary.
Dynamic Golden Pocket (0.618 - 0.786): Unlike static retracements, these Fibonacci levels are calculated relative to the current ATR envelope. The "Pocket" acts as a high-interest zone where price is expected to find support (in uptrends) or resistance (in downtrends).
Predictive Slope Projections: Using the current rate of change, the script projects the trend and Fibonacci levels into the future. This allows traders to visualize where "Value" will be in the coming bars, facilitating better trade planning and order placement.
🔵 CORE ARCHITECTURE
MTF Alignment Dashboard: A real-time table tracks the trend status and "Pocket" proximity across four timeframes. A "BULL" status combined with an "INSIDE" pocket signal across multiple timeframes indicates a high-confluence institutional setup.
Dynamic Transparency Feedback: The visual intensity of the Golden Pocket adapts based on price proximity. As price approaches the mid-point of the pocket, the colors become more saturated, providing an intuitive visual cue that the market is entering a high-probability reversal zone.
Momentum-Driven Basis: The trend baseline (1.0 level) acts as the ultimate anchor. As long as price remains above this volatility-adjusted line in a bullish regime, the trend is considered structurally sound.
🔵 FEATURES
Multi-MA Versatility: Choose from 5 different moving average types to calculate your trend basis, allowing the indicator to be tuned for slow-moving macro trends or fast-moving scalping setups.
Real-Time Level Labels: Clear, real-time labels (0.5, 0.618, 0.786, 1.0) on the right axis provide exact price targets and stop-loss anchors at a glance.
Customizable Projection Length: Adjust how far the indicator looks into the "future," allowing you to anticipate structural shifts before they occur on the chart.
Adaptive UI Positioning: The dashboard can be moved to any corner of the chart and scaled to match your screen resolution, ensuring it never interferes with your technical analysis.
🔵 STRATEGIC APPLICATION
The "Golden" Pullback: In a confirmed Bull trend (Cyan baseline), wait for price to enter the Dynamic Golden Pocket. Use the saturation of the baseFill color to identify the core of the value zone for a long entry.
MTF Confluence Trading: Only take trades when at least three timeframes on the dashboard show the same trend direction. If the 1H and 4H are "BULL" while the 15m enters the "INSIDE" pocket, you have a high-probability trend-continuation setup.
Volatility Breakouts: Monitor the distance between the baseline and the 0.5 Fib. When the ATR-based envelopes contract, a volatility breakout is imminent. A "⦿" label signal combined with a price cross of the 1.0 level marks the start of a new momentum cycle.
Dynamic Exit Planning: Use the projected 0.5 or 0.618 levels as trailing profit targets. Because these levels adjust for both price and volatility, they represent a mathematically "fair" area to take chips off the table.
ATR Fibonacci Trend Envelopes bridges the gap between classic technical analysis and modern volatility modeling. By combining MTF awareness with the natural pull of the Fibonacci ratios, it provides a clear, actionable map for navigating any market condition. Indicateur

Delta Pressure Ledger [JOAT]Delta Pressure Ledger
Introduction
Delta Pressure Ledger is an open-source lower-pane pressure model built entirely from chart-derived proxies. It combines anchored VWAP context, candle pressure, volume impulse, crowding stretch, volatility pressure, and settlement skew into a normalized composite ledger that classifies whether pressure is balanced, directional, crowded, or stressed.
The problem this script solves is hidden market pressure. Many traders rely on unavailable data feeds or vendor-only metrics to estimate crowding or liquidation risk. Delta Pressure Ledger uses only chart-accessible inputs and standardizes them through z-score normalization so pressure states can still be read in a consistent way across instruments.
Core Concepts
1. Chart-Derived Pressure Proxy
The script estimates directional pressure from candle settlement, intrabar range occupation, and volume impulse rather than external order flow feeds.
2. Anchored VWAP Context
Pressure is interpreted relative to anchored value, allowing the user to distinguish directional expansion from overstretched crowding.
3. Z-Score Normalization
All sub-engines are normalized over a configurable lookback, which makes the composite reading more portable across symbols and timeframes.
4. Crowding and Stress Logic
The script tracks when price and derived sentiment become stretched enough to imply elevated liquidation or unwind risk.
5. Composite Verdict
Pressure, crowding, volatility, and skew are merged into one verdict state so the user can quickly determine whether the market is orderly, imbalanced, or stressed.
Features
Anchored VWAP context: Session, weekly, or monthly value anchor
Pressure engine: Candle and volume-derived directional pressure model
Crowding engine: Stretch and behavioral excess detection
Volatility and skew layers: Pressure quality and instability are separated from raw direction
Normalized composite score: All sub-engines standardized into one comparable ledger
Risk meter: Liquidation-style stress estimate derived from crowding and instability
Confirmed-bar transitions: State changes and alerts are held to confirmed bars
Top-right dashboard: Regime, pressure, crowding, volatility, risk, composite score, and last confirmed flip
How to Use This Indicator
Step 1: Read the composite verdict
The verdict gives the fastest summary of whether the market is balanced, directionally pressured, or entering a crowded stress state.
Step 2: Separate pressure from crowding
A bullish pressure reading with low crowding is different from a bullish pressure reading with extreme crowding and high risk.
Step 3: Respect risk transitions
When the risk meter moves into elevated territory, directional continuation setups deserve more caution.
Indicator Limitations
This script uses chart-derived proxies rather than exchange-level liquidation or true open-interest feeds
Normalized readings can still behave differently across asset classes with unusual volume structure
Stress conditions can remain elevated for extended periods during strong trends
The script classifies pressure and risk context; it does not execute trades by itself
Originality Statement
Delta Pressure Ledger is original in the way it builds a portable, chart-derived pressure and crowding framework without depending on unavailable external feeds, while still organizing the result into a normalized composite and risk ledger.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice. Derived pressure and crowding models can be wrong, especially during atypical market events. Use proper risk management and independent judgment.
Indicateur

GARCH Volumetric Cloud [MarkitTick]💡 The GARCH Volumetric Cloud is a highly advanced, institutional-grade trend-following and volatility-tracking indicator designed to filter market noise and pinpoint high-probability trend reversals. By synergizing a dynamic volatility engine inspired by conditional heteroskedasticity models with the smoothing properties of synthetic Heikin-Ashi price action, this tool offers traders a multi-dimensional perspective on market dynamics. It goes beyond simple price crossovers by mathematically confirming that a structural shift in trend is supported by an underlying surge in market volatility. This dual-verification approach significantly reduces the likelihood of entering false breakouts or getting trapped in ranging, low-momentum environments.
✨ Originality and Utility
Standard technical indicators often rely on a single dimension of market data, such as moving averages for trend or the Average True Range for volatility. This script breaks the mold by calculating a real-time variance proxy based on squared logarithmic returns, effectively bridging the gap between academic quantitative finance and retail charting. The originality lies in its "Volatility Gatekeeper" mechanism. The system only validates trend signals when the market is experiencing a mathematically significant expansion in variance, preventing the underlying Heikin-Ashi cloud from signaling entries during dormant or strictly mean-reverting phases.
Furthermore, the script calculates synthetic Heikin-Ashi values internally without relying on secondary chart inputs or delayed security calls. This ensures seamless integration, zero lookahead bias, and absolute synchronization with the current timeframe. It combines this with a fully integrated JSON webhook alert system, making it an all-in-one solution for both manual discretionary traders and automated systematic execution.
🔬 Methodology and Concepts
The core methodology is divided into two distinct processing engines that operate in parallel and converge to generate actionable signals.
● Volatility Engine
The system first determines the period-over-period return, giving the user the option to utilize logarithmic returns for superior statistical normalization.
These returns are squared to calculate raw variance.
To model volatility clustering (the tendency for volatile periods to cluster together), the script applies an Exponentially Weighted Moving Average (EWMA) to the squared returns.
This EWMA acts as a dynamic variance proxy, prioritizing recent market shocks while retaining a memory of historical data, governed by the Lambda decay factor.
The square root of this variance proxy is taken to return the value to a standard volatility scale.
A localized volatility threshold is established by calculating a Simple Moving Average and Standard Deviation of this volatility proxy. A "High Volatility" state is triggered when the current volatility exceeds the moving average plus a user-defined multiple of the standard deviation.
● Trend Cloud Engine
The script derives mathematical Heikin-Ashi price points (Open, High, Low, Close) independently of the user's primary chart type.
Four distinct Exponential Moving Averages (EMAs) are applied sequentially to the synthetic Heikin-Ashi Close price.
The structural trend state is determined by the relationship between the Fast EMA and the Slow EMA.
When the Fast EMA crosses above the Slow EMA, the internal state shifts to Bullish. When it crosses below, the state shifts to Bearish.
🎨 Visual Guide
The visual interface of the indicator is designed to provide immediate situational awareness through color-coded elements and structural bands.
● Synthetic Heikin-Ashi Candles
The indicator plots custom candles directly on the chart, overriding the standard visual noise.
Bullish Theme: Colored in vivid Cyan (#00E5FF) when the underlying cloud structure is in an upward trend.
Bearish Theme: Colored in distinct Pink/Red (#FF3D71) when the underlying cloud structure shifts downward.
The bodies, borders, and wicks are synchronized to these specific themes to maintain a clean visual hierarchy.
● The Moving Average Cloud
Cloud L1 (Fast): Plotted as a solid line with 40 percent opacity.
Cloud L4 (Slow): Plotted as the foundational boundary line, also at 40 percent opacity.
Cloud Spine: A thicker, central moving average derived from the midpoint of the inner EMAs, drawn at 20 percent opacity to serve as a micro-support/resistance level within the broader cloud structure.
Gradient Fills: The space between the four EMA lines is filled with cascading color opacities (50 percent, 65 percent, and 78 percent), creating a three-dimensional visual depth that expands during strong trends and pinches during consolidation.
📖 How to Use
Applying this indicator requires an understanding of its dual-verification logic. It is not designed to trade every crossover, but rather to isolate structural shifts.
● Identifying Opportunities
A valid Long signal occurs when the Fast EMA crosses above the Slow EMA, but only if the previous candle was mathematically classified as being in a "High Volatility" state by the GARCH engine.
A valid Short signal occurs when the Fast EMA crosses below the Slow EMA under the exact same high-volatility prerequisite.
Visually, traders should look for a color shift in the cloud and candles, accompanied by a sharp widening of the cloud structure.
● Automation and Execution
The script calculates a dynamic Stop Loss based on the lowest low of the last 5 bars for long positions, and the highest high of the last 5 bars for short positions.
The Take Profit is mechanically projected using a strict 1:1.5 risk-to-reward ratio based on the calculated Stop Loss distance.
These parameters are packaged into a JSON payload and fired via webhook at the exact moment the signal bar closes and confirms, ensuring zero repainting and immediate execution for connected bots.
⚙️ Inputs and Settings
The indicator provides deep customization options, allowing traders to tune the engines to specific assets and timeframes.
● GARCH Volume Engine
Use EWMA: Toggles between the exponentially weighted variance model and a simple moving average of variance.
Log Returns: Enables logarithmic return calculations for more accurate financial time-series modeling.
Variance Length: Defines the lookback period for the initial variance baseline.
Threshold Lookback: Sets the window for the standard deviation bands applied to the final volatility proxy.
EWMA Lambda: The decay factor for the weighted average. A standard setting of 0.94 mirrors classic RiskMetrics methodology.
High Volatility Band: The standard deviation multiplier required to trigger a "High Volatility" validation state.
● Cloud & Trend Engine
Cloud Fast Length: The lookback for the primary reactive EMA.
Cloud Mid-Fast Length: The first internal structural EMA.
Cloud Mid-Slow Length: The second internal structural EMA.
Cloud Slow Length: The foundational EMA that determines the overall baseline trend.
● Webhook Actions (Automation)
Action Long: The string identifier sent in the JSON payload when a bullish setup is confirmed.
Action Short: The string identifier sent in the JSON payload when a bearish setup is confirmed.
🔍 Deconstruction of the Underlying Scientific and Academic Framework
The architectural foundation of this script is deeply rooted in quantitative financial theory, specifically drawing from time-series econometrics and signal processing. The volatility engine is a deterministic approximation of the Generalized Autoregressive Conditional Heteroskedasticity (GARCH) model. In standard financial mathematics, asset returns do not exhibit constant variance; instead, they experience periods of clustered turbulence and clustered calm.
By calculating the squared log returns, the script isolates the magnitude of price movement independently of directional drift. The application of an Exponentially Weighted Moving Average (EWMA) to these squared returns serves as the conditional variance estimator. The Lambda parameter acts as the memory decay coefficient. By setting this coefficient high (e.g., 0.94), the model ensures that the volatility proxy reacts aggressively to sudden market shocks (such as a macroeconomic data release or institutional block order) while slowly decaying back to the mean, perfectly mirroring the theoretical decay of implied volatility in options pricing.
Parallel to the econometric variance modeling, the script employs a cascaded digital filter design via the Heikin-Ashi EMA cloud. The Heikin-Ashi transformation modifies the standard Open-High-Low-Close data points to incorporate previous period averages, inherently introducing an autoregressive smoothing effect that diminishes high-frequency market noise. By passing this pre-smoothed data through a series of four Exponential Moving Averages, the system applies a multi-pole low-pass filter. The dispersion between the Fast EMA and Slow EMA represents the momentum vector of the trend. The final gating logic, which demands that a structural moving average crossover must be contemporaneous with a statistically significant deviation in the EWMA variance proxy, is a sophisticated method of reducing Type I errors (false positives) in algorithmic trend-following systems.
⚠️ 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. Indicateur

Equilibrium Momentum Shift + Divegence [BigBeluga]🔵 OVERVIEW
Equilibrium Momentum Shift is a range-based momentum oscillator designed to measure how far price has deviated from its current equilibrium.
Instead of focusing purely on trend direction or overbought/oversold conditions, this indicator evaluates price relative to the midpoint of its recent range and quantifies the strength of the shift away from that balance.
By combining normalized range deviation, smoothing techniques, and nonlinear compression, the indicator provides a clear view of when markets transition from equilibrium into directional momentum, now featuring Normal Divergence detection to spot potential trend reversals.
🔵 CONCEPT
Equilibrium Midpoint — The midpoint between the highest high and lowest low over the selected range length represents the equilibrium price.
Deviation Measurement — The indicator measures how far the current price has moved away from this midpoint.
Range Normalization — Deviations are normalized relative to the size of the current range, allowing the oscillator to remain consistent across different volatility conditions.
Momentum Compression — A hyperbolic tangent function compresses extreme values, stabilizing the oscillator and preventing runaway signals during large trends.
Divergence Identification — Automatically identifies discrepancies between price action and the oscillator to highlight weakening momentum in established trends.
🔵 HOW IT WORKS
1️⃣ Equilibrium Range Calculation
The indicator calculates the highest high and lowest low over the user-defined range length.
The midpoint between these two levels forms the equilibrium line.
This midline represents the center of balance for recent price activity.
2️⃣ Price Deviation Measurement
The distance between the current close and the equilibrium midpoint is calculated.
This deviation is then smoothed using a double EMA structure to reduce noise.
The smoothed value is normalized relative to half of the current range size.
3️⃣ Nonlinear Oscillator Transformation
A hyperbolic tangent function compresses normalized deviations into a stable range between -1 and +1.
This transformation prevents extreme outliers and creates a more interpretable oscillator.
4️⃣ Momentum Histogram
A signal line is generated using EMA smoothing.
The difference between the oscillator and the signal line forms a histogram.
The histogram behaves similarly to a MACD-style momentum indicator:
Expanding bars indicate strengthening momentum.
Contracting bars indicate weakening momentum.
5️⃣ Normal Divergence Logic
Bullish Divergence: Occurs when price makes a Lower Low , but the Equilibrium Oscillator makes a Higher Low . This suggests that despite the price drop, the selling pressure relative to equilibrium is fading.
Bearish Divergence: Occurs when price makes a Higher High , but the Equilibrium Oscillator makes a Lower High . This indicates that the buyers' ability to push price away from the midpoint is losing strength.
🔵 KEY FEATURES
Equilibrium midpoint plotted directly on the chart.
Range-normalized momentum oscillator.
Hyperbolic tangent compression to stabilize signals.
MACD-style histogram for momentum acceleration detection.
Automatic Normal Divergence labels to spot exhaustion.
Gradient-colored oscillator line reflecting directional bias.
Dashboard displaying real-time momentum metrics.
🔵 DASHBOARD METRICS
Shift — Current oscillator value showing how far price has moved from equilibrium.
State — Market regime derived from oscillator thresholds:
Bullish
Bearish
Neutral
Range Position — Location of price inside the current range expressed as a percentage.
Pressure — Magnitude of momentum deviation from equilibrium.
🔵 HOW TO USE
Use the equilibrium midline as a dynamic balance reference.
When the oscillator moves above zero, bullish momentum dominates.
When the oscillator moves below zero, bearish momentum dominates.
Trading Divergences: Watch for divergence labels when price is at historical range extremes. A bullish divergence near the "Lowest Low" of the range suggests a high-probability mean-reversion trade back toward equilibrium.
Histogram expansions highlight momentum acceleration.
Histogram contraction can signal potential momentum exhaustion.
🔵 INTERPRETING MOMENTUM SHIFTS
Oscillator near zero → Market is balanced around equilibrium.
Oscillator above 0.2 → Bullish momentum phase.
Oscillator below -0.2 → Bearish momentum phase.
Divergence Label + Oscillator Flatline → High probability of a trend reversal or deep pullback.
Rapid oscillator expansion → Strong directional pressure.
Oscillator flattening → Momentum compression or consolidation.
🔵 CONCLUSION
Equilibrium Momentum Shift offers a structured way to analyze how price behaves relative to its recent balance point.
By measuring normalized deviations from equilibrium and visualizing momentum shifts with a smoothed oscillator, histogram, and integrated divergence analysis , the indicator helps traders identify when markets transition from balance into directional movement.
This makes it especially useful for spotting early momentum expansions, trend continuation signals, and potential exhaustion points where price is likely to snap back to its equilibrium midpoint. Indicateur

Liquidity Contour Engine [JOAT]
Liquidity Contour Engine
Introduction
Liquidity Contour Engine is an overlay indicator that identifies two distinct institutional price phenomena: liquidity sweeps at swing highs and lows, and order blocks formed before impulsive structural moves. Liquidity sweep zones mark levels where price reached beyond a prior swing, triggering stop orders, then reversed — the classic footprint of a sweep-and-reversal sequence. Order block zones mark the last opposing candle before a significant directional impulse, representing the area where a large position was initiated.
The underlying premise is that institutions build and exit positions through order flow that leaves identifiable marks on the chart. A liquidity sweep is one such mark: price extending beyond a well-established swing level, clearing stops, then reversing. This behavior is not random — it reflects deliberate order accumulation at levels where retail stops cluster. Similarly, order blocks at the origin of impulsive moves may act as re-entry areas when price later returns to them.
Core Concepts
1. Confirmed Swing Pivot Detection
Swings are identified using ta.pivothigh and ta.pivotlow with a configurable lookback. All pivot detections are confirmed — offset by the lookback bars — meaning no repainting occurs. Only when sufficient bars have closed on both sides of a potential pivot is it registered.
2. Liquidity Sweep Detection
A bullish sweep is confirmed when: price wicks below the most recent swing low by at least a configurable ATR multiple, and the bar closes back above that swing low. This captures the wick-past-and-close-back pattern that characterizes institutional accumulation at liquidity levels. A bearish sweep is the mirror condition at swing highs.
Upon detection, a zone is created at the swept level, rendered as a dual-width line (thin solid + thick transparent shadow). Zones remain active until price sustains a close beyond the swept level by 0.5 ATR, at which point they convert to dotted lines (mitigated state).
3. Order Block Detection
An order block is identified as the prior N candle(s) before a structural impulse. A bullish impulse is defined as a bar that closes above the most recent swing high. The order block is the last candle body before that impulse, rendered as a filled box from body open to the wick high. Mitigation occurs when price closes beyond the 50% level of the order block body, fading the box to indicate the zone has been traded through.
4. Zone Lifecycle Management
The indicator uses arrays to track active zones and enforces a maximum count. When the maximum is exceeded, the oldest zone is removed from the chart. This prevents chart clutter while keeping the most recent and relevant zones visible.
Features
Liquidity Sweep Zones: Dual-width line rendering at swept swing levels, self-managing lifecycle
Order Block Boxes: Filled zones at order block origin, with mitigation fading
Swing Level Dotted Lines: Current swing high and low extensions as dotted reference lines
9-Row Dashboard: Sweep state, active zone counts, order block counts, last swing levels
Configurable ATR Threshold: Adjusts how far price must reach beyond a swing to qualify as a sweep
Max Zone Limit: Prevents chart clutter with configurable maximum active zone count
Input Parameters
Swing Lookback: Bars required each side for pivot confirmation (default: 8)
Sweep ATR Threshold: Minimum sweep distance in ATR units (default: 0.3)
Max Active Zones: Maximum concurrently displayed liquidity zones (default: 8)
ATR Period: Period for ATR calculation (default: 14)
Show Order Blocks: Toggle order block rendering
OB Lookback: How many bars back to identify the order block candle (default: 3)
How to Use This Indicator
Sweep-and-Reverse Setups
When a bullish sweep fires (price wicked below a swing low and closed back above), the zone represents the level where stops were taken. If price subsequently builds structure above that zone and delta pressure is positive, the setup is a potential long entry with the swept level as reference for the stop.
Order Block Re-Tests
When price returns to a bullish order block zone (shown in teal), it is revisiting the area where an institutional position was likely initiated. If the zone has not been mitigated (box remains filled), a reaction from that zone is plausible. A mitigated order block (faded) is a less reliable reference.
Zone Confluence
When a liquidity sweep zone and an order block coincide at the same price level, the confluence represents a stronger structural reference than either zone alone.
Limitations
Swing pivot confirmation introduces a bar lag equal to the lookback period. Sweeps and order blocks are identified after the fact, not in the moment they form
Not every liquidity sweep produces a reversal. Price can continue through a swept level without reversing
Order block identification is mechanical and cannot account for all institutional order placement strategies
On higher timeframes, zones cover wider price ranges and may require adjustment of the ATR threshold
Originality Statement
The unified framework for tracking liquidity sweeps and order blocks within a single indicator with a shared zone lifecycle management system is the original design contribution. Zone mitigation logic that converts active zones to passive reference lines (rather than deleting them) preserves structural context while visually indicating that a zone's primary relevance has passed. The dual-width shadow line rendering for sweep zones provides depth that distinguishes them clearly from standard horizontal lines.
Disclaimer
This indicator is for educational and informational purposes only. Liquidity sweep detection describes a pattern in historical price data. Past occurrences of this pattern do not guarantee future reactions. Order blocks are hypothetical areas of interest, not confirmed institutional levels. Always use proper risk management.
-Made with passion by officialjackofalltrades
Indicateur

Swing Fibonacci [BigBeluga]Swing Fibonacci is a high-precision geometric framework that merges traditional swing structure with parametric spiral projections. Unlike standard Fibonacci retracements that use static horizontal lines, this tool projects expanding harmonic spirals from major structural turning points to map out the "natural geometry" of the market.
By calculating the mathematical relationship between price volatility and time, the indicator identifies expansion shells where price is naturally inclined to react, stall, or reverse.
🔵 CONCEPTS
Macro Swing Detection: The engine utilizes a high-threshold lookback window (50–100 bars) to filter out market noise. It only identifies the most significant structural pivots, ensuring the spirals are anchored to "institutional" levels rather than minor retail fluctuations.
Anchor Points & Structural Mapping: At every confirmed trend reversal, the script anchors a ⦾ symbol. It then draws a solid "Swing Leg" connecting the current anchor to the previous one, providing a clear visual map of the market's structural transitions.
Parametric Fibonacci Spirals: The spirals are generated using a high-resolution 300-step parametric calculation. This ensures the curve remains perfectly smooth and mathematically accurate regardless of how many bars are on the screen.
Adaptive Price Normalization: To prevent the "squashed" look common in geometric tools, the spiral dynamically rescales itself based on the price range of the last 500 bars. This ensures the geometry stays proportional to current market volatility.
🔵 FEATURES
Institutional Data Dashboard: Located in the top-right corner, the dashboard provides real-time stats including the exact Anchor Price , the current Trend Status (BULLISH ▲ or BEARISH ▼), and the Swing % move from the low/high.
Real-Time Swing Tracking: A dynamic dashed line follows the current price, connecting it back to the active anchor point. This allows you to visualize the current "swing in progress" before it is finalized.
Parametric Control Suite:
• Radius: Adjusts the vertical "stretch" and overall size.
• Spiral Qty: Controls the number of rotations (up to 10) to project further into the future.
Color Flow Visualization: The spirals utilize a professional gradient transition from the bearish color (inner) to the bullish color (outer), visually representing the expansion of price energy.
🔵 HOW TO USE
Identify Reaction Zones: Price often treats the edges of the spiral curves as dynamic support and resistance. Look for "confluence" where a spiral curve intersects with a horizontal level or a previous swing point.
Forecasting Expansion:
• Bullish Spiral: Projects outward from a swing low, highlighting potential take-profit zones or areas where the trend might exhaust.
• Bearish Spiral: Projects from a swing high, identifying "expansion floors" for short positions.
Trend Confirmation: Use the Trend Squares at the bottom of the chart for a quick pulse on the current directional bias without cluttering the main price action.
Harmonic Timing: The spiral's horizontal reach provides a "time" component. If price reaches a specific spiral arc at a specific time, it often marks a high-probability turning point in the cycle.
🔵 CONCLUSION
Swing Fibonacci transforms abstract price action into a tangible geometric forecast. By anchoring dynamic, price-normalized spirals to the market’s strongest turning points, it provides a unique lens through which to view volatility, extension, and mean reversion.
Ideal for harmonic traders, swing analysts, and anyone looking for a deeper mathematical edge in their structural analysis. Indicateur

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 TradingView 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 TradingView'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 TradingView 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 TradingView 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 TradingView 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. Bibliothèque
