Machine Learning BBPct [BackQuant]Machine Learning BBPct
What this is (in one line)
A Bollinger Band %B oscillator enhanced with a simplified K-Nearest Neighbors (KNN) pattern matcher. The model compares today’s context (volatility, momentum, volume, and position inside the bands) to similar situations in recent history and blends that historical consensus back into the raw %B to reduce noise and improve context awareness. It is informational and diagnostic—designed to describe market state, not to sell a trading system.
Background: %B in plain terms
Bollinger %B measures where price sits inside its dynamic envelope: 0 at the lower band, 1 at the upper band, ~ 0.5 near the basis (the moving average). Readings toward 1 indicate pressure near the envelope’s upper edge (often strength or stretch), while readings toward 0 indicate pressure near the lower edge (often weakness or stretch). Because bands adapt to volatility, %B is naturally comparable across regimes.
Why add (simplified) KNN?
Classic %B is reactive and can be whippy in fast regimes. The simplified KNN layer builds a “nearest-neighbor memory” of recent market states and asks: “When the market looked like this before, where did %B tend to be next bar?” It then blends that estimate with the current %B. Key ideas:
• Feature vector . Each bar is summarized by up to five normalized features:
– %B itself (normalized)
– Band width (volatility proxy)
– Price momentum (ROC)
– Volume momentum (ROC of volume)
– Price position within the bands
• Distance metric . Euclidean distance ranks the most similar recent bars.
• Prediction . Average the neighbors’ prior %B (lagged to avoid lookahead), inverse-weighted by distance.
• Blend . Linearly combine raw %B and KNN-predicted %B with a configurable weight; optional filtering then adapts to confidence.
This remains “simplified” KNN: no training/validation split, no KD-trees, no scaling beyond windowed min-max, and no probabilistic calibration.
How the script is organized (by input groups)
1) BBPct Settings
• Price Source – Which price to evaluate (%B is computed from this).
• Calculation Period – Lookback for SMA basis and standard deviation.
• Multiplier – Standard deviation width (e.g., 2.0).
• Apply Smoothing / Type / Length – Optional smoothing of the %B stream before ML (EMA, RMA, DEMA, TEMA, LINREG, HMA, etc.). Turning this off gives you the raw %B.
2) Thresholds
• Overbought/Oversold – Default 0.8 / 0.2 (inside ).
• Extreme OB/OS – Stricter zones (e.g., 0.95 / 0.05) to flag stretch conditions.
3) KNN Machine Learning
• Enable KNN – Switch between pure %B and hybrid.
• K (neighbors) – How many historical analogs to blend (default 8).
• Historical Period – Size of the search window for neighbors.
• ML Weight – Blend between raw %B and KNN estimate.
• Number of Features – Use 2–5 features; higher counts add context but raise the risk of overfitting in short windows.
4) Filtering
• Method – None, Adaptive, Kalman-style (first-order),
or Hull smoothing.
• Strength – How aggressively to smooth. “Adaptive” uses model confidence to modulate its alpha: higher confidence → stronger reliance on the ML estimate.
5) Performance Tracking
• Win-rate Period – Simple running score of past signal outcomes based on target/stop/time-out logic (informational, not a robust backtest).
• Early Entry Lookback – Horizon for forecasting a potential threshold cross.
• Profit Target / Stop Loss – Used only by the internal win-rate heuristic.
6) Self-Optimization
• Enable Self-Optimization – Lightweight, rolling comparison of a few canned settings (K = 8/14/21 via simple rules on %B extremes).
• Optimization Window & Stability Threshold – Governs how quickly preferred K changes and how sensitive the overfitting alarm is.
• Adaptive Thresholds – Adjust the OB/OS lines with volatility regime (ATR ratio), widening in calm markets and tightening in turbulent ones (bounded 0.7–0.9 and 0.1–0.3).
7) UI Settings
• Show Table / Zones / ML Prediction / Early Signals – Toggle informational overlays.
• Signal Line Width, Candle Painting, Colors – Visual preferences.
Step-by-step logic
A) Compute %B
Basis = SMA(source, len); dev = stdev(source, len) × multiplier; Upper/Lower = Basis ± dev.
%B = (price − Lower) / (Upper − Lower). Optional smoothing yields standardBB .
B) Build the feature vector
All features are min-max normalized over the KNN window so distances are in comparable units. Features include normalized %B, normalized band width, normalized price ROC, normalized volume ROC, and normalized position within bands. You can limit to the first N features (2–5).
C) Find nearest neighbors
For each bar inside the lookback window, compute the Euclidean distance between current features and that bar’s features. Sort by distance, keep the top K .
D) Predict and blend
Use inverse-distance weights (with a strong cap for near-zero distances) to average neighbors’ prior %B (lagged by one bar). This becomes the KNN estimate. Blend it with raw %B via the ML weight. A variance of neighbor %B around the prediction becomes an uncertainty proxy ; combined with a stability score (how long parameters remain unchanged), it forms mlConfidence ∈ . The Adaptive filter optionally transforms that confidence into a smoothing coefficient.
E) Adaptive thresholds
Volatility regime (ATR(14) divided by its 50-bar SMA) nudges OB/OS thresholds wider or narrower within fixed bounds. The aim: comparable extremeness across regimes.
F) Early entry heuristic
A tiny two-step slope/acceleration probe extrapolates finalBB forward a few bars. If it is on track to cross OB/OS soon (and slope/acceleration agree), it flags an EARLY_BUY/SELL candidate with an internal confidence score. This is explicitly a heuristic—use as an attention cue, not a signal by itself.
G) Informational win-rate
The script keeps a rolling array of trade outcomes derived from signal transitions + rudimentary exits (target/stop/time). The percentage shown is a rough diagnostic , not a validated backtest.
Outputs and visual language
• ML Bollinger %B (finalBB) – The main line after KNN blending and optional filtering.
• Gradient fill – Greenish tones above 0.5, reddish below, with intensity following distance from the midline.
• Adaptive zones – Overbought/oversold and extreme bands; shaded backgrounds appear at extremes.
• ML Prediction (dots) – The KNN estimate plotted as faint circles; becomes bright white when confidence > 0.7.
• Early arrows – Optional small triangles for approaching OB/OS.
• Candle painting – Light green above the midline, light red below (optional).
• Info panel – Current value, signal classification, ML confidence, optimized K, stability, volatility regime, adaptive thresholds, overfitting flag, early-entry status, and total signals processed.
Signal classification (informational)
The indicator does not fire trade commands; it labels state:
• STRONG_BUY / STRONG_SELL – finalBB beyond extreme OS/OB thresholds.
• BUY / SELL – finalBB beyond adaptive OS/OB.
• EARLY_BUY / EARLY_SELL – forecast suggests a near-term cross with decent internal confidence.
• NEUTRAL – between adaptive bands.
Alerts (what you can automate)
• Entering adaptive OB/OS and extreme OB/OS.
• Midline cross (0.5).
• Overfitting detected (frequent parameter flipping).
• Early signals when early confidence > 0.7.
These are purely descriptive triggers around the indicator’s state.
Practical interpretation
• Mean-reversion context – In range markets, adaptive OS/OB with ML smoothing can reduce whipsaws relative to raw %B.
• Trend context – In persistent trends, the KNN blend can keep finalBB nearer the mid/upper region during healthy pullbacks if history supports similar contexts.
• Regime awareness – Watch the volatility regime and adaptive thresholds. If thresholds compress (high vol), “OB/OS” comes sooner; if thresholds widen (calm), it takes more stretch to flag.
• Confidence as a weight – High mlConfidence implies neighbors agree; you may rely more on the ML curve. Low confidence argues for de-emphasizing ML and leaning on raw %B or other tools.
• Stability score – Rising stability indicates consistent parameter selection and fewer flips; dropping stability hints at a shifting backdrop.
Methodological notes
• Normalization uses rolling min-max over the KNN window. This is simple and scale-agnostic but sensitive to outliers; the distance metric will reflect that.
• Distance is unweighted Euclidean. If you raise featureCount, you increase dimensionality; consider keeping K larger and lookback ample to avoid sparse-neighbor artifacts.
• Lag handling intentionally uses neighbors’ previous %B for prediction to avoid lookahead bias.
• Self-optimization is deliberately modest: it only compares a few canned K/threshold choices using simple “did an extreme anticipate movement?” scoring, then enforces a stability regime and an overfitting guard. It is not a grid search or GA.
• Kalman option is a first-order recursive filter (fixed gain), not a full state-space estimator.
• Hull option derives a dynamic length from 1/strength; it is a convenience smoothing alternative.
Limitations and cautions
• Non-stationarity – Nearest neighbors from the recent window may not represent the future under structural breaks (policy shifts, liquidity shocks).
• Curse of dimensionality – Adding features without sufficient lookback can make genuine neighbors rare.
• Overfitting risk – The script includes a crude overfitting detector (frequent parameter flips) and will fall back to defaults when triggered, but this is only a guardrail.
• Win-rate display – The internal score is illustrative; it does not constitute a tradable backtest.
• Latency vs. smoothness – Smoothing and ML blending reduce noise but add lag; tune to your timeframe and objectives.
Tuning guide
• Short-term scalping – Lower len (10–14), slightly lower multiplier (1.8–2.0), small K (5–8), featureCount 3–4, Adaptive filter ON, moderate strength.
• Swing trading – len (20–30), multiplier ~2.0, K (8–14), featureCount 4–5, Adaptive thresholds ON, filter modest.
• Strong trends – Consider higher adaptive_upper/lower bounds (or let volatility regime do it), keep ML weight moderate so raw %B still reflects surges.
• Chop – Higher ML weight and stronger Adaptive filtering; accept lag in exchange for fewer false extremes.
How to use it responsibly
Treat this as a state descriptor and context filter. Pair it with your execution signals (structure breaks, volume footprints, higher-timeframe bias) and risk management. If mlConfidence is low or stability is falling, lean less on the ML line and more on raw %B or external confirmation.
Summary
Machine Learning BBPct augments a familiar oscillator with a transparent, simplified KNN memory of recent conditions. By blending neighbors’ behavior into %B and adapting thresholds to volatility regime—while exposing confidence, stability, and a plain early-entry heuristic—it provides an informational, probability-minded view of stretch and reversion that you can interpret alongside your own process.
趨勢分析
BitKurd Timings V3.1 BetaBitKurd Timings V3.1 Beta
Introduction
This Script displays the Asia Session Range, the London Open Inducement Window, the NY Open Inducement Window, the Previous Week's high and low, the Previous Day's highs and lows, and the Day Open price in the cleanest way possible.
Description
The Indicator is based on UTC -7 timing but displays the Session Boxes automatically correct at your chart so you do not have to adjust any timings based on your Time Zone and don't have to do any calculations based on your UTC. It is already perfect.
You will see on default settings the purple Asia Box and 2 grey boxes, the first one is for the London Open Inducement Window (1 hour) and the second grey box is for the NY Open Inducement Window (also 1 hour)
Asia Range comes with default settings with the Asia Range high, low, and midline, you can remove these 3 lines in the settings "style" and untick the "Lines" box, that way you only will have the boxes displayed.
Special Feature
Most Timing-based Indicators have "bugged" boxes or don't show clean boxes at all and don't adjust at daylight savings times, we made sure that everything automatically gets adjusted so you don't have to! So the timings will always display at the correct time regarding the daylight savings times.
Combining Timing with Liquidity Zones the right way and in a clear, clean, and simple format.
Different than others this script also shows the "true" Asia range as it respects the "day open gap" which affects the Asia range in other scripts and it also covers the full 8 hours of Asia Session.
Additions
You can add in the settings menu the last week's high and low, the previous day's high and low, and also the day's open price by ticking the boxes in the settings menu
All colors of the boxes are fully adjustable and customizable for your personal preferences. Same for the previous weeks and day highs and lows. Just go to "Style" and you can adjust the Line types or colors to your preferred choice.
Recommended Use
The most beautiful display is on the M5 Timeframe as you have a clear overview of all sessions without losing the intraday view. You can also use it on the M1 for more details or the M15 for the bigger picture. The Template can hide on higher time frames starting from the H1 to not flood your chart with boxes.
How to use the Asia Session Range Box
Use the Asia Range Box as your intraday Guide, keep in mind that a Breakout of Asia high or low induces Liquidity and a common price behavior is a reversal after the fake breakout of that range.
How to use the London Open and NY Open Inducement Windows
Both grey boxes highlight the Open of either London Open or NY Open and you should keep an eye out for potential Liquditiy Graps or Mitigations during that times as this is when they introduce major Liquidity for the regarding Session.
How to use the Asia high, low and midline and day open price
After Asia Range got taken out in one direction, often price comes back to those levels to mitigate or bounce off, so you can imagine those zones as support and resistance on some occasions, recommended in combination with Imbalances.
How to use the previous day and week's highs and lows
Once added in the settings, you can display those price levels, you can use them either as Liquidity Targets or as Inducement Levels once they are taken out.
Enjoy!
Fractal Circles#### FRACTAL CIRCLES ####
I combined 2 of my best indicators Fractal Waves (Simplified) and Circles.
Combining the Fractal and Gann levels makes for a very simple trading strategy.
Core Functionality
Gann Circle Levels: This indicator plots mathematical support and resistance levels based on Gann theory, including 360/2, 360/3, and doubly strong levels. The system automatically adjusts to any price range using an intelligent multiplier system, making it suitable for forex, stocks, crypto, or any market.
Fractal Wave Analysis: Integrates real-time trend analysis from both current and higher timeframes. Shows the current price range boundaries (high/low) and trend direction through dynamic lines and background fills, helping traders understand market structure.
Key Trading Benefits
Active Level Detection: The closest Gann level to current price is automatically highlighted in green with increased line thickness. This eliminates guesswork about which level is most likely to act as immediate support or resistance.
Real-Time Price Tracking: A customizable line follows current price with an offset to the right, projecting where price sits relative to upcoming levels. A gradient-filled box visualizes the exact distance between current price and the active Gann level.
Multi-Timeframe Context: View fractal waves from higher timeframes while maintaining current timeframe precision. This helps identify whether short-term moves align with or contradict longer-term structure.
Smart Alert System: Comprehensive alerts trigger when price crosses any Gann level, with options to monitor all levels or focus only on the active level. Reduces the need for constant chart monitoring while ensuring you never miss significant level breaks.
Practical Trading Applications
Entry Timing: Use active level highlighting to identify the most probable support/resistance for entries. The real-time distance box helps gauge risk/reward before entering positions.
Risk Management: Set stops based on Gann level breaks, particularly doubly strong levels which tend to be more significant. The gradient visualization makes it easy to see how much room price has before hitting key levels.
Trend Confirmation: Fractal waves provide immediate context about whether current price action aligns with broader market structure. Bullish/bearish background fills offer quick visual confirmation of trend direction.
Multi-Asset Analysis: The auto-scaling multiplier system works across all markets and timeframes, making it valuable for traders who monitor multiple instruments with vastly different price ranges.
Confluence Trading: Combine Gann levels with fractal wave boundaries to identify high-probability setups where multiple technical factors align.
This tool is particularly valuable for traders who appreciate mathematical precision in their technical analysis while maintaining the flexibility to adapt to real-time market conditions.
Multi-Band Trend LineThis Pine Script creates a versatile technical indicator called "Multi-Band Trend Line" that builds upon the concept of the popular "Follow Line Indicator" by Dreadblitz. While the original Follow Line Indicator uses simple trend detection to place a line at High or Low levels, this enhanced version combines multiple band-based trading strategies with dynamic trend line generation. The indicator supports five different band types and provides more sophisticated buy/sell signals based on price breakouts from various technical analysis bands.
Key Features
Multi-Band Support
The indicator supports five different band types:
- Bollinger Bands: Uses standard deviation to create bands around a moving average
- Keltner Channels: Uses ATR (Average True Range) to create bands around a moving average
- Donchian Channels: Uses the highest high and lowest low over a specified period
- Moving Average Envelopes: Creates bands as a percentage above and below a moving average
- ATR Bands: Uses ATR multiplier to create bands around a moving average
Dynamic Trend Line Generation (Enhanced Follow Line Concept)
- Similar to the Follow Line Indicator, the trend line is placed at High or Low levels based on trend direction
- Key Enhancement: Instead of simple trend detection, this version uses band breakouts to trigger trend changes
- When price breaks above the upper band (bullish signal), the trend line is set to the low (optionally adjusted with ATR) - similar to Follow Line's low placement
- When price breaks below the lower band (bearish signal), the trend line is set to the high (optionally adjusted with ATR) - similar to Follow Line's high placement
- The trend line acts as dynamic support/resistance, following the price action more precisely than the original Follow Line
ATR Filter (Follow Line Enhancement)
- Like the original Follow Line Indicator, an ATR filter can be selected to place the line at a more distance level than the normal mode settled at candles Highs/Lows
- When enabled, it adds/subtracts ATR value to provide more conservative trend line placement
- Helps reduce false signals in volatile markets
- This feature maintains the core philosophy of the Follow Line while adding more precision through band-based triggers
Signal Generation
- Buy Signal: Generated when trend changes from bearish to bullish (trend line starts rising)
- Sell Signal: Generated when trend changes from bullish to bearish (trend line starts falling)
- Signals are displayed as labels on the chart
Visual Elements
- Upper and lower bands are plotted in gray
- Trend line changes color based on direction (green for bullish, red for bearish)
- Background color changes based on trend direction
- Buy/sell signals are marked with labeled shapes
How It Works
Band Calculation: Based on the selected band type, upper and lower boundaries are calculated
Signal Detection: When price closes above the upper band or below the lower band, a breakout signal is generated
Trend Line Update: The trend line is updated based on the breakout direction and previous trend line value
Trend Direction: Determined by comparing current trend line with the previous value
Alert Generation: Buy/sell conditions trigger alerts and visual signals
Use Cases
Enhanced trend following strategies: More precise than basic Follow Line due to band-based triggers
Breakout trading: Multiple band types provide various breakout opportunities
Dynamic support/resistance identification: Combines Follow Line concept with band analysis
Multi-timeframe analysis with different band types: Choose the most suitable band for your timeframe
Reduced false signals: Band confirmation provides better entry/exit points compared to simple trend following
CHoCH Reversal Hunter🔥 CHoCH Reversal Hunter — Detect Bearish CHoCH Patterns & Fibonacci Golden Zone For Precision Reversal Setups
📈 Overview
CHoCH Reversal Hunter is a Pine Script™ indicator for structured bearish market analysis.
It combines major/minor pivot detection, Change of Character (CHoCH) filtering, and logarithmic Fibonacci retracements into one framework.
The goal: identify Small LL → CHoCH → Golden Zone setups with higher precision.
🧠 Core Logic
1. 📊 Market Structure Backbone
Tracks the 4 most recent major highs (H0–H3) and 3 major lows.
These pivots form the basis for trend evaluation.
2. 🔻 Bearish Background Conditions
A bearish market context is confirmed when:
// Bearish Background Condition
isBearish = (High 3 < High 2) and (
(High 2 > High 1 and High 2 < High 0) or
(High 2 <= High 1)
)
// Reset to neutral if High 2 < High 3
This ensures that only a true lower-high structure activates the bearish framework.
3. 🎯 Hunt for Small Lower Low (LL)
Monitors minor pivot lows with a smaller lookback period.
A valid Small LL must break below the third major low (Low 2).
This Small LL becomes the 0% Fibonacci anchor.
4. 🔄 Change of Character (CHoCH) Selection
The indicator scans recent bars for three possible CHoCH patterns:
// CHoCH Type Definitions in CHoCH Hunter
// Inside → current bar inside previous bar
isInsideBar = high < high and low > low
// Smarty → short-term reversal clue
isSmartyBar = low > low and low < low
// Pivot → minor swing high (small swing detection)
isSmallPivotHigh = ta.pivothigh(high, small_swing_period, small_swing_period)
Filter rules for validity:
CHoCH must occur before the Small LL bar.
Its high must be greater than the Small LL bar’s high (dominance criterion).
5. ⚡ Confirmation & Fibonacci Activation
Once price crosses above the selected CHoCH → setup confirmed.
Fibonacci retracements (logarithmic scale) are calculated:
100% → current high (dynamic, updates before breach).
65% → Golden Zone upper boundary.
50% → Golden Zone lower boundary.
0% → Small LL anchor.
6. 📈 Dynamic Management & Reset Rules
Before 50% breach → Fibo High auto-updates with new highs.
After breach → Levels freeze.
Setup resets if:
Price drops below Small LL.
Price breaks beyond frozen levels.
New Small LL formation detected.
✨ Key Features
📍 Automatic detection of major & minor pivots.
🔍 Clear definitions for Inside, Smarty, Pivot CHoCHs.
📐 Logarithmic Fibonacci retracements for exponential markets.
🎯 Golden Zone highlighting (50%–65%).
🔄 Built-in reset logic to invalidate weak setups.
🎨 Visualization
Pivot markers for Major (📕) & Minor (📘) swings.
Labels for CHoCH points with type (“Inside”, “Smarty”, “Pivot”).
Golden Zone highlighted between 50%–65%.
Optional structure labels for clarity.
⚙️ Inputs & Customization
Major Structure Period (default: 4) — sensitivity for big swings.
Minor Structure Period (default: 2) — sensitivity for small swings.
Toggle display of pivots, structure labels, and Golden Zone.
📚 Educational Value
CHoCH Reversal Hunter is designed to help traders learn:
How bearish structures are objectively defined.
Different CHoCH types and how to filter them.
Applying Fibonacci retracements in structured setups.
⚠️ Risk Disclaimer
🚨 This indicator is for educational purposes only and does not constitute financial advice.
Trading involves significant risk — always backtest and apply sound risk management.
🆕 Release Notes v1.0
Bearish structure detection logic added.
CHoCH type classification (Inside, Smarty, Pivot).
Logarithmic Fibonacci retracement with Golden Zone.
Automatic reset & invalidation rules.
💡 Pro Tip: Watch for the sequence Bearish Background → Small LL → CHoCH → Golden Zone — this is the core hunting pattern of CHoCH Reversal Hunter.
Session Volume Profile (DeadCat)Volume Profile is a charting study that displays trading activity over specific time periods at various price levels. It appears as a horizontal histogram on the chart, revealing where traders have shown the most interest based on volume concentration.
This Volume Profile automatically anchors to user-selected timeframes, creating fresh volume analysis for each new period while maintaining clean, systematic visualization of price-volume relationships.
Core Components :
Point of Control (POC): The price level with the highest volume activity during the selected period, marked with a yellow line and left-side label.
Value Area High/Low (VAH/VAL): Price boundaries that contain a specified percentage of the total volume (default 40%), helping identify the main trading range where most activity occurred.
Volume Histogram: Left-aligned bars showing volume distribution across price levels, with value area highlighting for enhanced visual clarity.
Key Features :
- Automatic Period Detection: Supports hourly, daily, weekly, and monthly timeframe anchoring
- Customizable Granularity: Adjustable rows (10-500) for different price resolution needs
- Labels: Clear POC, VAH, and VAL identification positioned at profile start
- Toggle Controls**: Optional display for volume rows, key levels, and background fills
- Clean Visualization: Profiles reset automatically at each new period for current market focus
Display Options :
- Profile Rows: Show/hide the volume histogram bars
- Key Level Lines: Individual controls for POC, VAH, and VAL display
- Value Area Background: Optional shading between VAH and VAL levels
- Color Customization: Separate color controls for all visual elements
The indicator provides systematic volume analysis by creating fresh profiles at regular intervals, helping traders identify significant price levels and volume patterns within their preferred timeframe structure.
Disclaimer : This indicator is for educational and informational purposes only. Trading decisions should be based on comprehensive analysis and proper risk management. Past performance does not guarantee future results.
Low of day distanceA simple indicator that tells you the distance to the low of the day in percentage terms.
Useful for quick position sizing calculations when your strategy, for instance, uses low of day stops.
TrendMaster Pro with Dynamic ATROverview
TrendMaster Pro with Dynamic ATR is a comprehensive trend-following indicator designed for traders seeking to identify entry and exit points in trending markets while incorporating volatility-based risk management. Built on a multi-timeframe Exponential Moving Average (EMA) system, it combines short-term momentum signals with long-term trend filters, enhanced by a Volatility-Adjusted Moving Average (VMA) for confirmation and Average True Range (ATR) for adaptive stop-loss and take-profit levels.
This indicator overlays directly on your chart, providing visual cues for buy/sell signals, dynamic stops/targets, and optional EMA lines. It's ideal for swing trading, day trading, or scalping across various assets like stocks, forex, cryptocurrencies, and commodities. The system emphasizes trend alignment to reduce false signals, with customizable options for trailing mechanisms and filters to suit different market conditions.
Key benefits:
Multi-Timeframe Analysis: Incorporates higher timeframe EMAs for robust trend detection without needing to switch charts.
Volatility Adaptation: Uses ATR for dynamic positioning of stops and targets, helping manage risk in volatile environments.
Flexible Customization: Toggles for displaying EMAs, using trailing stops/targets, and applying VMA filters for entries/exits.
Alert Integration: Built-in alerts for entries, exits, stop breaches, and target hits to automate notifications.
Core Components
The indicator revolves around four EMAs, a VMA, and ATR calculations:
Exponential Moving Averages (EMAs):
Fast EMA (Default: 12 periods): Captures short-term momentum and quick price changes.
Slow EMA (Default: 27 periods): Identifies medium-term trends, providing a smoother view than the Fast EMA.
Stop EMA (Default: 48 periods on 15-minute timeframe): Acts as dynamic support/resistance for risk management and exit signals.
Trend EMA (Default: 288 periods on 5-minute timeframe): Serves as a long-term trend filter to ensure trades align with the overall market direction.
Volatility-Adjusted Moving Average (VMA):
A dynamic moving average that adjusts its sensitivity based on market volatility (using a Directional Movement Index-inspired calculation).
Length: Default 6 periods.
Colored green (uptrend), red (downtrend), or blue (neutral/sideways).
Optionally filters entries and exits to confirm trend direction.
Average True Range (ATR):
Measures volatility over a specified period (Default: 14).
Used to set adaptive stop-loss and take-profit levels.
Multipliers allow customization: Stop (Default: 1.5x ATR), Fixed Target (Default: 3.0x ATR), Trailing Target (Default: 2.0x ATR).
Supports trailing options for stops (based on highest/lowest since entry) and targets (ratcheting with price movement).
Signal Generation
Entry Signals
Buy (Long) Signal: Triggered when the price is above the Trend EMA (bullish alignment) and one of the following occurs:
Price crosses above the Trend EMA.
Price crosses above the Fast EMA, with Fast EMA > Slow EMA > Trend EMA.
Price crosses above the Slow EMA, with Fast EMA > Slow EMA > Trend EMA.
Filtered optionally by VMA being green (uptrend confirmation).
Visual: Green "BUY" label below the bar.
Sell (Short) Signal: Triggered when the price is below the Trend EMA (bearish alignment) and one of the following occurs:
Price crosses below the Trend EMA.
Price crosses below the Fast EMA, with Fast EMA < Slow EMA < Trend EMA.
Price crosses below the Slow EMA, with Fast EMA < Slow EMA < Trend EMA.
Filtered optionally by VMA being red (downtrend confirmation).
Visual: Red "SELL" label above the bar.
Exit Signals
Exit Long: Occurs when the position is active and:
Price crosses below the Stop EMA, or
Price hits the ATR stop-loss (fixed or trailing), or
Price reaches the ATR take-profit (fixed or trailing).
Filtered optionally by VMA > Stop EMA and VMA red (downtrend shift).
Visual: Green "E" label (exit) or "TP" label (if target hit).
Exit Short: Occurs when the position is active and:
Price crosses above the Stop EMA, or
Price hits the ATR stop-loss (fixed or trailing), or
Price reaches the ATR take-profit (fixed or trailing).
Filtered optionally by VMA < Stop EMA and VMA green (uptrend shift).
Visual: Red "E" label (exit) or "TP" label (if target hit).
The indicator tracks only one active position at a time (long or short), resetting on exit. Trailing stops update based on the highest high (long) or lowest low (short) since entry.
Visual Elements
How to Use ?
Setup: Add to your chart and adjust inputs based on your timeframe (e.g., shorter lengths for intraday, longer for swings).
Trading Strategy:
Enter on "BUY" or "SELL" labels when aligned with your broader analysis.
Monitor ATR lines for risk/reward: Aim for targets at least 2x stop distance.
Use trailing options in trending markets to lock in profits; fixed in ranging ones.
Combine with volume or other indicators for confirmation.
Risk Management: Always respect ATR stops to limit losses. Position size based on stop distance (e.g., 1-2% account risk).
Backtesting: Test on historical data to optimize parameters for your asset.
Alerts: Set up notifications for signals via TradingView's alert system. Examples:
"BUY signal triggered"
"EXIT long trade"
"Long ATR target reached on close"
Notes and Limitations
This is not financial advice; use at your own risk and combine with personal analysis.
Performance varies by market conditions—best in trending environments; may whipsaw in sideways markets.
Multi-timeframe requests may cause slight repainting on live charts due to higher TF data.
No repainting on closed bars, but ensure your chart timeframe is compatible with input TFs.
Licensed under Mozilla Public License 2.0. For questions or feedback, contact @MudraMiner.
This indicator empowers traders with a balanced, adaptive system—happy trading! 🚀
RSI by Tamil harmonic trader rajRSI Indicator will show RSI value on chart right side as per timeframe.
AI Fib Strategy (Full Trade Plan)This indicator automatically plots Fibonacci retracements and a Golden Zone box (61.8%–65% retracement) based on the 4H candle body high/low.
Features:
Auto-detects session breaks or daily breaks (configurable).
Draws standard Fib retracement levels (0%, 23.6%, 38.2%, 50%, 61.8%, 78.6%, 100%).
Highlights the Golden Zone for high-probability trade entries.
Optional Take Profit extensions (TP1, TP2, TP3).
Fully compatible with Pine Script v6.
Usage:
Best applied on intraday charts (15m, 30m, 1H).
Use the Golden Zone for entry confirmations.
Combine with candlestick patterns, order blocks, or volume for stronger signals.
🎁 <166> 25_0807 MACD DEMA TEMA DON + TURNOVER 통합신호Unified Signals
Each module (MACD, DEMA Ichimoku, TEMA Ichimoku, Donchian, Volume) can be enabled/disabled individually.
All conditions are combined into a single “all_conditions” logic.
If all active conditions are satisfied → bullish (buy).
If not → bearish (sell).
Buy/Sell labels, background fills, and candle colors are displayed.
Labels reset daily (new day → old labels deleted, new ones drawn).
Price Action Key Level Break & Retest — Instant ReversalThis script identifies high-confidence support and resistance levels using pivot points and multi-step retest confirmation. It helps traders detect reliable breakout and reversal zones using price action.
How It Works:
1. The script scans for pivot highs and lows on the chart to identify potential key levels.
2. Each level is monitored for multiple retests (configurable by the user). The more a level is tested and holds, the stronger it becomes.
3. When price interacts with a key level:
o A Support signal occurs if the level acts as support after multiple retests.
o A Resistance signal occurs if the level acts as resistance after multiple retests.
o If a signal fails (price breaks the level), an opposite signal is automatically placed at the breach point.
4. Optional volume filter validates the strength of moves, reducing false signals.
5. Horizontal Line Visualization: Support and Resistance signals are represented by drawing manually horizontal lines, which remain on the chart regardless of scrolling, zooming, or candle compression and helps traders to identify the breakout of key levels
Example:
• Suppose a stock forms a pivot low at ₹1,000.
• Price retraces and touches ₹1,000 two to three times, holding each time — the level is confirmed as strong support.
• The script places a buy line at ₹1,000.
• If price breaks below ₹1,000 after holding it for multiple retests, the script automatically generates a Resistance Signal at the breach point, signaling a potential trend reversal.
• That Resistance Signal act as Resistance level throughout. if such Resistance level breaks out above, it act as Support level and vice versa
• This allows traders to react adaptively, entering trades based on confirmed support or resistance while managing risk.
Why It’s Useful:
• Focuses on multi-retest confirmation rather than single touch points, reducing false signals.
• To draw horizontal lines on key levels, providing clear visualization of key levels without clutter.
• Integrates adaptive breach signals, so traders can respond when levels fail.
• Suitable for swing, intraday, and trend-following strategies.
How to Use:
1. Apply the script to any timeframe.
2. Configure pivot detection length and maximum retests to match trading style.
3. Enable the optional volume filter for stronger signal validation.
4. Monitor the horizontal lines for Support/Resistance signals and opposite signals at breaches.
5. Combine with other technical analysis if desired.
Concepts Behind the Script:
• Pivot-based support and resistance
• Multi-retest validation for stronger levels
• Adaptive opposite signals for failed levels
• Volume-based confirmation for reliability
• Horizontal line visualization for easy tracking
Key Features:
Horizontal Lines visualization: Support and Resistance levels remain on the chart permanently, providing constant visual reference.
Multi-Timeframe Compatible: Can be applied on any timeframe; lines and breach logic adjust automatically.
Optional Noise Filters: Volume and retest filters improve signal reliability.
Why It’s Worth Paying:
• Uses multi-retest confirmation to reduce false signals compared to standard support/resistance scripts.
• Provides adaptive opposite signals for failed levels — giving traders an actionable edge.
• Visualizes key levels as fixed horizontal lines, helping traders track trends clearly.
• Works across multiple timeframes — suitable for intraday, swing, or trend-following strategies.
How to Request Access:
This script is invite-only on TradingView. To get access:
1. DM me on TradingView with your username.
2. Access is granted individually to ensure proper use and avoid unauthorized sharing.
3. Once approved, you can apply the script to your charts immediately and benefit from high-confidence level detection.
Disclaimer:
Trading involves risk. Signals are based on historical price action and should be used alongside other technical analysis and risk management strategies.
Past performance does not guarantee future results. This is an analytical tool; it does not provide investment advice.
Impulse Convexity Trend Gate [T1][T69]OVERVIEW 🧭
• A price-only trend engine that opens a “gate” only when trend strength, acceleration, and impulse dominance align.
• Built from three cooperating parts: adaptive slope, directional convexity, and an impulse-vs-pullback ratio.
• Output is a bounded oscillator (−100…+100) plus side-specific gate states (bull/bear), with optional pullback and weakness highlights.
THE IDEA & USEFULNESS 🧪
• Not a simple mashup: each component plays a distinct role—slope for direction, convexity for acceleration agreement, and an impulse ratio to suppress correction noise.
• Adaptive EMA length (series-based) lets the midline adjust to conditions without external indicators.
• Approximation of hyperbolic tangent and clamp keep signals bounded and stable while avoiding library dependencies.
• Designed to help trend traders act only when continuation is likely, and stand down during pullbacks or chop.
HOW IT WORKS (PIPELINE) ⚙️
• Price transform
• Uses log price for scale stability.
• Adaptive midline
• Volatility-aware EMA length is clamped between minimum and maximum, then applied via a custom recursive EMA.
• Slope & convexity
• Slope (first difference of the midline) defines direction; convexity (second difference) verifies acceleration agrees with that direction.
• Impulse vs pullback ratio (R)
• Sums directional progress versus counter-direction pullbacks over a window; requires impulse to dominate.
• Normalization & score
• Slope and convexity are normalized by recent dispersion; combined into a raw score and squashed to −100…+100 using manual tanh.
• Trend gate
• Gate opens only when: R ≥ threshold, |normalized slope| ≥ threshold, and slope/convexity share the same sign.
• States & visuals
• Bull/Bear Gate Entry when gate is open, oscillator crosses ±15 in the correct direction, price is on the correct side of the midline, and slope/convexity agree.
• Pullbacks mark counter-moves while a gate is active; Weakness flags specific fade patterns after pullbacks.
FEATURES ✨
• Bull and Bear Gate Entries (green/red columns).
• Pullback shading and optional trend-weakness highlights (yellow/orange + teal/maroon).
• Background tint reflects the active side (bull or bear).
• Pure price logic; no volume or external filters required.
HOW TO USE 🎯
• Regime filter
• Trade only in the direction of the open gate; ignore signals when the gate is closed.
• Pullback entries
• During an open gate, wait for a pullback zone, then act on trend-resumption (e.g., oscillator re-push through ±15 or structure break in gate direction).
• Exits & risk
• Consider trimming when the oscillator relaxes toward 0 while the gate remains open, or when convexity flips against slope and R deteriorates.
• Timeframes & markets
• Suited for trend following on crypto/FX/indices from M30 to 4H/1D; raise thresholds on lower timeframes to reduce noise.
CONFIGURATION 🔧
• Impulse ratio gate (R ≥): raises/lowers the standard for continuation dominance.
• Slope strength gate (|sN| ≥): controls how strong a slope must be to count.
• Show Pullback Impulse (toggle): enable/disable pullback highlights.
• Show Trend Weakness (toggle): enable/disable weakness flags.
LIMITATIONS ⚠️
• As a trend tool, it can lag at regime transitions; expect whipsaws in tight ranges.
• Parameters are instrument- and timeframe-dependent; tune thresholds before live use.
• Pullback/weakness flags are contextual—not trade signals by themselves; use them with gate state and your execution rules.
ADVANCED TIPS 🛠️
• Tighten R and slope thresholds for lower timeframes; loosen for higher timeframes.
• Pair with NNFX-style money management and pair-level filters; let the gate be the confirmation layer, not the entry trigger by itself.
• Batch-test across 100+ symbols, export metrics, and run Monte Carlo to validate LLN reliability and Sharpe/IQR stability.
• For system hedging, disable entries when both sides trigger on the same asset to avoid internal conflict.
NOTES 📝
• Price-only construction reduces data-vendor differences and keeps behavior consistent across markets.
• Manual tanh/clamp ensure stable, bounded scores even during extremes.
DISCLAIMER 🛡️
• For research and education. No financial advice. Test thoroughly, size conservatively, and respect your risk rules.
Previous Day High & Low (PDH / PDL) with HistoryThis indicator automatically plots the Previous Day High (PDH) and Previous Day Low (PDL) on your chart.
✨ Features:
📅 Multiple days of history (choose how many days to keep, or unlimited).
🎨 Custom colors and line styles (solid, dashed, dotted).
🔎 Show or hide levels once touched by price.
🏷️ Optional labels (“PDH” and “PDL”) that follow the line to the right edge.
🚀 Works on any market, any timeframe.
🔧 Use cases:
Identify key liquidity levels.
Track daily ranges for intraday trading.
Combine with other strategies for confluence.
FibAlgo® - Perfect Entry Zone™FibAlgo® - Perfect Entry Zone™
OVERVIEW
FibAlgo® - Perfect Entry Zone™ is an advanced technical analysis tool that dynamically detects and visualizes support and resistance levels in the market. Instead of static levels, it draws smart "Entry Zones" that change their color and function based on price action. The indicator's core concept is based on the principle that when a resistance level is broken, it becomes support (and vice versa). It automatically captures these "Support/Resistance Flip" moments. Its most powerful feature is the built-in "Adaptive System," or "The Brain," which analyzes historical data to find the Fibonacci levels with the highest historical accuracy and optimizes them for you.
CONCEPTS
Effective use of this indicator comes from understanding its three underlying core concepts.
1. The Adaptive Analysis Engine ("The Brain"): This is the indicator's most powerful feature. Instead of using a fixed period, it intelligently tests numerous past market peaks and troughs to find which Fibonacci range has historically produced the most accurate reversal signals. What makes this system special is its use of a weighted scoring system that prioritizes finding the "Zone 1" (the 0.0-1.0 Fibonacci range) with the highest confidence. In short, the algorithm is optimized to find the most reliable initial reversal areas for you.
2. Dynamic Zones and the S/R Flip (Support/Resistance Flip): The colored boxes you see on the chart represent the dynamic battle between support and resistance. Their colors and states change according to price action.
Uptrend Scenario: As a trend begins, a RED box appears as potential resistance. If the price breaks through this red box to the upside, the trend's strength is confirmed, and the indicator flips the box's color to GREEN. This means the old resistance has now become new support. This new green box is now a potential LONG entry area on a price retest.
Downtrend Scenario: As a trend begins, a GREEN box appears as potential support. If the price breaks down through this green box, the trend's strength is validated, and the indicator flips the box's color to RED. This shows that the old support has now become new resistance. This new red box is now a potential SHORT entry area on a price retest.
3. Confidence Percentage (% Confidence): This percentage, displayed on each box, is a data-driven score that shows the historical significance of that price zone. It answers the question: "In the past, how often did the market react to this specific price area?" A higher percentage suggests the zone is more significant and noteworthy.
FEATURES
Intelligent Adaptive System ("The Brain"): A smart engine that automatically finds and optimizes the most suitable Fibonacci analysis period for the market.
Dynamic Support/Resistance Flip Zones: Visually intuitive entry zones that automatically change function and color (from red to green or green to red) based on price breakouts.
Data-Driven Confidence Score: A confidence rating that displays the historical importance and success rate of each zone as a percentage, aiding in decision-making.
Automatic Fibonacci Drawing: Automatically detects significant peaks and troughs (pivots) in the market and draws the relevant Fibonacci structure for you.
Comprehensive Visual Customization: The ability to adjust many visual elements to your personal preference, including trend lines, level lines, colors, label positions, and font sizes.
Built-in User Guide: A detailed user manual, viewable on the chart, that explains all the mechanics and strategies of the indicator.
USAGE
This indicator provides clear trading strategies based on the "Support/Resistance Flip" concept.
Long Entry Strategy:
Look for an uptrend in the market.
Wait for the price to decisively break above a RED resistance box.
Observe the box's color flipping to GREEN (new support) after the breakout.
Wait for a price pullback (retest) to this newly formed GREEN support box. This area is a potential long entry signal.
Short Entry Strategy:
Look for a downtrend in the market.
Wait for the price to decisively break below a GREEN support box.
Observe the box's color flipping to RED (new resistance) after the breakdown.
Wait for a price pullback (retest) to this newly formed RED resistance box. This area is a potential short entry signal.
Note : More aggressive traders can also use the zones as direct buy or sell signals, as they represent the most tested Fibonacci levels in the past. However, this approach is riskier and requires caution. Always use it in conjunction with your own risk management strategy.
CRoTLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum
AI Gold Liquidity Breakout CatcherTitle: Gold AI Liquidity Breakout Catcher
Description:
Indicator Philosophy and Originality:
This indicator is not merely a collection of separate tools, but an integrated trading framework designed to improve decision-making by ensuring signal confluence. The core philosophy is that high-probability trading signals occur when multiple, distinct analysis methodologies align.
The originality of this script lies in how it systematically combines a leading signal (the Liquidity Breakout) with multiple, independent lagging confirmation tools (the Classic Filters, the Hull MA, and the Range Filter). A user can see a primary breakout signal and immediately validate its strength against the broader trend defined by the Hull MA, the intermediate trend from the Range Filter, and the specific conditions of the classic filters.
This synergy, where different components work together to validate a single event, is the primary value and reason for this mashup. It provides a structured, multi-layered confirmation process within a single tool, which is not achievable by adding these indicators separately to the chart.
This indicator is a comprehensive technical analysis tool designed to identify potential trading opportunities and provide supplemental trend analysis. It features a primary signal engine based on pivot trendline breakouts, a sophisticated confirmation layer using classic technical indicators, and three separate modules for discretionary analysis: an ICT-based structure plotter, a highly customizable Hull Moving Average (HMA), and a volatility-adaptive Range Filter. This document provides a detailed, transparent explanation of all underlying logic.
1. Core Engine: Pivot-Based Liquidity Trendline Signals
The indicator's foundational signal is generated from a custom method we call "Liquidity Trendlines," which aims to identify potential shifts in momentum.
How It Works:
The script first identifies significant swing points in the price using ta.pivothigh() and ta.pivotlow().
It then draws a trendline connecting consecutive pivot points.
A "Liquidity Breakout" signal (liquidity_plup for buy, liquidity_pldn for sell) is generated when the price closes decisively across this trendline, forming the basis for a potential trade.
2. The Signal Confirmation Process: Multi-Layered Filtering System
A raw Liquidity Breakout signal is only a starting point. To enhance reliability, the signal must pass through a series of user-enabled filters. A final Buy or Sell signal is only plotted if all active filter conditions are met simultaneously.
General & Smart Trend Filters: Use a combination of EMAs, DMI (ADX), and market structure to define the trend.
RSI & MACD Filters: Used for momentum confirmation.
Directional Body Strength Filter: A custom filter that validates the signal based on the strength and direction of the signal candle's body (bodyUpOK / bodyDownOK).
Support & Resistance (S&R) Filter: Blocks signals forming too close to key S&R zones.
Higher Timeframe (HTF) Filter: Provides confluence by checking the trend on higher timeframes.
3. Visual Aid 1: ICT-Based Structure & Premium/Discount Zones
This module is for visual and discretionary analysis only and does not directly influence the automated Buy/Sell signals.
ICT Market Structure: Plots labels for CHoCH, SMS, and BMS based on a Donchian-channel-like logic.
ICT Premium & Discount Zones: When enabled, it draws colored zones corresponding to Premium, Discount, and Equilibrium levels.
4. Visual Aid 2: Hull Moving Average (HMA) Integration
This is another independent tool for trend analysis. It does not affect the primary signals but has its own alerts and serves as a powerful visual confirmation layer.
Functionality: Includes multiple Hull variations (HMA, THMA, EHMA), customizable colors based on trend, and the ability to pull data from a higher timeframe.
5. Visual Aid 3: Range Filter Integration
This module is a volatility-adaptive trend filter that provides its own set of signals and visuals. It is designed to be a standalone trend analysis tool integrated within the indicator for additional confluence.
How It Works: The Range Filter calculates a dynamic volatility threshold based on the average range of the price. A central filter line moves up or down only when the price exceeds this threshold, effectively filtering out market noise.
Visuals: It plots the central filter line and upper/lower bands that create a volatility channel. It can also color the price bars based on the trend.
Signals & Alerts: The Range Filter generates its own "Manual Buy" and "Manual Sell" signals when the price crosses the filter line after a change in trend direction. These signals have their own dedicated alerts.
6. Risk Management & Additional Features
TP/SL Calculations: Automatically calculates Take Profit and Stop Loss levels for the primary signals based on the ATR.
Multi-Timeframe (MTF) Scanner: A dashboard that monitors the final Buy/Sell signal status across multiple timeframes.
Session Filter & Alerts: Allows for restricting trades to specific market sessions and configuring alerts for any valid signal.
By combining breakout detection with a rigorous confirmation process and multiple supplemental analysis tools, this indicator provides a structured and transparent approach to trading.
Mag7 Day-Trade Recommender (Single-Symbol) [v6]Mag7 Day-Trade Recommender & Status Board
Intraday trading toolkit for the Magnificent Seven (AAPL, MSFT, NVDA, GOOGL, AMZN, TSLA, META). Signals are generated from VWAP crossovers confirmed by EMA50 trend and volume spikes, with automatic stops and targets (1R/2R). Includes a single-chart trade overlay and a multi-symbol scanner dashboard so you can instantly see which Mag7 names are in play.
Mag7 Day-Trade Recommender & Status Board (v6)📌 Mag7 Day-Trade Recommender & Status Board (v6)
Overview
This indicator system is designed to generate high-probability intraday trading signals on the Magnificent Seven stocks (AAPL, MSFT, NVDA, GOOGL, AMZN, TSLA, META). It combines price action with VWAP, EMA trend filters, and volume confirmation to highlight potential long and short setups.
It comes in two versions:
Day-Trade Recommender (single-symbol) – overlays on one chart, plotting entries, stops, and targets.
Status Board (multi-symbol scanner) – a dashboard table showing signal status across all Mag7 stocks at once.
Core Logic
VWAP Crossovers: Signals are triggered when price crosses above (LONG) or below (SHORT) VWAP.
EMA Trend Filter: Confirms trades only when price is aligned with the EMA50 slope (optional).
Volume Spike Filter: Requires current volume to exceed the 20-bar average by a set multiplier (default: 1.2×).
ATR-Based Risk/Reward: Stops are placed using ATR multiples, with profit targets set at 1R and 2R.
Session Filter: Optionally restricts signals to Regular Trading Hours (09:30–16:00).
****************** Note: Not financial advice. For educational purposes only. /b]*******************
Pullback IndicatorPullback Indicator
Plots a retracement level between a detected swing High and Low at a user-defined % (e.g., 38.2, 50, 61.8).
Formula: Level = Low + (High − Low) × (Pullback % / 100).
Merging Y-Axis into one
Once you add this indicator to the chart, you will see two Y-axes (or two price scales). Right-click on the price scales on the right, select “Merge all scales into one,” and choose “On the right.”
Modes
• Rolling → High/Low from last N bars on the chart’s timeframe. Recomputed every bar. Good for intraday, fast-adapting ranges.
• RollingDateRange → High/Low from a calendar window (Daily context). Options:
• RollDays = last N calendar days
• or Use Fixed Start Date (window expands day by day)
• Exclude Forming Day = ignore today’s incomplete daily candle for stable intraday levels.
Levels update once per daily bar unless today is included.
Inputs
• Pullback %
• Range Mode (Rolling | RollingDateRange)
• Lookback (bars)
• RollDays / Fixed Start Date
• Exclude Forming Day
• Show Pullback Label
Why range choice matters
Peak & trough are subjective—different windows give different High/Low. Select your window based on trading horizon:
• Intraday → Rolling (bars)
• Swing/position → RollingDateRange (days/fixed date)
How often are High/Low recomputed?
• Rolling (bars):
Recomputed on every bar of the chart’s timeframe using the most recent lookbackBars window. Levels can change frequently.
• RollingDateRange (Daily context):
Computed once per daily bar for the configured calendar window.
• With Exclude Forming Day = ON, the High/Low only update after the prior daily bar closes.
• With it OFF, the current (forming) daily bar can update the High/Low intraday if it sets a new extreme.
⸻
ATR Stoploss 15m with EMA Trend 1H - Dotted Fixeduse this as a basic ATR stoploss. It uses 100 and 20 EMA on 1hr to determine trend.
Scalp Sense AI# Scalp Sense AI (No Repaint)
**Adaptive trend & reversal detector with an AI-driven score, multi-timeframe confirmations, robust volume filters, and a purpose-built Scalping Mode.**
Signals are generated **only on bar close** (no repaint), include structured alert payloads for webhooks, and come with optional ATR-based TP/SL visualization for study and validation.
---
## What it is (in one paragraph)
**Scalp Sense AI** combines classic market structure (DI/ADX, EMA, SMA, Keltner, ATR) with a continuous **AI Score** that fuses RSI normalization, EMA distance (in ATR units), and DI edge into a single, volatility-aware signal. It adaptively gates **trend** and **reversal** entries, applies **HTF confirmation** without lookahead, and enforces **guard rails** (e.g., strong-trend reversal blocking) unless a high-confidence AI override and volume confirmation are present. **Scalping Mode** compresses reaction times and adds micro price-action cues (wick rejections, micro-EMA crosses, small engulfing) to surface more—but disciplined—opportunities.
---
## Non-Repainting Design
* All signals, markers, state, and alerts are computed **after bar close** using `barstate.isconfirmed`.
* HTF data are requested with `lookahead_off`.
* No “future-peeking” constructs are used.
* Result: signals do **not** change after the candle closes.
---
## How the engine works (pipeline overview)
1. **Base metrics**
* **RSI**, **EMA**, **ATR** (+ ATR SMA for regime/volatility), **SMA long & short**, **Keltner** (EMA ± ATR×mult).
* **Manual DI/ADX** for fine control (DM+, DM−, true range smoothing).
2. **Volatility regime**
* Compares ATR to its SMA and scales thresholds by √(ATR/ATR\_SMA) → robust “high\_vol” gating.
3. **Volume & flow**
* **Volume Z-score**, **OBV slope**, and **MFI** (all computed manually) to confirm impulses and filter weak reversals.
4. **Higher-Timeframe confirmation (optional)**
* Imports HTF **PDI/MDI/ADX** and **SMA** (no lookahead) to require alignment when enabled.
5. **AI Score**
* Weighted fusion of **RSI (normalized around 0)**, **EMA distance (in ATR)**, and **DI edge**.
* Smoothed; then its **mean (μ)** and **volatility (σ)** are estimated to form **adaptive bands** (hi/lo), with optional **hysteresis**.
* **Debounce** (M in N bars) avoids flicker; **bias state** persists until truly invalidated.
6. **Signal logic**
* **Trend entries** require AI bias + trend confirmations (DI/ADX/SMA, HTF if enabled), volatility OK, and **anti-breakout** filter.
* **Reversal entries** come in **core**, **early**, and **scalp** flavors (progressively more frequent), guarded by strong-trend blocks that an **AI+volume+ADX-cooling override** can bypass.
7. **Scalping Mode**
* Adaptive parameter contraction (shorter lengths), gentler guards, micro-patterns (wick/engulf/micro-EMA cross), and reduced cooldown to increase high-quality opportunities.
8. **Cooldown & state**
* One signal per side after a configurable spacing in bars; internal “last direction” avoids clustering.
9. **Visualization & alerts**
* **Triangles** for trend, **circles** for reversals (offset by ATR to avoid overlap).
* **Single-line alert payload** (BUY/SELL, reason, AI, volZ, ADX) ready for webhooks.
---
## Signals & visualization
* **Trend Long/Short** → triangle markers (above/below) when:
* AI bias aligns with trend confirmations (DI edge, ADX above threshold, price vs long SMA, optional HTF alignment).
* Volatility regime agrees; **anti-breakout** prevents entries exactly at lookback highs/lows.
* **Reversal Long/Short** → circular markers when:
* **Core**: AI near “loose” band, OBV/MFI/volZ supportive, ADX cooling, DI spread relaxed, PA confirms (crosses/div).
* **Early**: anticipatory patterns (Keltner exhaustion, simple RSI “quasi-divergence”).
* **Scalp**: micro-EMA cross, wick rejection, mini-engulfing, with relaxed guards but AI/volume still in the loop.
* **Markers appear only on the bar that actually emitted the signal** (no repaint); offsets use ATR so shapes don’t overlap.
---
## Alerts (ready for webhooks)
Enable “**Any alert() function call**” and you’ll receive compact, single-line payloads once per bar:
```
action=BUY;reason=reversal-early;ai=0.1375;volZ=0.82;adx=27.5
action=SELL;reason=trend;ai=-0.2210;volZ=0.43;adx=31.9
```
* `action`: BUY / SELL
* `reason`: `trend` | `reversal-core` | `reversal-early` | `reversal-scalp`
* `ai`: current smoothed AI Score at signal bar
* `volZ`: volume Z-score
* `adx`: current ADX
---
## Inputs (exhaustive)
### 1) Core Inputs
* **RSI Length (Base)** (`rsi_length_base`, int)
Base RSI lookback. Shorter = more reactive; longer = smoother.
* **RSI Overbought Threshold** (`rsi_overbought`, int)
Informational for context; RSI is used normalized in the AI fusion.
* **RSI Oversold Threshold** (`rsi_oversold`, int)
Informational; complements visual context.
* **EMA Length (Base)** (`ema_length_base`, int)
Primary adaptive mean; also used for Keltner mid and distance metric.
* **ATR Length (Base)** (`atr_length_base`, int)
Volatility unit for Keltner, SL/TP (debug), and regime detection.
* **ATR SMA Length** (`atr_sma_len`, int)
Smooth baseline for ATR regime; supports “high\_vol” logic.
* **ATR Multiplier Base** (`atr_mult_base`, float)
Scales volatility gating (sqrt-scaled); higher = tighter high-vol requirement.
* **Disable Volatility Filter** (`disable_volatility_check`, bool)
Bypass volatility gating if true.
* **Price Change Period (bars)** (`price_change_period_base`, int)
Simple momentum check (+/−% over N bars) used in trend validation.
* **Base Cooldown Bars Between Signals** (`signal_cooldown_base`, int ≥ 0)
Minimum bars to wait between signals (per side).
* **Trend Confirmation Bars** (`trend_confirm_bars`, int ≥ 1)
Require persistence above/below long SMA for this many bars.
* **Use Higher Timeframe Confirmation** (`use_higher_tf`, bool)
Turn on/off HTF alignment (no repaint).
* **Higher Timeframe for Confirmation** (`higher_tf`, timeframe)
E.g., “60” to confirm M15 with H1; used for HTF PDI/MDI/ADX and SMA.
* **TP as ATR Multiple** (`tp_atr_mult`, float)
For **visual debug** only (drawn after entries); not an order manager.
* **SL as ATR Multiple** (`sl_atr_mult`, float)
For visual debug only.
* **Enable Scalping Mode** (`scalping_mode`, bool)
Compresses lengths/thresholds, unlocks micro-PA modules, reduces cooldown.
* **Show Debug Lines** (`show_debug`, bool)
Plots AI bands, DI/ADX, EMA/SMA, Keltner, vol metrics, and TP/SL (debug).
### 2) AI Score & Thresholds
* **AI Score Smooth Len** (`ai_len`, int)
EMA smoothing over the raw fusion.
* **AI Volatility Window** (`ai_sigma_len`, int)
Window to estimate AI mean (μ) and standard deviation (σ).
* **K High (sigma)** (`ai_k_hi`, float)
Upper band width (σ multiplier) for strong threshold.
* **K Low (sigma)** (`ai_k_lo`, float)
Lower band width (σ multiplier) for loose threshold.
* **Debounce Window (bars)** (`ai_debounce_m`, int ≥ 1)
Rolling window length used by the confirm counter.
* **Min Bars>Thr in Window** (`ai_debounce_n`, int ≥ 1)
Minimum confirmations inside the debounce window to validate a state.
* **Use Hysteresis Thresholds** (`ai_hysteresis`, bool)
Requires crossing back past a looser band to exit bias → fewer whipsaws.
* **Weight DI Edge (0–1)** (`ai_weight_di`, float)
Importance of DI edge within the fusion.
* **Weight EMA Dist (0–1)** (`ai_weight_ema`, float)
Importance of EMA distance (in ATR units).
* **Weight RSI Norm (0–1)** (`ai_weight_rsi`, float)
Importance of normalized RSI.
* **Sensitivity (0–1)** (`sensitivity`, float)
Contracts/expands bands (higher = more sensitive).
### 3) Volume Filters
* **Volume MA Length** (`vol_ma_len`, int)
Baseline for volume Z-score.
* **Volume Z-Score Window** (`vol_z_len`, int)
Std-dev window for Z-score; larger = fewer volume “spikes”.
* **Reversal: Min Volume Z for confirm** (`vol_rev_min_z`, float)
Minimum Z required to validate reversals (adaptively relaxed in scalping).
* **OBV Slope Lookback** (`obv_slope_len`, int)
Rising/falling OBV over this window supports bull/bear confirmations.
* **MFI Length** (`mfi_len`, int)
Money Flow Index lookback (manual calculation).
### 4) Filters (Breakout / ADX / Reversal)
* **Enable Breakout Filter** (`enable_breakout_fil`, bool)
Avoid trend entries at lookback highs/lows.
* **Breakout Lookback Bars** (`breakout_lookback`, int ≥ 1)
Window for the anti-breakout guard.
* **Base ADX Length** (`adx_length_base`, int)
Lookback for DI/ADX smoothing (also adapted in Scalping Mode).
* **Base ADX Threshold** (`adx_threshold_base`, float)
Minimum ADX to validate trend context (scaled in Scalping Mode).
* **Enable Reversal Filter** (`enable_rev_filter`, bool)
Master switch for reversal logic.
* **Max ADX for Reversal** (`rev_adx_max`, float)
Hard cap: above this ADX, reversals are blocked (unless overridden by AI if allowed in Guards).
### 5) Reversal Guard (regime protection & overrides)
* **Strong Trend: ADX add-above Thr** (`guard_adx_add`, float)
Extra ADX above `adx_threshold` to mark “strong” trend.
* **Strong Trend: min DI spread** (`guard_spread_min`, float)
Minimum DI separation to consider a trend “dominant”.
* **Require ADX drop from window max (%)** (`guard_adx_drop_min_pct`, float 0–1)
ADX must drop at least this fraction from its window maximum to consider “cooling”.
* **Regime Window (bars)** (`guard_regime_len`, int ≥ 10)
Window over which ADX max is measured for the “cooling” check.
* **EMA Slope Lookback** (`guard_slope_len`, int ≥ 2)
EMA slope horizon used alongside Keltner for strong-trend identification.
* **Keltner Mult (ATR)** (`guard_kc_mult`, float)
Keltner width for strong trend bands and exhaustion checks.
* **HTF Reversal Block Mode** (`htf_block_mode`, string: `Off` | `On` | `AI-controlled`)
* `Off`: never block by HTF.
* `On`: block reversals whenever HTF is strong.
* `AI-controlled`: block **unless** AI+volume+ADX-cooling override criteria are met.
* **AI-controlled: allow AI override** (`ai_htf_override`, bool)
Enables the override mechanism in `AI-controlled` mode.
* **AI override multiplier (vs band\_hi)** (`ai_override_mult`, float)
Strength needed beyond the high band to count as “strong AI”.
* **AI override: min bars beyond strong thr** (`ai_override_min_bars`, int ≥ 1)
Debounce on the override itself.
### 6) Markers
* **Reversal Circle ATR Offset** (`rev_marker_offset_atr`, float ≥ 0)
Vertical offset for reversal circles; trend triangles use a separate (internal) offset.
### 7) Scalping Mode Tuning
* **Reversal aggressiveness (0–1)** (`scalp_rev_aggr`, float)
Higher = looser guards and stronger AI sensitivity.
* **Wick: body multiple (bull/bear)** (`scalp_wick_body_mult`, float)
Wick must be at least this multiple of body to count as rejection.
* **Wick: ATR multiple (min)** (`scalp_wick_atr_mult`, float)
Minimal wick length in ATR units.
* **Micro EMA factor (vs EMA base)** (`scalp_ema_fast_factor`, float 0.2–0.9)
Fast EMA length = base EMA × factor (rounded/int).
* **Relax breakout filter in scalping** (`scalp_breakout_relax`, bool)
Lets more trend entries through in scalping context.
### 8) ICT-style SMA (bases)
* **ICT SMA Long Length (Base)** (`sma_long_len_base`, int)
Long-term baseline for regime/trend.
* **ICT SMA Short1 Length (Base)** (`sma_short1_len_base`, int)
Short baseline for price-action crosses.
* **ICT SMA Short2 Length (Base)** (`sma_short2_len_base`, int)
Companion short baseline used in PA cross checks.
> **Adaptive “effective” values:** When **Scalping Mode** is ON, the script internally shortens multiple lengths (RSI/EMA/ATR/ADX/μσ windows, SMAs) and gently relaxes guards (ADX drop %, DI spread, volume Z, override thresholds), reduces cooldown/confirm bars, and optionally relaxes the breakout filter—so you get **more frequent but still curated** signals.
---
## Plots & debug (optional)
* DI+/DI−, ADX (curr + HTF), EMA, long SMA, Keltner up/down (when strong), AI Score, AI mean, AI bands (hi/lo; low plots only when hysteresis is on), Volume MA and Z-score, and ATR-based TP/SL guide (after entries).
* These are **study aids**; the indicator does not manage trades.
---
## Recommended use
* **Timeframes**:
* Scalping Mode: M1–M15.
* Standard Mode: M15–H1 (or higher).
* **Markets**: Designed for liquid FX, indices, metals, and large-cap crypto.
* **Chart type**: Standard candles recommended (Heikin-Ashi alters inputs and hence signals).
* **Alerts**: Use “Any alert() function call”. Parse the key/value payloads server-side.
---
## Good to know
* **Why some alerts don’t draw shapes retroactively**: markers are drawn **only on** the bar that emitted the signal (no repaint by design).
* **Why a reversal didn’t fire**: strong-trend guards + HTF block may have been active; check ADX, DI spread, Keltner position, EMA slope, and whether AI override criteria were met.
* **Too many / too few signals**: tune **Scalping Mode**, `signal_cooldown_base`, AI bands (`ai_k_hi/lo`, `sensitivity`), volume Z (`vol_rev_min_z`), and guards (`rev_adx_max`, `guard_*`).
---
## Disclaimer
This is an **indicator**, not a strategy or an execution system. It does not place, modify, or manage orders. Markets carry risk—validate on historical data and demo before any live decisions. No performance claims are made.
---
### Version
**Scalp Sense AI v11.5** — Adaptive AI bands with hysteresis/debounce, HTF no-lookahead confirmations, guarded reversal logic with AI override, full volume suite (Z, OBV slope, MFI), anti-breakout filter, and a dedicated Scalping Mode with micro-PA cues.