Change in State of Delivery CISD [AlgoAlpha]🟠 OVERVIEW
This script tracks how price “changes delivery” after failed attempts to push in one direction. It builds swing levels from pivots, watches for those levels to be wicked, and then checks if price delivers cleanly in the opposite direction. When the pattern meets the script’s tolerance rules, it marks a Change in State of Delivery (CISD). These CISD levels are drawn as origin lines and are used to spot shifts in intent, failed pushes, and continuation attempts. A CISD becomes stronger when it forms after opposing liquidity is swept within a defined lookback.
🟠 CONCEPTS
The script first defines structure using swing highs/lows. These levels act as potential liquidity points. When price wicks through a swing, the script registers a mitigation event. After this, it looks for a reversal-style candle sequence: a failed push, followed by a counter-move strong enough to pass a tolerance ratio. This ratio compares how far price expanded away from the failed attempt versus the counter-move that followed. If the ratio is high enough, this becomes a CISD. The idea is simple: liquidity interaction sets context , and the tolerance logic identifies actual intent . CISD levels and sweep markers combine these two ideas into a clean map of where delivery flipped.
🟠 FEATURES
Liquidity tracking: marks swing highs/lows and updates them until expiry
Liquidity sweep confirmation when CISD aligns with recent mitigations
Alert conditions for all key events: mitigations, CISDs, and strong CISDs
🟠 USAGE
Setup : Add the script to your chart. Use it on any timeframe where swing behavior matters. Set the Swing Period for how wide a pivot must be. Set Noise Filter to control how strict the CISD detection is. Liquidity Lookback defines how recent a wick must be to confirm a sweep.
Read the chart : Origin lines mark where the CISD began. A green line signals bullish intent; a red line signals bearish intent. ▲ and ▼ shapes show CISDs that form after liquidity is swept, these mark strong signals for potential entry. Swing dots show recent swing highs/lows. Candle colors follow the latest CISD trend.
Settings that matter : Increasing Swing Period produces fewer but stronger swings. Raising Noise Filter requires cleaner counter-moves and reduces false CISDs. Liquidity Lookback controls how strict the sweep confirmation is. Expiry Bars decides how long swing levels remain active.
Indicadores e estratégias
Fractals Trend [BigBeluga]🔵 OVERVIEW
Fractals Trend is a trend-following overlay that leverages fractal swing points to define dynamic support and resistance zones. By storing and averaging recent high and low fractals, it determines trend direction and plots a smooth band that flips depending on market bias—displaying support during uptrends and resistance during downtrends .
🔵 CONCEPTS
Fractal Swings: Fractals are identified using a customizable length. A high fractal forms when the current high is the highest in a range; a low fractal when the current low is the lowest.
Fractal Memory: The indicator keeps a rolling window of recent high and low fractals inside arrays, limited by the user-defined storage quantity.
switch
upperF => FracrtalsUpper.push(high )
lowerF => FracrtalsLower.push(low )
FracrtalsUpper.size() > fCount => FracrtalsUpper.shift()
FracrtalsLower.size() > fCount => FracrtalsLower.shift()
Trend Detection: Price crossing above the average, min/max or median high fractals signals an uptrend; crossing below average, min/max or median low fractals signals a downtrend.
Dynamic Band Plotting: Depending on the trend, the script plots the average of either the upper or lower fractals as a trailing support or resistance line.
Visual Confirmation: Fractal labels appear as triangle markers at highs and lows, providing additional structural context.
🔵 FEATURES
Automatically detects high and low fractals using customizable length.
Stores a defined number of fractals to smooth out noise and reduce false signals.
Flips trend bias dynamically with colored band and smooth transitions.
Plots fractal-based support in bullish trends, resistance in bearish trends.
Triangle markers show real-time fractal highs and lows.
Fully configurable visuals, color themes, and fractal detection logic.
Clean, non-intrusive overlay that works on any market or timeframe.
🔵 HOW TO USE
Use the colored band as a directional filter: green = uptrend (support), orange = downtrend (resistance).
Combine with entry signals or break/retest strategies when price approaches the band.
Use triangle markers to confirm structural swing points.
Adjust Fractals Length to tune sensitivity—shorter values detect quicker shifts, longer values reduce noise.
Change the fractal bands type to adapt trend detection to different market conditions.
Use in conjunction with momentum or volume tools for confluence.
🔵 CONCLUSION
Fractals Trend offers a lightweight, intuitive way to track market bias using price structure alone. Its smart switching logic and clean visuals make it a powerful tool for trend traders seeking structure-based dynamic S/R—without laggy moving averages or overcomplicated signals.
🔥 SMC Reversal Engine v3.5 – Clean FVG + DashboardSMC Reversal Engine v3.5 – Clean FVG + Dashboard
The SMC Reversal Engine is a precision-built Smart Money Concepts tool designed to help traders understand market structure the single most important foundation in reading price action. It reveals how institutions move liquidity, where structure shifts occur, and how Fair Value Gaps (FVGs) align with these changes to signal potential reversals or continuations.
Understanding How It Works
At its core, the script detects CHoCH (Change of Character) and BOS (Break of Structure)—the two key turning points in institutional order flow. A CHoCH shows that the market has reversed intent (for example, from bearish to bullish), while a BOS confirms a continuation of the current trend. Together, they form the backbone of structure-based trading.
To refine this logic, the engine uses fractal pivots clusters of candles that confirm swing highs and lows. Fractals filter out noise, identifying points where price truly changes direction. The script lets you set this sensitivity manually or automatically adapts it depending on the timeframe. Lower fractal sensitivity captures smaller intraday swings for scalpers, while higher sensitivity locks onto major swing structures for swing and position traders.
The dashboard gives you a real-time reading of the trend, the last high and low, and what the market is likely to do next—for example, “Expect HL” or “Wait for LH.” It even tracks the accuracy of these structure predictions over time, giving an educational feedback loop to help you learn price behavior.
Fair Value Gaps and Tap Entries
Fair Value Gaps (FVGs) mark moments when price moves too quickly, leaving inefficiencies that institutions often revisit. When price taps into an FVG, it often acts as a high-probability entry zone for reversals or continuations. The script automatically detects, extends, and deletes old FVGs, keeping only relevant zones visible for a clean chart.
Traders can enable markTapEntry to visually confirm when an FVG gets filled. This is a simple but powerful trigger that often aligns with CHoCH or BOS moments.
Recommended Settings for Different Traders
For Scalpers, use a lower HTF structure such as 1 minute or 5 minutes. Keep Auto Fractals on for faster reaction, and limit FVG zones to 2–3. This gives you a clean, real-time reflection of order flow.
For Intraday Traders, 15-minute to 1-hour structure gives the perfect balance between reactivity and stability. Fractal sensitivity around 3–5 captures the most actionable levels without excessive noise.
For Swing Traders, use 4-hour, 1-day, or even 3-day structure. The chart becomes smoother, showing higher-order CHoCH and BOS that define true institutional transitions. Combine this with EMA confirmation for higher conviction.
For Position or Macro Traders, select Weekly or Monthly structure. The dynamic label system expands automatically to keep more historical BOS/CHoCH points visible, allowing you to see long-term shifts clearly.
Educational Value
This indicator is built to teach traders how to see structure the way professionals and smart money do. You’ll learn to recognize how markets transition from one phase to another from accumulation to manipulation to expansion. Each CHoCH or BOS helps you decode where liquidity is being taken and where new intent begins.
The included SMC Quick Guide explains each structural cue right on your chart. Within days of using it, you’ll start noticing patterns that reveal how price really moves, instead of guessing based on indicators.
Settings and How to Use Them
Everything in the SMC Reversal Engine is designed to adapt to your trading style and help you read structure like a professional.
When you open the Inputs Panel, you’ll see sections like Fractal Settings, FVG Settings, Buy/Sell Confirmation, and Educational Tools.
Under Fractal Settings, you can choose the higher timeframe (HTF) that defines structure—from minutes to weeks. The Auto Fractal Sensitivity option automatically adjusts how tight or wide swing points are detected. Lower sensitivity captures short-term fluctuations (great for scalpers), while higher values filter noise and isolate major swing highs and lows (perfect for swing traders).
The Fair Value Gap (FVG) options manage imbalance zones—the footprints of institutional orders. You can show or hide these zones, extend them into the future, and control how long they remain before auto-deletion. The Mark Entry When FVG is Tapped option places a small label when price revisits the gap—a potential entry signal that aligns with smart money logic.
EMA Confirmation adds a layer of confluence. The script can automatically scale EMA lengths based on timeframe, or you can input your preferred values (for example, 9/21 for intraday, 50/200 for swing). Require EMA Crossover Confirmation helps filter false moves, keeping you trading only with aligned momentum.
The Educational section gives traders visual reinforcement. When enabled, you’ll see tags like HH (Higher High), HL (Higher Low), LH (Lower High), and LL (Lower Low). These show structure shifts in real time, helping you learn visually what market structure really means. The Cheat Sheet panel summarizes each term, always visible in the corner for quick reference.
Early Top Warnings use wick size and RSI divergence to signal when price may be overextended—a useful heads-up before potential CHoCH formations.
Finally, the Narrative and Accuracy System translates structure into simple English—messages like Trend Bullish → Wait for HL or BOS Bearish → Expect LL. Over time, you can monitor how accurate these expectations have been, training your pattern recognition and confidence.
Pro Tips for Getting the Most Out of the SMC Reversal Engine
1. Start on Higher Timeframes First: Begin on the 4H or Daily chart where structure is cleaner and signals have more weight. Then scale down for entries once you grasp directional intent.
2. Use FVGs for Context, Not Just Entries: Observe how price behaves around unfilled FVGs—they often act as magnets or barriers, offering insight into where liquidity lies.
3. Combine With HTF Bias: Always trade in the direction of your higher timeframe trend. A bullish weekly BOS means lower timeframes should ideally align bullishly for optimal setups.
4. Clean Charts = Clear Mind: Use Minimal Mode when focusing on price action, then toggle the educational tools back on to review structure for learning.
5. Don’t Chase Every CHoCH or BOS: Focus on significant breaks that align with broader context and liquidity sweeps, not minor fluctuations.
6. Accuracy Rate Is a Feedback Tool: Use the accuracy stat as a reflection of consistency—not a trade trigger.
7. Build Narrative Awareness: Read the on-chart narrative messages to reinforce structured thinking and stay disciplined.
8. Practice Replay Mode: Step through past structures to visually connect CHoCH, BOS, and FVG behavior. It’s one of the best ways to train pattern recognition.
Summary
* Detects CHoCH and BOS automatically with fractal precision
* Identifies and manages Fair Value Gaps (FVGs) in real time
* Displays a smart dashboard with accuracy tracking
* Adapts label visibility dynamically by timeframe
* Perfect for both learning and trading with institutional clarity
This tool isn’t about predicting the market—it’s about understanding it. Once you can read structure, everything else in trading becomes secondary.
Every Hour 1st FVG vTDLEvery Hour 1st FVG vTDL
For more information on how to trade FVG's, refer to Michael J. Huddleston aka The Inner Circle Trader as he is the guy who invented the concept after all.
x.com
www.youtube.com
I'm just vibing plz dont take down my indicator pinescript people plz and thank you
What It Shows:
This indicator displays the first Fair Value Gap (FVG) that appears during each hourly session, based on lower timeframe price action.
Core Concept:
Fair Value Gap (FVG) Detection:
Uses a 3-candle pattern to detect price gaps
Key Features:
1. Hourly Time-Based Filtering:
Divides the trading day into hourly blocks
Shows ONLY the first FVG(s) that appear in each hour
Resets tracking at the start of each new hour
Uses America/New_York timezone
2. Two Display Modes:
"First Only": Shows whichever FVG appears first per hour (bullish OR bearish)
Once one box appears, no more boxes for that hour
"Show Both": Shows first bullish AND first bearish FVG per hour
Displays the first bull FVG + the first bear FVG independently
3. Multi-Timeframe Support:
Lower Timeframe Selection: Choose 15-second, 1-minute, or 5-minute FVG detection
Works on ANY chart timeframe:
On 1-min chart: Uses direct candle data
On higher timeframes (5-min, 15-min, hourly, etc.): Fetches lower timeframe data to detect gaps
NOTE: YOU CAN NOT GO LOWER THAN THE TIME FRAME SELECTED FOR FVG IT WILL NOT WORK BECAUSE WE ARE REQUESTING DATA FROM A LOWER TIME FRAME, IF YOU ARE LOWER THAN THAT TIME FRAME YOU WILL GET:
Error on bar 0: The chart's timeframe must be greater or equal to the timeframe used with `request.security_lower_tf()`.
4. Visual Display:
Colored boxes mark the FVG zones:
Blue (default) = Bullish FVG
Red (default) = Bearish FVG
Box positioning:
Left edge: When the FVG formed
Right edge: End of that hour (HH:59:59)
Height: The actual gap size
5. Size Filtering:
Minimum gap size setting (default: 4 ticks)
Filters out tiny, insignificant gaps
Trading Logic Behind It:
The indicator helps identify the first imbalance of each hour by:
Highlighting where price moved too fast, leaving imbalances
Traders watch these zones for setups and entry models
Z-Fusion Oscillator | Lyro RSThe Z-Fusion Oscillator converts five momentum indicators into Z-scores and blends them into one normalized signal that adapts across markets.
By combining normalization, smoothing, and divergence detection, users can easily identify when momentum is accelerating, weakening, reversing, or entering extreme zones
🔶 USAGE
The Z-Fusion Oscillator is designed to give traders a unified reading of market momentum—removing the noise of comparing tools that normally run on different scales.
By transforming RSI, MACD histogram, Stochastic, Momentum, and Rate of Change into Z-scores, this tool standardizes all inputs, making trend strength and shifts easier to interpret.
A dual-line system (fast Z-fusion line + slower baseline) highlights turning points, while overbought/oversold bands and “X-marks” help traders spot exhaustion and potential reversals.
🔹 Unified Momentum Structure
The indicator’s core strength comes from combining five Z-scored signals into one average.
Which makes momentum behavior more consistent across assets, reduces false extremes, and highlights true shifts in trend conviction.
🔹 Divergence Detection
The tool includes fully integrated divergence detection:
Regular Bullish Divergence: Price makes a lower low while Z-Fusion forms a higher low.
Regular Bearish Divergence: Price makes a higher high while Z-Fusion forms a lower high
Bullish and bearish divergences are marked directly on the oscillator with labels and colored pivot connections, making hidden momentum shifts obvious.
🔹 Visual Extremes
Two sets of upper and lower Z-score thresholds help identify:
Extreme overbought surges
Extreme oversold drops
Reversal zones
Potential exhaustion conditions
Background coloring reinforces when the oscillator moves beyond major levels, helping traders quickly assess momentum pressure.
🔹 Detecting Momentum Anomalies
Z-scores allow the oscillator to highlight when market momentum behaves abnormally relative to its own recent history.
For example:
The oscillator reaching +1 or –1 after an extended trend may indicate a climax.
A sharp Z-score reversal within an extreme zone can signal a trend exhaustion or a corrective move.
Divergences often appear earlier due to normalization smoothing out indicator noise.
This makes the Z-Fusion Oscillator particularly useful for spotting subtle shifts in trend direction that traditional indicators may miss.
🔶 DETAILS
🔹 Composite Z-Score Framework
Each momentum tool is smoothed, normalized, and transformed:
RSI → EMA-smoothed, Z-scored
MACD histogram → Z-scored
Stochastic → EMA + SMA smoothing, then Z-scored
Momentum → EMA-smoothed, Z-scored
Rate of Change → EMA-smoothed, Z-scored
These are averaged into one composite Z-score to provide a consistent reading across assets and market conditions.
🔹 Fusion Trend Lines
Two lines serve as the core signal:
Fast Line (savg) – reacts quicker to trend changes
Slow Line (savg2) – acts as a baseline filter
Crossovers between these lines highlight momentum shifts, while their color reflects trend bias.
🔹 Overbought/Oversold Zones
Two upper and two lower Z-score thresholds define “zones”:
Upper zones highlight overheated momentum or potential bearish reversals
Lower zones highlight depressed momentum or potential bullish reversals
Filled regions and background colors help visually confirm extreme conditions.
🔹 Pivot-Based Divergence Engine
The script includes filtered pivot detection with customizable look-backs and range limits to ensure divergences are meaningful, not noise-driven.
🔶 SETTINGS
🔹 Indicator Settings
Source — Price series used for all calculations.
Z-Score Length — Lookback period for Z-score normalization.
Z-Score MA Length — Smoothing length for the fusion signal lines.
Overbought/Oversold Levels — Four customizable threshold lines.
Color Palette — Choose from preset themes or define custom colors.
🔹 RSI
Length — RSI calculation period.
EMA Smoothing Length — Smooths RSI before Z-score conversion.
🔹 MACD
Fast Length — Fast EMA length.
Slow Length — Slow EMA length.
Signal Line Length — MACD signal smoothing.
🔹 Stochastic
%K Length — Main stochastic length.
EMA Smoothing — Smooths %K for stability.
%D Length — Smoothing for the signal line.
🔹 Momentum
Length — Momentum lookback.
EMA Smoothing — Smooths momentum before Z-scoring.
🔹 Rate of Change
Length — ROC lookback.
EMA Smoothing — Smooths ROC values.
🔹 Divergence
Enable/Disable Divergence Detection — Toggle divergence engine.
Pivot Left/Right Lookback — Defines pivot detection sensitivity.
Detection Range Limits — Controls allowable range for divergence.
Bull/Bear Colors & Styling — Customize divergence visualization.
🔶 SUMMARY
The Z-Fusion Oscillator combines multiple momentum signatures into a single normalized signal, enabling traders to:
Identify reversals early
Detect momentum exhaustion
Spot bullish and bearish divergences
Track overbought/oversold conditions
Visualize trend strength with clarity
Whether you're a swing trader, intraday analyst, or trend-reversal hunter, the Z-Fusion Oscillator provides a powerful and adaptive way to read momentum.
Momentum Tide [Alpha Extract]A sophisticated momentum-based trend identification system that measures normalized price deviation from an EMA baseline using ATR scaling and hyperbolic tangent smoothing for precise trend state classification. Utilizing advanced signal processing with configurable neutral bands and slope sensitivity adjustments, this indicator delivers institutional-grade momentum analysis with continuous strength measurement and visual trend confirmation. The system's three-state classification (bullish, bearish, neutral) combined with dynamic color intensity scaling provides comprehensive market momentum assessment across varying volatility conditions.
🔶 Advanced Baseline Deviation Framework
Implements EMA-based baseline calculation with ATR-normalized deviation measurement to create volatility-adjusted momentum signals. The system calculates raw price deviation from the baseline, scales by ATR and slope sensitivity factor, then applies exponential smoothing for stable signal generation with reduced noise and false transitions.
// Core Momentum Calculation
Baseline = ta.ema(close, Baseline_Length)
ATR_Value = ta.atr(ATR_Length)
Raw_Deviation = (close - Baseline) / (ATR_Value * Slope_Scaler)
Signal = ta.ema(Raw_Deviation, Signal_Smoothing)
🔶 Hyperbolic Tangent Normalization Engine
Features sophisticated tanh transformation that clamps raw deviation signals into normalized -1 to +1 range for consistent interpretation across all market conditions. The system applies safe exponential calculations with value capping to prevent overflow while maintaining signal sensitivity, creating bounded momentum readings suitable for systematic threshold analysis.
// Tanh Normalization
Clamped_Signal = tanh(Signal) // Bounded to
Strength = abs(Clamped_Signal) // Momentum intensity
🔶 Three-State Classification System
Implements intelligent trend state determination using configurable neutral band thresholds to reduce whipsaw signals during ranging conditions. The system classifies market as bullish (+1) when momentum exceeds upper neutral band, bearish (-1) below lower neutral band, and neutral (0) within the band, providing clear directional bias with built-in consolidation recognition.
🔶 Dynamic Color Intensity Architecture
Provides advanced visual feedback through momentum strength-based color intensity modulation, where stronger trends display more opaque colors and weaker trends show increased transparency. The system dynamically adjusts color alpha values based on absolute momentum strength, creating intuitive visual representation of trend conviction across baseline, candles, and bars.
🔶 Trend Strength Meter Visualization
Features innovative horizontal gradient meter displaying real-time momentum position across bear-to-bull spectrum with 24-segment resolution. The system creates smooth color transitions from bearish red through neutral gray to bullish green, with arrow indicator showing precise momentum location for instant trend strength assessment without cluttering the price chart.
🔶 Intelligent Flip Detection System
Generates transition markers when trend state changes from neutral/bearish to bullish or neutral/bullish to bearish, with duplicate signal suppression to prevent marker clustering. The system tracks previous signal states and only plots new markers on genuine trend reversals, providing clean entry signal visualization for systematic trading approaches.
snapshot
🔶 Configurable Neutral Band Framework
Implements adjustable neutral zone width using ATR percentage parameters to optimize signal frequency for different trading styles and market conditions. Wider bands reduce flip frequency for position trading while tighter bands increase sensitivity for active trading strategies, enabling customization without code modification.
🔶 Slope Sensitivity Adjustment
Features slope scaler parameter that modulates ATR normalization factor, controlling signal smoothness versus responsiveness trade-off. Higher values create smoother momentum readings with fewer transitions while lower values increase snappiness for faster reaction to price changes, allowing optimization across different volatility regimes and timeframes.
🔶 Comprehensive Visual Integration
Provides multi-dimensional trend visualization through color-coded baseline overlay, momentum-synchronized candle coloring, and bar color modification with configurable display toggles. The system includes optional flip markers and strength meter with position control for complete chart integration without visual overload.
🔶 Performance Optimization Framework
Utilizes efficient calculation methods with optimized table management for strength meter updates and minimal computational overhead for real-time momentum processing. The system includes intelligent state tracking and safe mathematical operations to prevent errors during extreme market conditions while maintaining consistent performance.
🔶 Why Choose Momentum Tide ?
This indicator delivers sophisticated momentum-based trend analysis through normalized deviation measurement and intelligent three-state classification. Unlike traditional momentum oscillators that operate in separate windows, Momentum Tide integrates directly with price action through baseline overlay and candle coloring while providing the analytical depth of bounded momentum measurement. The system's combination of tanh normalization, configurable neutral bands, dynamic color intensity, and innovative strength meter makes it essential for traders seeking adaptive trend-following approaches with clear visual feedback across cryptocurrency, forex, and equity markets. The three-state system naturally filters ranging periods while the momentum strength measurement enables position sizing and confidence assessment for systematic trading strategies.
Pre-Market ORB Break and Retest - Institutional═══════════════════════════════════
PRE-MARKET ORB BREAK AND RETEST - INSTITUTIONAL
═══════════════════════════════════
Free professional Pre-Market Opening Range Breakout indicator from QuantCrawler - your AI-powered futures trading analysis platform.
Built as a free resource for the trading community. Support us at quantcrawler.com and on YouTube @AutomateWithAaron.
═══════════════════════════════════
📊 HOW IT WORKS
1. Captures the 8:00-8:15 AM ET pre-market range where institutional investors position
2. Draws OR High, OR Low, and Midpoint levels on your chart
3. Waits for market open at 9:30 AM EST before detecting breakouts
4. Fires LONG/SHORT entry signals when price retests the OR midpoint after breakout
═══════════════════════════════════
✓ FEATURES
- Runs on 1m or 5m charts - captures 15m pre-market range automatically
- Zone marked at 8:15 AM, trades trigger after 9:30 AM market open
- Universal - works on futures, forex, stocks, and crypto
- Customizable sessions - NY, London, Asia, or any custom timeframe
- Adjustable breakout distance to match your instrument
- Clean visual signals - only shows actionable entries
- Session end time stops monitoring after market close
═══════════════════════════════════
⚙️ SETTINGS
- Breakout Distance (Points): Distance outside OR zone to confirm breakout
- Timezone: Select your trading session
- Opening Range Time: Pre-market positioning window (default 8:00-8:15)
- Session End Time: When to stop monitoring (default 16:00)
═══════════════════════════════════
🎯 IDEAL FOR
Day traders who defend institutional positioning levels. The 8:00-8:15 AM range captures where smart money positions before retail market open, giving you an edge on key support/resistance zones.
═══════════════════════════════════
🚀 WANT MORE?
This indicator pairs perfectly with QuantCrawler's AI-powered chart analysis:
- Multi-timeframe futures analysis (15m/5m/1m scalping, 4H/1H/30m intraday, 1D/4H/1H swing)
- Precision entry points, stop losses, and profit targets
- Confidence scoring for every setup
- Covers futures, forex, and crypto markets
Visit quantcrawler.com to see how AI can level up your trading.
═══════════════════════════════════
⚠️ DISCLAIMER
This indicator is for educational purposes only. Past performance does not guarantee future results. Always use proper risk management and never risk more than you can afford to lose.
═══════════════════════════════════
Built with ❤️ by Aaron at QuantCrawler
quantcrawler.com | AI-Powered Futures Trading Analysis
Super momentum DBSISuper momentum DBSI: The Ultimate Guide
1. What is this Indicator?
The Super momentum DBSI is a "Consensus Engine." Instead of relying on a single line (like an RSI) to tell you where the market is going, this tool calculates 33 distinct technical indicators simultaneously for every single candle.
It treats the market like a democracy. It asks 33 mathematical "voters" (Momentum, Trend, Volume, Volatility) if they are Bullish or Bearish.
If 30 out of 33 say "Buy," the score is high (Yellow), and the trend is extremely strong.
If only 15 say "Buy," the score is low (Teal), and the trend is weak or choppy.
2. Visual Guide: How to Read the Numbers
The Scores
Top Number (Bears): Represents Selling Pressure.
Bottom Number (Bulls): Represents Buying Pressure.
The Colors (The Traffic Lights)
The colors are your primary signal. They tell you who is currently winning the war.
🟡 YELLOW (Dominance):
This indicates the Winning Side.
If the Bottom Number is Yellow, Bulls are in control.
If the Top Number is Yellow, Bears are in control.
🔴 RED (Weakness):
This appears on the Top. It means Bears are present but losing.
🔵 TEAL (Weakness):
This appears on the Bottom. It means Bulls are present but losing.
3. Trading Strategy
Scenario A: The "Strong Buy" (Long Entry)
The Setup: You are looking for a shift in momentum where Buyers overwhelm Sellers.
Watch the Bottom Number: Wait for it to turn Yellow.
Confirm Strength: Ensure the score is above 15 and rising (e.g., 12 → 18 → 22).
Check the Top: The Top Number should be Red and low (below 10).
Trigger: Enter on the candle close.
Scenario B: The "Strong Sell" (Short Entry)
The Setup: You are looking for Sellers to crush the Buyers.
Watch the Top Number: Wait for it to turn Yellow.
Confirm Strength: Ensure the score is above 15 and rising.
Check the Bottom: The Bottom Number should be Teal and low.
Trigger: Enter on the candle close.
Scenario C: The "No Trade Zone" (Choppy Market)
The Setup: The market is confused.
Visual: Top is Red, Bottom is Teal.
Meaning: NOBODY IS WINNING. There is no Yellow number.
Action: Do not trade. This usually happens during lunch hours, weekends, or right before big news. This filter alone will save you from many false breakouts.
4. What is Inside? (The 33 Indicators)
To give you confidence in the signals, here is exactly what the script is checking:
Group 1: Momentum (Oscillators)
Detects if price is moving fast.
RSI (Relative Strength Index)
CCI (Commodity Channel Index)
Stochastic
Williams %R
Momentum
Rate of Change (ROC)
Ultimate Oscillator
Awesome Oscillator
True Strength Index (TSI)
Stoch RSI
TRIX
Chande Momentum Oscillator
Group 2: Trend Direction
Detects the general path of the market.
13. MACD
14. Parabolic SAR
15. SuperTrend
16. ALMA (Moving Average)
17. Aroon
18. ADX (Directional Movement)
19. Coppock Curve
20. Ichimoku Conversion Line
21. Hull Moving Average
Group 3: Price Action
Detects where price is relative to averages.
22. Price vs EMA 20
23. Price vs EMA 50
24. Price vs EMA 200
Group 4: Volume & Force
Detects if there is money behind the move.
25. Money Flow Index (MFI)
26. On Balance Volume (OBV)
27. Chaikin Money Flow (CMF)
28. VWAP (Intraday)
29. Elder Force Index
30. Ease of Movement
Group 5: Volatility
Detects if price is pushing the outer limits.
31. Bollinger Bands
32. Keltner Channels
33. Donchian Channels
5. Pro Tips for Success
Don't Catch Knives: If the Bear score (Top) is Yellow and 25+, do not try to buy the dip. Wait for the Yellow score to break.
Exit Early: If you are Long and the Yellow Bull score drops from 28 to 15 in one candle, TAKE PROFIT. The momentum has died.
Use Higher Timeframes: This indicator works best on 15m, 1H, and 4H charts. On the 1m chart, it may be too volatile.
Volatility Signal-to-Noise Ratio🙏🏻 this is VSNR: the most effective and simple volatility regime detector & automatic volatility threshold scaler that somehow no1 ever talks about.
This is simply an inverse of the coefficient of variation of absolute returns, but properly constructed taking into account temporal information, and made online via recursive math with algocomplexity O(1) both in expanding and moving windows modes.
How do the available alternatives differ (while some’re just worse)?
Mainstream quant stat tests like Durbin-Watson, Dickey-Fuller etc: default implementations are ALL not time aware. They measure different kinds of regime, which is less (if at all) relevant for actual trading context. Mix of different math, high algocomplexity.
The closest one is MMI by financialhacker, but his approach is also not time aware, and has a higher algocomplexity anyways. Best alternative to mine, but pls modify it to use a time-weighted median.
Fractal dimension & its derivatives by John Ehlers: again not time aware, very low info gain, relies on bar sizes (high and lows), which don’t always exist unlike changes between datapoints. But it’s a geometric tool in essence, so this is fundamental. Let it watch your back if you already use it.
Hurst exponent: much higher algocomplexity, mix of parametric and non-parametric math inside. An invention, not a math entity. Again, not time aware. Also measures different kinds of regime.
How to set it up:
Given my other tools, I choose length so that it will match the amount of data that your trading method or study uses multiplied by ~ 4-5. E.g if you use some kind of bands to trade volatility and you calculate them over moving window 64, put VSNR on 256.
However it depends mathematically on many things, so for your methods you may instead need multipliers of 1 or ~ 16.
Additionally if you wanna use all data to estimate SNR, put 0 into length input.
How to use for regime detection:
First we define:
MR bias: mean reversion bias meaning volatility shorts would work better, fading levels would work better
Momo bias: momentum bias meaning volatility longs would work better, trading breakouts of levels would work better.
The study plots 3 horizontal thresholds for VSNR, just check its location:
Above upper level: significant Momo bias
Above 1 : Momo bias
Below 1 : MR bias
Below lower level: significant MR bias
Take a look at the screenshots, 2 completely different volatility regimes are spotted by VSNR, while an ADF does not show different regime:
^^ CBOT:ZN1!
^^ INDEX:BTCUSD
How to use as automatic volatility threshold scaler
Copy the code from the script, and use VSNR as a multiplier for your volatility threshold.
E.g you use a regression channel and fade/push upper and lower thresholds which are RMSEs multiples. Inside the code, multiply RMSE by VSNR, now you’re adaptive.
^^ The same logic as when MM bots widen spreads with vola goes wild.
How it works:
Returns follow Laplace distro -> logically abs returns follow exponential distro , cuz laplace = double exponential.
Exponential distro has a natural coefficient of variation = 1 -> signal to noise ratio defined as mean/stdev = 1 as well. The same can be said for Student t distro with parameter v = 4. So 1 is our main threshold.
We can add additional thresholds by discovering SNRs of Student t with v = 3 and v = 5 (+- 1 from baseline v = 4). These have lighter & heavier tails each favoring mean reversion or momentum more. I computed the SNR values you see in the code with mpmath python module, with precision 256 decimals, so you can trust it I put it on my momma.
Then I use exponential smoothing with properly defined alphas (one matches cumulative WMA and another minimizes error with WMA in moving window mode) to estimate SNR of abs returns.
…
Lightweight huh?
∞
Supply and Demand Zones [Clean v6]Supply and Demand Zones
Overview
The Supply and Demand Zones indicator is an automated market structure tool designed to identify high-probability Points of Interest (POI) on any asset or timeframe. Built using Pine Script v6, this script focuses on clarity and performance, providing traders with a clutter-free view of where institutional buying and selling pressure has previously occurred.
Unlike crowded indicators that overwhelm the chart, this script dynamically manages zones—drawing new ones as structure forms and automatically removing invalid zones as price breaks through them.
Key Features
Automated Zone Detection: Automatically identifies Supply (Resistance) and Demand (Support) zones based on Swing Highs and Swing Lows.
Dynamic Zone Management: Active zones extend to the right until price interacts with them.
Break of Structure (BOS) Logic: When price violates a zone (closes beyond the invalidation level), the zone is automatically removed and marked as "Broken" to keep the chart clean.
Zig Zag Structure: Includes an optional Zig Zag overlay to visualize market flow, Higher Highs, and Lower Lows.
ATR-Based Sizing: Zone width is calculated using the Average True Range (ATR), ensuring zones adapt to the asset's current volatility.
Pine Script v6: Optimized using the latest array and method functions for speed and stability.
How It Works
Zone Creation: The script looks for Pivot Highs and Lows based on your defined Swing Length.
Supply Zones (Red): Created at Swing Highs.
Demand Zones (Blue): Created at Swing Lows.
Zone Width: The height of the box is determined by the ATR multiplied by your Zone Width setting. This ensures the zone covers the "wick" area or the volatility range of the pivot.
Invalidation: If the price closes past the outer edge of a zone (the top of a Supply zone or bottom of a Demand zone), the script detects a break, removes the filled box, and leaves a subtle trace of the broken structure.
How to Use
Trend Following: Use the Zig Zag lines to identify the trend direction. Look for Long entries in Demand zones during an uptrend, and Short entries in Supply zones during a downtrend.
Reversals: Watch for price to react at older, unfilled zones (POIs) that align with major support/resistance levels.
Stop Loss Placement: The outer edge of the zone acts as a natural invalidation point. If price closes beyond it, the setup is typically invalidated.
Settings Guide
Swing Length: Determines the sensitivity of the pivot detection. Lower numbers find more local zones (scalping); higher numbers find major structural zones (swing trading).
Max Zones to Keep: Limits the number of historic zones displayed to prevent chart clutter.
Zone Width (ATR): Adjusts how thick the zones are. Increase this value if you want to capture wider wicks.
Visual Settings: Fully customizable colors for Supply, Demand, Borders, and Zig Zag lines.
Disclaimer
This tool is for informational and educational purposes only. It visualizes past price action and does not guarantee future performance. Always manage your risk appropriately.
15m ORB BREAK AND RETEST - MIDPOINT═══════════════════════════════════
15m ORB BREAK AND RETEST - MIDPOINT
═══════════════════════════════════
Free professional 15-minute Opening Range Breakout indicator from QuantCrawler - your AI-powered futures trading analysis platform.
Built as a free resource for the trading community. Support us at quantcrawler.com and on YouTube @AutomateWithAaron.
═══════════════════════════════════
📊 HOW IT WORKS
1. Captures the 15-minute Opening Range (default: 9:30-9:45 AM ET)
2. Draws OR High, OR Low, and Midpoint levels on your chart
3. Detects breakouts when price closes beyond the OR zone + your specified distance
4. Fires LONG/SHORT entry signals when price retests the OR midpoint after breakout
═══════════════════════════════════
✓ FEATURES
- Runs on 1m or 5m charts - captures 15m opening range automatically
- Universal - works on futures, forex, stocks, and crypto
- Customizable sessions - NY, London, Asia, or any custom timeframe
- Adjustable breakout distance to match your instrument
- Clean visual signals - only shows actionable entries
- Session end time stops monitoring after market close
═══════════════════════════════════
⚙️ SETTINGS
- Breakout Distance (Points): Distance outside OR zone to confirm breakout
- Timezone: Select your trading session
- Opening Range Time: First 15 minutes to capture (default 9:30-9:45)
- Session End Time: When to stop monitoring (default 16:00)
═══════════════════════════════════
🎯 IDEAL FOR
Day traders and swing traders who prefer wider opening ranges for reduced noise. The 15-minute OR provides more stable support/resistance levels compared to 5m setups.
═══════════════════════════════════
🚀 WANT MORE?
This indicator pairs perfectly with QuantCrawler's AI-powered chart analysis:
- Multi-timeframe futures analysis (15m/5m/1m scalping, 4H/1H/30m intraday, 1D/4H/1H swing)
- Precision entry points, stop losses, and profit targets
- Confidence scoring for every setup
- Covers futures, forex, and crypto markets
Visit quantcrawler.com to see how AI can level up your trading.
═══════════════════════════════════
⚠️ DISCLAIMER
This indicator is for educational purposes only. Past performance does not guarantee future results. Always use proper risk management and never risk more than you can afford to lose.
═══════════════════════════════════
Built with ❤️ by Aaron and QuantCrawler
quantcrawler.com | AI-Powered Futures Trading Analysis
Uptrick: Dynamic Z-Score DivergenceIntroduction
Uptrick: Dynamic Z-Score Divergence is an oscillator that combines multiple momentum sources within a Z-Score framework, allowing for the detection of statistically significant mean-reversion setups, directional shifts, and divergence signals. It integrates a multi-source normalized oscillator, a slope-based signal engine, structured divergence logic, a slope-adaptive EMA with dynamic bands, and a modular bar coloring system. This script is designed to help traders identify statistically stretched conditions, evolving trend dynamics, and classical divergence behavior using a unified statistical approach.
Overview
At its core, this script calculates the Z-Score of three momentum sources—RSI, Stochastic RSI, and MACD—using a user-defined lookback period. These are averaged and smoothed to form the main oscillator line. This normalized oscillator reflects how far short-term momentum deviates from its mean, highlighting statistically extreme areas.
Signals are triggered when the oscillator reverses slope within defined inner zones, indicating a shift in direction while the signal remains in a statistically stretched state. These mean-reversion flips (referred to as TP signals) help identify turning points when price momentum begins to revert from extended zones.
In addition, the script includes a divergence detection engine that compares oscillator pivot points with price pivot points. It confirms regular bullish and bearish divergence by validating spacing between pivots and visualizes both the oscillator-side and chart-side divergences clearly.
A dynamic trend overlay system is included using a Slope Adaptive EMA (SA-EMA). This trend line becomes more responsive when Z-Score deviation increases, allowing the trend line to adapt to market conditions. It is paired with ATR-based bands that are slope-sensitive and selectively visible—offering context for dynamic support and resistance.
The script includes configurable bar coloring logic, allowing users to color candles based on oscillator slope, last confirmed divergence, or the most recent signal of any type. A full alert system is also built-in for key signals.
Originality
The script is based on the well-known concept of Z-Score valuation, which is a standard statistical method for identifying how far a signal deviates from its mean. This foundation—normalizing momentum values such as RSI or MACD to measure relative strength or weakness—is not unique to this script and is widely used in quantitative analysis.
What makes this implementation original is how it expands the Z-Score foundation into a fully featured, signal-producing system. First, it introduces a multi-source composite oscillator by combining three momentum inputs—RSI, Stochastic RSI, and MACD—into a unified Z-Score stream. Second, it builds on that stream with a directional slope logic that identifies turning points inside statistical zones.
The most distinctive additions are the layered features placed on top of this normalized oscillator:
A structured divergence detection engine that compares oscillator pivots with price pivots to validate regular bullish and bearish divergence using precise spacing and timing filters.
A fully integrated slope-adaptive EMA overlay, where the smoothing dynamically adjusts based on real-time Z-Score movement of RSI, allowing the trend line to become more reactive during high-momentum environments and slower during consolidation.
ATR-based dynamic bands that adapt to slope direction and offer real-time visual zones for support and resistance within trend structures.
These features are not typically found in standard Z-Score indicators and collectively provide a unique approach that bridges statistical normalization, structure detection, and adaptive trend modeling within one script.
Features
Z-Score-based oscillator combining RSI, StochRSI, and MACD
Configurable smoothing for stable composite signal output
Buy/Sell TP signals based on slope flips in defined zones
Background highlighting for extreme outer bands
Inner and outer zones with fill logic for statistical context
Pivot-based divergence detection (regular bullish/bearish)
Divergence markers on oscillator and price chart
Slope-Adaptive EMA (SA-EMA) with real-time adaptivity based on RSI Z-Score
ATR-based upper and lower bands around the SA-EMA, visibility tied to slope direction
Configurable bar coloring (oscillator slope, divergence, or most recent signal)
Alerts for TP signals and confirmed divergences
Optional fixed Y-axis scaling for consistent oscillator view
The full setup mode can be seen below:
Input Parameters
General Settings
Full Setup: Enables rendering of the full visual system (lines, bands, signals)
Z-Score Lookback: Lookback period for normalization (mean and standard deviation)
Main Line Smoothing: EMA length applied to the averaged Z-Score
Slope Detection Index: Used to calculate directional flips for signal logic
Enable Background Highlighting: Enables visual region coloring in
overbought/oversold areas
Force Visible Y-Axis Scale: Forces max/min bounds for a consistent oscillator range
Divergence Settings
Enable Divergence Detection: Toggles divergence logic
Pivot Lookback Left / Right: Defines the structure of oscillator pivot points
Minimum / Maximum Bars Between Pivots: Controls the allowed spacing range for divergence validation
Bar Coloring Settings
Bar Coloring Mode:
➜ Line Color: Colors bars based on oscillator slope
➜ Latest Confirmed Signal: Colors bars based on the most recent confirmed divergence
➜ Any Latest Signal: Colors based on the most recent signal (TP or divergence)
SA-EMA Settings
RSI Length: RSI period used to determine adaptivity
Z-Score Length: Lookback for normalizing RSI in adaptive logic
Base EMA Length: Base length for smoothing before adaptivity
Adaptivity Intensity: Scales the smoothing responsiveness based on RSI deviation
Slope Index: Determines slope direction for coloring and band logic
Band ATR Length / Band Multiplier: Controls the width and responsiveness of the trend-following bands
Alerts
The script includes the following alert conditions:
Buy Signal (TP reversal detected in oversold zone)
Sell Signal (TP reversal detected in overbought zone)
Confirmed Bullish Divergence (oscillator HL, price LL)
Confirmed Bearish Divergence (oscillator LH, price HH)
These alerts allow integration into automation systems or signal monitoring setups.
Summary
Uptrick: Dynamic Z-Score Divergence is a statistically grounded trading indicator that merges normalized multi-momentum analysis with real-time slope logic, divergence detection, and adaptive trend overlays. It helps traders identify mean-reversion conditions, divergence structures, and evolving trend zones using a modular system of statistical and structural tools. Its alert system, layered visuals, and flexible input design make it suitable for discretionary traders seeking to combine quantitative momentum logic with structural pattern recognition.
Disclaimer
This script is for educational and informational purposes only. No indicator can guarantee future performance, and trading involves risk. Always use risk management and test strategies in a simulated environment before deploying with live capital.
Fib and Slope Trend Detector [EWT] + MTF Dashboard🚀 Overview
The Momentum Structure Trend Detector is a sophisticated trend-following tool that combines Price Velocity (Slope) with Market Structure (Fibonacci) to identify high-probability trend reversals and continuations.
Unlike traditional indicators that rely heavily on lagging moving averages, this script analyzes the speed of price action in real-time. It operates on the core principle of market structure: Impulse moves are fast and steep, while corrections are slow and shallow.
🧠 The Logic: Physics Meets Market Structure
This indicator determines the trend direction by calculating the Slope (Velocity) of price swings.
ZigZag Calculation: It first identifies market swings (Highs and Lows) using a standard pivot detection algorithm.
Slope Calculation: It calculates the velocity of every completed leg using the formula: $Slope = \frac{|Price Change|}{|Time Duration|}$.
Trend Definition:
Uptrend : If the previous Up-move was fast (Impulse) and the subsequent Down-move is slower (Correction), the market is primed for an uptrend.
Downtrend : If the previous Down-move was fast (Impulse) and the subsequent Up-move is slower (Correction), the market is primed for a downtrend.
🔥 Key Features
1. Aggressive Real-Time Detection (No Lag)
Most structure indicators wait for a "Higher High" to confirm a trend, which often leads to late entries. This script uses an Aggressive Live Slope calculation:
It compares the current developing slope of the live price action against the slope of the previous completed leg.
Result: As soon as the current move becomes "steeper" (faster) than the previous correction, the trend flips immediately. This allows you to catch the "meat" of the move before a new pivot is even confirmed.
2. Fibonacci Validity Filter
Momentum alone isn't enough; we need structural integrity.
The script calculates the 78.6% Retracement level of the impulse leg.
If a correction moves deeper than this Fibonacci limit (on a closing basis), the trend structure is considered "broken" or "invalid," and the indicator switches to a Neutral state. This filters out choppy/ranging markets.
3. Multi-Timeframe (MTF) Dashboard
A customizable dashboard on the chart allows for fractal analysis. You can view the trend state (UP/DOWN/NEUTRAL) across 9 different timeframes (1m to 1M) simultaneously.
Green Row : Uptrend
Red Row : Downtrend
Gray : Neutral/Indeterminate
4. Smart Visuals
Background Colo r: Changes dynamically (Teal for Bullish, Red for Bearish, Gray for Neutral) to give you an instant read of the market state.
Slope Labels : Displays the calculated numeric slope on the chart, helping you visualize the momentum difference between impulse and corrective waves.
Invalidation Levels : Automatically plots the invalidation line (Stop Loss level) based on the market structure.
🛠️ Settings & Inputs
Strategy Settings
Pivot Deviation Length : Sensitivity of the ZigZag calculation (Default: 5). Lower numbers = more sensitive to small swings.
Max Retracement % : The Fibonacci limit for a valid correction (Default: 78.6%).
Min Bars for Live Calc : To prevent noise, the script waits for this many bars after a pivot before calculating the "Live Slope" (Default: 3).
Dashboard Settings
Show Dashboard : Toggle the table on/off.
Timeframe Toggles : Enable/Disable specific timeframes (1m, 5m, 15m, 30m, 1H, 4H, 1D, 1W, 1M) to suit your trading style.
🎯 How to Use
Wait for Background Change : When the background turns Teal, it indicates that a corrective pullback has ended and a new impulse with high velocity has begun.
Check Invalidation : Look at the plotted Stop Loss Level. If price closes below this line, the trade idea is invalid.
Confirm with Dashboard : Use the table to ensure the higher timeframes (e.g., 1H, 4H) align with your current chart's direction for higher probability setups.
Disclaimer : This tool is designed for trend analysis and educational purposes. Past performance (momentum) is not indicative of future results. Always manage your risk.
Santhosh Trend-Change AlertsSanthosh Trend-Change Alerts : This indicator identifies potential trend change in market. i would suggest to use 1Min time frame with 75 Period ( Input). To have more accuracy on trading , add RSI Divergence (14) and Super trend (10,3)
Static K-means Clustering | InvestorUnknownStatic K-Means Clustering is a machine-learning-driven market regime classifier designed for traders who want a data-driven structure instead of subjective indicators or manually drawn zones.
This script performs offline (static) K-means training on your chosen historical window. Using four engineered features:
RSI (Momentum)
CCI (Price deviation / Mean reversion)
CMF (Money flow / Strength)
MACD Histogram (Trend acceleration)
It groups past market conditions into K distinct clusters (regimes). After training, every new bar is assigned to the nearest cluster via Euclidean distance in 4-dimensional standardized feature space.
This allows you to create models like:
Regime-based long/short filters
Volatility phase detectors
Trend vs. chop separation
Mean-reversion vs. breakout classification
Volume-enhanced money-flow regime shifts
Full machine-learning trading systems based solely on regimes
Note:
This script is not a universal ML strategy out of the box.
The user must engineer the feature set to match their trading style and target market.
K-means is a tool, not a ready made system, this script provides the framework.
Core Idea
K-means clustering takes raw, unlabeled market observations and attempts to discover structure by grouping similar bars together.
// STEP 1 — DATA POINTS ON A COORDINATE PLANE
// We start with raw, unlabeled data scattered in 2D space (x/y).
// At this point, nothing is grouped—these are just observations.
// K-means will try to discover structure by grouping nearby points.
//
// y ↑
// |
// 12 | •
// | •
// 10 | •
// | •
// 8 | • •
// |
// 6 | •
// |
// 4 | •
// |
// 2 |______________________________________________→ x
// 2 4 6 8 10 12 14
//
//
//
// STEP 2 — RANDOMLY PLACE INITIAL CENTROIDS
// The algorithm begins by placing K centroids at random positions.
// These centroids act as the temporary “representatives” of clusters.
// Their starting positions heavily influence the first assignment step.
//
// y ↑
// |
// 12 | •
// | •
// 10 | • C2 ×
// | •
// 8 | • •
// |
// 6 | C1 × •
// |
// 4 | •
// |
// 2 |______________________________________________→ x
// 2 4 6 8 10 12 14
//
//
//
// STEP 3 — ASSIGN POINTS TO NEAREST CENTROID
// Each point is compared to all centroids.
// Using simple Euclidean distance, each point joins the cluster
// of the centroid it is closest to.
// This creates a temporary grouping of the data.
//
// (Coloring concept shown using labels)
//
// - Points closer to C1 → Cluster 1
// - Points closer to C2 → Cluster 2
//
// y ↑
// |
// 12 | 2
// | 1
// 10 | 1 C2 ×
// | 2
// 8 | 1 2
// |
// 6 | C1 × 2
// |
// 4 | 1
// |
// 2 |______________________________________________→ x
// 2 4 6 8 10 12 14
//
// (1 = assigned to Cluster 1, 2 = assigned to Cluster 2)
// At this stage, clusters are formed purely by distance.
Your chosen historical window becomes the static training dataset , and after fitting, the centroids never change again.
This makes the model:
Predictable
Repeatable
Consistent across backtests
Fast for live use (no recalculation of centroids every bar)
Static Training Window
You select a period with:
Training Start
Training End
Only bars inside this range are used to fit the K-means model. This window defines:
the market regime examples
the statistical distributions (means/std) for each feature
how the centroids will be positioned post-trainin
Bars before training = fully transparent
Training bars = gray
Post-training bars = full colored regimes
Feature Engineering (4D Input Vector)
Every bar during training becomes a 4-dimensional point:
This combination balances: momentum, volatility, mean-reversion, trend acceleration giving the algorithm a richer "market fingerprint" per bar.
Standardization
To prevent any feature from dominating due to scale differences (e.g., CMF near zero vs CCI ±200), all features are standardized:
standardize(value, mean, std) =>
(value - mean) / std
Centroid Initialization
Centroids start at diverse coordinates using various curves:
linear
sinusoidal
sign-preserving quadratic
tanh compression
init_centroids() =>
// Spread centroids across using different shapes per feature
for c = 0 to k_clusters - 1
frac = k_clusters == 1 ? 0.0 : c / (k_clusters - 1.0) // 0 → 1
v = frac * 2 - 1 // -1 → +1
array.set(cent_rsi, c, v) // linear
array.set(cent_cci, c, math.sin(v)) // sinusoidal
array.set(cent_cmf, c, v * v * (v < 0 ? -1 : 1)) // quadratic sign-preserving
array.set(cent_mac, c, tanh(v)) // compressed
This makes initial cluster spread “random” even though true randomness is hardly achieved in pinescript.
K-Means Iterative Refinement
The algorithm repeats these steps:
(A) Assignment Step, Each bar is assigned to the nearest centroid via Euclidean distance in 4D:
distance = sqrt(dx² + dy² + dz² + dw²)
(B) Update Step, Centroids update to the mean of points assigned to them. This repeats iterations times (configurable).
LIVE REGIME CLASSIFICATION
After training, each new bar is:
Standardized using the training mean/std
Compared to all centroids
Assigned to the nearest cluster
Bar color updates based on cluster
No re-training occurs. This ensures:
No lookahead bias
Clean historical testing
Stable regimes over time
CLUSTER BEHAVIOR & TRADING LOGIC
Clusters (0, 1, 2, 3…) hold no inherent meaning. The user defines what each cluster does.
Example of custom actions:
Cluster 0 → Cash
Cluster 1 → Long
Cluster 2 → Short
Cluster 3+ → Cash (noise regime)
This flexibility means:
One trader might have cluster 0 as consolidation.
Another might repurpose it as a breakout-loading zone.
A third might ignore 3 clusters entirely.
Example on ETHUSD
Important Note:
Any change of parameters or chart timeframe or ticker can cause the “order” of clusters to change
The script does NOT assume any cluster equals any actionable bias, user decides.
PERFORMANCE METRICS & ROC TABLE
The indicator computes average 1-bar ROC for each cluster in:
Training set
Test (live) set
This helps measure:
Cluster profitability consistency
Regime forward predictability
Whether a regime is noise, trend, or reversion-biased
EQUITY SIMULATION & FEES
Designed for close-to-close realistic backtesting.
Position = cluster of previous bar
Fees applied only on regime switches. Meaning:
Staying long → no fee
Switching long→short → fee applied
Switching any→cash → fee applied
Fee input is percentage, but script already converts internally.
Disclaimers
⚠️ This indicator uses machine-learning but does not predict the future. It classifies similarity to past regimes, nothing more.
⚠️ Backtest results are not indicative of future performance.
⚠️ Clusters have no inherent “bullish” or “bearish” meaning. You must interpret them based on your testing and your own feature engineering.
Cloud MasterSwap Between Traditional, Crypto and AI Ichimoko Cloud Settings with one Indicator. You can also input your own custom settings if you're a brainiac.
1H & 15M Swing Liquidity BSL / SSL (Projected to Lower TFs)I created this script to plot 1H intermediate and 15m short term liquidity on the lower timeframe charts. Works best when used with high timeframe keylevels as a catalyst to move price to these liquidity zones.
Trinity KST (known sure thing) ProThis version is the **modern, low-lag evolution** of Martin Pring’s original 1990s KST.
Key differences from the classic KST
- Original uses only simple moving averages (SMA) on the four ROCs → quite a bit of lag.
- This version lets you replace every SMA with **ALMA, HEMA, TEMA, or EMA** → dramatically reduces lag while keeping the signal smooth and reliable.
- ALMA + progressive offset (0.90–0.97) is especially powerful because longer-term ROCs react almost as fast as the short ones without getting noisy.
- Histogram, clean labels inside the oscillator pane, alerts, background tint — all the quality-of-life stuff the original never had.
How traders actually use it in >2026
1. Primary signal: KST crosses above/below the red signal line = momentum shift (bullish/bearish).
2. Zero-line cross = confirmation of trend change (especially strong on daily/weekly).
3. Divergences between price and KST = high-probability reversals (works great on BTC, SPX, NAS100).
4. Histogram turning from red to green (or vice-versa) = early warning before the actual line cross.
Best settings I and many others run live right now (no table, just the winners)
- Crypto & Nasdaq: **ALMA + aggressiveness 0.93–0.96** → fastest valid signals.
- Forex pairs & Gold: **HEMA** (zero-lag Hull) → super clean, almost no whipsaw.
- Broad stock indices (SPX, DAX, etc.): **ALMA 0.91–0.93** or **TEMA** → perfect middle ground.
- Classic conservative daily/weekly swings: leave it on **SMA** (original Pring) or ALMA 0.88–0.90.
In short: same reliable KST logic you already know, but now it reacts 6–12 bars earlier and with far fewer fakeouts — exactly what you need in today’s fast markets.
Support & Resistance Zone Hunter [BOSWaves]Support & Resistance Zone Hunter - Dynamic Structural Zones with Real-Time Breakout Intelligence
Overview
The Support & Resistance Zone Hunter is a professional-grade structural mapping framework designed to automatically detect high-probability support and resistance areas in real time. Unlike traditional static levels or manually drawn zones, this system leverages pivot detection, range thresholds, and optional volume validation to create dynamic zones that reflect the true structural architecture of the market.
Zones evolve as price interacts with their boundaries. The first touch of a zone determines its bias - bullish, bearish, or neutral - and the system tracks the full lifecycle of each zone from formation, testing, and bias establishment to potential breakout events. Diamond-shaped breakout signals highlight structurally significant price expansions while filtering noise using a configurable cooldown period.
By visualizing market structure in this way, traders gain a deeper understanding of price behavior, trend momentum, and areas where liquidity and reactive forces are concentrated.
Theoretical Foundation
The Support & Resistance Zone Hunter is built on the premise that meaningful structural zones arise from two core principles:
Pivot-Based Turning Points : Only significant highs and lows that represent actual swings in price are considered.
Contextual Validation : Zones must pass minimum range criteria and optional volume thresholds to ensure their relevance.
Markets naturally generate numerous micro-pivots that do not carry predictive significance. By filtering out minor swings and validating zones against volume and range, the system isolates levels that are more likely to attract future price interaction or act as catalysts for breakout moves.
This framework captures not only where price is likely to react but also the direction of potential pressure, providing a statistically grounded, visually intuitive representation of market structure.
How It Works
The Support & Resistance Zone Hunter constructs zones through a multi-layered process that blends pivot logic, range validation, and real-time bias determination:
1. Pivot Detection Core
The indicator identifies pivot highs and pivot lows using a configurable lookback period. Zones are only considered valid when both a top and bottom pivot are present.
2. Zone Qualification Engine
Prospective zones must satisfy two conditions:
Range Threshold : The distance between pivot high and low must exceed the minimum percentage set by the user.
Volume Requirement : If enabled, the current volume must exceed the 50-period moving average.
Only zones meeting these criteria are drawn, reducing noise and emphasizing high-probability structural levels.
3. Zone Lifecycle
Once a valid top and bottom pivot exist:
The zone is created starting from the pivot formation bar.
Zones remain active until both boundaries have been touched by price.
The first boundary touched establishes bias: resistance first → bullish bias ,support first → bearish bias, neither → neutral.
Inactive zones stop expanding but remain visible historically to maintain a clear structural context.
4. Visual Rendering
Active zones are displayed as filled boxes with color corresponding to their bias. Top, bottom, and midpoint lines are drawn for reference. Once a zone becomes inactive, its lines are removed while the filled box remains as a historical footprint.
5. Breakout Detection
Breakout signals occur when price closes above the top boundary or below the bottom boundary of an active zone. The system applies a cooldown period and requires price to return to the zone since the previous breakout to prevent signal spam. Bullish and bearish breakouts are visually represented by diamond-shaped markers with configurable colors.
Interpretation
The Support & Resistance Zone Hunter provides a structural view of market balance:
Bullish Zones : Form when resistance is tested first, indicating upward pressure and potential continuation.
Bearish Zones : Form when support is tested first, reflecting downward pressure and continuation risk.
Neutral Zones : Fresh zones that have not yet been interacted with, representing undiscovered liquidity.
Breakout Diamonds : Highlight significant structural price expansions, helping traders identify confirmed continuation moves while filtering noise.
Zones do not simply indicate past levels; they dynamically reflect the evolving battle between buyers and sellers, providing actionable context for both trend continuation and reversion strategies.
Strategy Integration
The Support & Resistance Zone Hunter is versatile and can be applied across multiple trading approaches:
Trend Continuation : Use bullish and bearish zones to confirm directional bias. Breakout diamonds indicate structural continuation opportunities.
Reversion Entries : Neutral zones often act as magnets in ranging markets, allowing for high-probability mean-reversion setups.
Breakout Trading : Diamonds mark true structural expansions, reducing false breakout risk and guiding stop placement or momentum entries.
Liquidity Zone Alignment : Combining the indicator with order block, breaker, or volume-based tools helps validate zones against broader market participation.
Technical Implementation Details
Pivot Engine : Two-sided pivot detection based on configurable lookback.
Zone Qualification : Minimum range requirement and optional volume filter.
Bias Logic : Determined by the first boundary touched.
Zone Lifecycle : Active until both boundaries are touched, historical visibility retained.
Breakout Signals : Diamond markers with cooldown filtering and price-return validation.
Visuals : Transparent filled zones with live top, bottom, and midpoint lines.
Suggested Optimal Parameters
Pivot Lookback : 10 - 30 for intraday, 20 - 50 for swing trading.
Minimum Range % : 0.5 - 2% for crypto or indices, 1 - 3% for metals or forex.
Volume Filter : Enable for assets with inconsistent liquidity; disable for consistently liquid markets.
Breakout Cooldown : 5 - 20 bars depending on volatility.
These suggested parameters should be used as a baseline; their effectiveness depends on the asset and timeframe, so fine-tuning is expected for optimal performance.
Performance Characteristics
High Effectiveness:
Markets with clear pivot structure and reliable volume.
Trending symbols with consistent retests.
Assets where zones attract repeated price interaction.
Reduced Effectiveness:
Random walk markets lacking structural pivots.
Low-volatility periods with minimal price reaction.
Assets with irregular volume distribution or erratic price action.
Integration Guidelines
Use zone color as contextual bias rather than a standalone signal.
Combine with structural tools, order blocks, or volume-based indicators for confluence.
Validate zones on higher timeframes to refine lower timeframe entries.
Treat breakout diamonds as confirmation of continuation rather than independent triggers.
Disclaimer
The Support & Resistance Zone Hunter provides structural zone mapping and breakout analytics. It does not predict price movement or guarantee profitability. Success requires disciplined risk management, proper parameter calibration, and integration into a comprehensive trading strategy.
Luxy Super-Duper SuperTrend Predictor Engine and Buy/Sell signalA professional trend-following grading system that analyzes historical trend
patterns to provide statistical duration estimates using advanced similarity
matching and k-nearest neighbors analysis. Combines adaptive Supertrend with
intelligent duration statistics, multi-timeframe confluence, volume confirmation,
and quality scoring to identify high-probability setups with data-driven
target ranges across all timeframes.
Note: All duration estimates are statistical calculations based on historical data, not guarantees of future performance.
WHAT MAKES THIS DIFFERENT
Unlike traditional SuperTrend indicators that only tell you trend direction, this system answers the critical question: "What is the typical duration for trends like this?"
The Statistical Analysis Engine:
• Analyzes your chart's last 15+ completed SuperTrend trends (bullish and bearish separately)
• Uses k-nearest neighbors similarity matching to find historically similar setups
• Calculates statistical duration estimates based on current market conditions
• Learns from estimation errors and adapts over time (Advanced mode)
• Displays visual duration analysis box showing median, average, and range estimates
• Tracks Statistical accuracy with backtest statistics
Complete Trading System:
• Statistical trend duration analysis with three intelligence levels
• Adaptive Supertrend with dynamic ATR-based bands
• Multi-timeframe confluence analysis (6 timeframes: 5M to 1W)
• Volume confirmation with spike detection and momentum tracking
• Quality scoring system (0-70 points) rating each setup
• One-click preset optimization for all trading styles
• Anti-repaint guarantee on all signals and duration estimates
METHODOLOGY CREDITS
This indicator's approach is inspired by proven trading methodologies from respected market educators:
• Mark Minervini - Volatility Contraction Pattern (VCP) and pullback entry techniques
• William O'Neil - Volume confirmation principles and institutional buying patterns (CANSLIM methodology)
• Dan Zanger - Volatility expansion entries and momentum breakout strategies
Important: These are educational references only. This indicator does not guarantee any specific trading results. Always conduct your own analysis and risk management.
KEY FEATURES
1. TREND DURATION ANALYSIS SYSTEM - The Core Innovation
The statistical analysis engine is what sets this indicator apart from standard SuperTrend systems. It doesn't just identify trend changes - it provides statistical analysis of potential duration.
How It Works:
Step 1: Historical Tracking
• Automatically records every completed SuperTrend trend (duration in bars)
• Maintains separate databases for bullish trends and bearish trends
• Stores up to 15 most recent trends of each type
• Captures market conditions at each trend flip: volume ratio, ATR ratio, quality score, price distance from SuperTrend, proximity to support/resistance
Step 2: Similarity Matching (k-Nearest Neighbors)
• When new trend begins, system compares current conditions to ALL historical flips
• Calculates similarity score based on:
- Volume similarity (30% weight) - Is volume behaving similarly?
- Volatility similarity (30% weight) - Is ATR/volatility similar?
- Quality similarity (20% weight) - Is setup strength comparable?
- Distance similarity (10% weight) - Is price distance from ST similar?
- Support/Resistance proximity (10% weight) - Similar structural context?
• Selects the 15 MOST SIMILAR historical trends (not just all trends)
• This is like asking: "When conditions looked like this before, how long did trends last?"
Step 3: Statistical Analysis
• Calculates median duration (most common outcome)
• Calculates average duration (mean of similar trends)
• Determines realistic range (min to max of similar trends)
• Applies exponential weighting (recent trends weighted more heavily)
• Outputs confidence-weighted statistical estimate
Step 4: Advanced Intelligence (Advanced Mode Only)
The Advanced mode applies five sophisticated multipliers to refine estimates:
A) Market Structure Multiplier (±30%):
• Detects nearby support/resistance levels using pivot detection
• If flip occurs NEAR a key level: Estimate adjusted -30% (expect bounce/rejection)
• If flip occurs in open space: Estimate adjusted +30% (clear path for continuation)
• Uses configurable lookback period and ATR-based proximity threshold
B) Asset Type Multiplier (±40%):
• Adjusts duration estimates based on asset volatility characteristics
• Small Cap / Biotech: +40% (explosive, extended moves)
• Tech Growth: +20% (momentum-driven, longer trends)
• Blue Chip / Large Cap: 0% (baseline, steady trends)
• Dividend / Value: -20% (slower, grinding trends)
• Cyclical: Variable based on macro regime
• Crypto / High Volatility: +30% (parabolic potential)
C) Flip Strength Multiplier (±20%):
• Analyzes the QUALITY of the trend flip itself
• Strong flip (high volume + expanding ATR + quality score 60+): +20%
• Weak flip (low volume + contracting ATR + quality score under 40): -20%
• Logic: Historical data shows that powerful flips tend to be followed by longer trends
D) Error Learning Multiplier (±15%):
• Tracks Statistical accuracy over last 10 completed trends
• Calculates error ratio: (estimated duration / Actual Duration)
• If system consistently over-estimates: Apply -15% correction
• If system consistently under-estimates: Apply +15% correction
• Learns and adapts to current market regime
E) Regime Detection Multiplier (±20%):
• Analyzes last 3 trends of SAME TYPE (bull-to-bull or bear-to-bear)
• Compares recent trend durations to historical average
• If recent trends 20%+ longer than average: +20% adjustment (trending regime detected)
• If recent trends 20%+ shorter than average: -20% adjustment (choppy regime detected)
• Detects whether market is in trending or mean-reversion mode
Three analysis modes:
SIMPLE MODE - Basic Statistics
• Uses raw median of similar trends only
• No multipliers, no adjustments
• Best for: Beginners, clean trending markets
• Fastest calculations, minimal complexity
STANDARD MODE - Full Statistical Analysis
• Similarity matching with k-nearest neighbors
• Exponential weighting of recent trends
• Median, average, and range calculations
• Best for: Most traders, general market conditions
• Balance of accuracy and simplicity
ADVANCED MODE - Statistics + Intelligence
• Everything in Standard mode PLUS
• All 5 advanced multipliers (structure, asset type, flip strength, learning, regime)
• Highest Statistical accuracy in testing
• Best for: Experienced traders, volatile/complex markets
• Maximum intelligence, most adaptive
Visual Duration Analysis Box:
When a new trend begins (SuperTrend flip), a box appears on your chart showing:
• Analysis Mode (Simple / Standard / Advanced)
• Number of historical trends analyzed
• Median expected duration (most likely outcome)
• Average expected duration (mean of similar trends)
• Range (minimum to maximum from similar trends)
• Advanced multipliers breakdown (Advanced mode only)
• Backtest accuracy statistics (if available)
The box extends from the flip bar to the estimated endpoint based on historical data, giving you a visual target for trend duration. Box updates in real-time as trend progresses.
Backtest & Accuracy Tracking:
• System backtests its own duration estimates using historical data
• Shows accuracy metrics: how well duration estimates matched actual durations
• Tracks last 10 completed duration estimates separately
• Displays statistics in dashboard and duration analysis boxes
• Helps you understand statistical reliability on your specific symbol/timeframe
Anti-Repaint Guarantee:
• duration analysis boxes only appear AFTER bar close (barstate.isconfirmed)
• Historical duration estimates never disappear or change
• What you see in history is exactly what you would have seen real-time
• No future data leakage, no lookahead bias
2. INTELLIGENT PRESET CONFIGURATIONS - One-Click Optimization
Unlike indicators that require tedious parameter tweaking, this system includes professionally optimized presets for every trading style. Select your approach from the dropdown and ALL parameters auto-configure.
"AUTO (DETECT FROM TF)" - RECOMMENDED
The smartest option: automatically selects optimal settings based on your chart timeframe.
• 1m-5m charts → Scalping preset (ATR: 7, Mult: 2.0)
• 15m-1h charts → Day Trading preset (ATR: 10, Mult: 2.5)
• 2h-4h-D charts → Swing Trading preset (ATR: 14, Mult: 3.0)
• W-M charts → Position Trading preset (ATR: 21, Mult: 4.0)
Benefits:
• Zero configuration - works immediately
• Always matched to your timeframe
• Switch timeframe = automatic adjustment
• Perfect for traders who use multiple timeframes
"SCALPING (1-5M)" - Ultra-Fast Signals
Optimized for: 1-5 minute charts, high-frequency trading, quick profits
Target holding period: Minutes to 1-2 hours maximum
Best markets: High-volume stocks, major crypto pairs, active futures
Parameter Configuration:
• Supertrend: ATR 7, Multiplier 2.0 (very sensitive)
• Volume: MA 10, High 1.8x, Spike 3.0x (catches quick surges)
• Volume Momentum: AUTO-DISABLED (too restrictive for fast scalping)
• Quality minimum: 40 points (accepts more setups)
• Duration Analysis: Uses last 15 trends with heavy recent weighting
Trading Logic:
Speed over precision. Short ATR period and low multiplier create highly responsive SuperTrend. Volume momentum filter disabled to avoid missing fast moves. Quality threshold relaxed to catch more opportunities in rapid market conditions.
Signals per session: 5-15 typically
Hold time: Minutes to couple hours
Best for: Active traders with fast execution
"DAY TRADING (15M-1H)" - Balanced Approach
Optimized for: 15-minute to 1-hour charts, intraday moves, session-based trading
Target holding period: 30 minutes to 8 hours (within trading day)
Best markets: Large-cap stocks, major indices, established crypto
Parameter Configuration:
• Supertrend: ATR 10, Multiplier 2.5 (balanced)
• Volume: MA 20, High 1.5x, Spike 2.5x (standard detection)
• Volume Momentum: 5/20 periods (confirms intraday strength)
• Quality minimum: 50 points (good setups preferred)
• Duration Analysis: Balanced weighting of recent vs historical
Trading Logic:
The most balanced configuration. ATR 10 with multiplier 2.5 provides steady trend following that avoids noise while catching meaningful moves. Volume momentum confirms institutional participation without being overly restrictive.
Signals per session: 2-5 typically
Hold time: 30 minutes to full day
Best for: Part-time and full-time active traders
"SWING TRADING (4H-D)" - Trend Stability
Optimized for: 4-hour to Daily charts, multi-day holds, trend continuation
Target holding period: 2-15 days typically
Best markets: Growth stocks, sector ETFs, trending crypto, commodity futures
Parameter Configuration:
• Supertrend: ATR 14, Multiplier 3.0 (stable)
• Volume: MA 30, High 1.3x, Spike 2.2x (accumulation focus)
• Volume Momentum: 10/30 periods (trend stability)
• Quality minimum: 60 points (high-quality setups only)
• Duration Analysis: Favors consistent historical patterns
Trading Logic:
Designed for substantial trend moves while filtering short-term noise. Higher ATR period and multiplier create stable SuperTrend that won't flip on minor corrections. Stricter quality requirements ensure only strongest setups generate signals.
Signals per week: 2-5 typically
Hold time: Days to couple weeks
Best for: Part-time traders, swing style
"POSITION TRADING (D-W)" - Long-Term Trends
Optimized for: Daily to Weekly charts, major trend changes, portfolio allocation
Target holding period: Weeks to months
Best markets: Blue-chip stocks, major indices, established cryptocurrencies
Parameter Configuration:
• Supertrend: ATR 21, Multiplier 4.0 (very stable)
• Volume: MA 50, High 1.2x, Spike 2.0x (long-term accumulation)
• Volume Momentum: 20/50 periods (major trend confirmation)
• Quality minimum: 70 points (excellent setups only)
• Duration Analysis: Heavy emphasis on multi-year historical data
Trading Logic:
Conservative approach focusing on major trend changes. Extended ATR period and high multiplier create SuperTrend that only flips on significant reversals. Very strict quality filters ensure signals represent genuine long-term opportunities.
Signals per month: 1-2 typically
Hold time: Weeks to months
Best for: Long-term investors, set-and-forget approach
"CUSTOM" - Advanced Configuration
Purpose: Complete manual control for experienced traders
Use when: You understand the parameters and want specific optimization
Best for: Testing new approaches, unusual market conditions, specific instruments
Full control over:
• All SuperTrend parameters
• Volume thresholds and momentum periods
• Quality scoring weights
• analysis mode and multipliers
• Advanced features tuning
Preset Comparison Quick Reference:
Chart Timeframe: Scalping (1M-5M) | Day Trading (15M-1H) | Swing (4H-D) | Position (D-W)
Signals Frequency: Very High | High | Medium | Low
Hold Duration: Minutes | Hours | Days | Weeks-Months
Quality Threshold: 40 pts | 50 pts | 60 pts | 70 pts
ATR Sensitivity: Highest | Medium | Lower | Lowest
Time Investment: Highest | High | Medium | Lowest
Experience Level: Expert | Advanced | Intermediate | Beginner+
3. QUALITY SCORING SYSTEM (0-70 Points)
Every signal is rated in real-time across three dimensions:
Volume Confirmation (0-30 points):
• Volume Spike (2.5x+ average): 30 points
• High Volume (1.5x+ average): 20 points
• Above Average (1.0x+ average): 10 points
• Below Average: 0 points
Volatility Assessment (0-30 points):
• Expanding ATR (1.2x+ average): 30 points
• Rising ATR (1.0-1.2x average): 15 points
• Contracting/Stable ATR: 0 points
Volume Momentum (0-10 points):
• Strong Momentum (1.2x+ ratio): 10 points
• Rising Momentum (1.0-1.2x ratio): 5 points
• Weak/Neutral Momentum: 0 points
Score Interpretation:
60-70 points - EXCELLENT:
• All factors aligned
• High conviction setup
• Maximum position size (within risk limits)
• Primary trading opportunities
45-59 points - STRONG:
• Multiple confirmations present
• Above-average setup quality
• Standard position size
• Good trading opportunities
30-44 points - GOOD:
• Basic confirmations met
• Acceptable setup quality
• Reduced position size
• Wait for additional confirmation or trade smaller
Below 30 points - WEAK:
• Minimal confirmations
• Low probability setup
• Consider passing
• Only for aggressive traders in strong trends
Only signals meeting your minimum quality threshold (configurable per preset) generate alerts and labels.
4. MULTI-TIMEFRAME CONFLUENCE ANALYSIS
The system can simultaneously analyze trend alignment across 6 timeframes (optional feature):
Timeframes analyzed:
• 5-minute (scalping context)
• 15-minute (intraday momentum)
• 1-hour (day trading bias)
• 4-hour (swing context)
• Daily (primary trend)
• Weekly (macro trend)
Confluence Interpretation:
• 5-6/6 aligned - Very strong multi-timeframe agreement (highest confidence)
• 3-4/6 aligned - Moderate agreement (standard setup)
• 1-2/6 aligned - Weak agreement (caution advised)
Dashboard shows real-time alignment count with color-coding. Higher confluence typically correlates with longer, stronger trends.
5. VOLUME MOMENTUM FILTER - Institutional Money Flow
Unlike traditional volume indicators that just measure size, Volume Momentum tracks the RATE OF CHANGE in volume:
How it works:
• Compares short-term volume average (fast period) to long-term average (slow period)
• Ratio above 1.0 = Volume accelerating (money flowing IN)
• Ratio above 1.2 = Strong acceleration (institutional participation likely)
• Ratio below 0.8 = Volume decelerating (money flowing OUT)
Why it matters:
• Confirms trend with actual money flow, not just price
• Leading indicator (volume often leads price)
• Catches accumulation/distribution before breakouts
• More intuitive than complex mathematical filters
Integration with signals:
• Optional filter - can be enabled/disabled per preset
• When enabled: Only signals with rising volume momentum fire
• AUTO-DISABLED in Scalping mode (too restrictive for fast trading)
• Configurable fast/slow periods per trading style
6. ADAPTIVE SUPERTREND MULTIPLIER
Traditional SuperTrend uses fixed ATR multiplier. This system dynamically adjusts the multiplier (0.8x to 1.2x base) based on:
• Trend Strength: Price correlation over lookback period
• Volume Weight: Current volume relative to average
Benefits:
• Tighter bands in calm markets (less premature exits)
• Wider bands in volatile conditions (avoids whipsaws)
• Better adaptation to biotech, small-cap, and crypto volatility
• Optional - can be disabled for classic constant multiplier
7. VISUAL GRADIENT RIBBON
26-layer exponential gradient fill between price and SuperTrend line provides instant visual trend strength assessment:
Color System:
• Green shades - Bullish trend + volume confirmation (strongest)
• Blue shades - Bullish trend, normal volume
• Orange shades - Bearish trend + volume confirmation
• Red shades - Bearish trend (weakest)
Opacity varies based on:
• Distance from SuperTrend (farther = more opaque)
• Volume intensity (higher volume = stronger color)
The ribbon provides at-a-glance trend strength without cluttering your chart. Can be toggled on/off.
8. INTELLIGENT ALERT SYSTEM
Two-tier alert architecture for flexibility:
Automatic Alerts:
• Fire automatically on BUY and SELL signals
• Include full context: quality score, volume state, volume momentum
• One alert per bar close (alert.freq_once_per_bar_close)
• Message format: "BUY: Supertrend bullish + Quality: 65/70 | Volume: HIGH | Vol Momentum: STRONG (1.35x)"
Customizable Alert Conditions:
• Appear in TradingView's "Create Alert" dialog
• Three options: BUY Signal Only, SELL Signal Only, ANY Signal (BUY or SELL)
• Use TradingView placeholders: {{ticker}}, {{interval}}, {{close}}, {{time}}
• Fully customizable message templates
All alerts use barstate.isconfirmed - Zero repaint guarantee.
9. ANTI-REPAINT ARCHITECTURE
Every component guaranteed non-repainting:
• Entry signals: Only appear after bar close
• duration analysis boxes: Created only on confirmed SuperTrend flips
• Informative labels: Wait for bar confirmation
• Alerts: Fire once per closed bar
• Multi-timeframe data: Uses lookahead=barmerge.lookahead_off
What you see in history is exactly what you would have seen in real-time. No disappearing signals, no changed duration estimates.
HOW TO USE THE INDICATOR
QUICK START - 3 Steps to Trading:
Step 1: Select Your Trading Style
Open indicator settings → "Quick Setup" section → Trading Style Preset dropdown
Options:
• Auto (Detect from TF) - RECOMMENDED: Automatically configures based on your chart timeframe
• Scalping (1-5m) - For 1-5 minute charts, ultra-fast signals
• Day Trading (15m-1h) - For 15m-1h charts, balanced approach
• Swing Trading (4h-D) - For 4h-Daily charts, trend stability
• Position Trading (D-W) - For Daily-Weekly charts, long-term trends
• Custom - Manual configuration (advanced users only)
Choose "Auto" and you're done - all parameters optimize automatically.
Step 2: Understand the Signals
BUY Signal (Green Triangle Below Price):
• SuperTrend flipped bullish
• Quality score meets minimum threshold (varies by preset)
• Volume confirmation present (if filter enabled)
• Volume momentum rising (if filter enabled)
• duration analysis box shows expected trend duration
SELL Signal (Red Triangle Above Price):
• SuperTrend flipped bearish
• Quality score meets minimum threshold
• Volume confirmation present (if filter enabled)
• Volume momentum rising (if filter enabled)
• duration analysis box shows expected trend duration
Duration Analysis Box:
• Appears at SuperTrend flip (start of new trend)
• Shows median, average, and range duration estimates
• Extends to estimated endpoint based on historical data visually
• Updates mode-specific intelligence (Simple/Standard/Advanced)
Step 3: Use the Dashboard for Context
Dashboard (top-right corner) shows real-time metrics:
• Row 1 - Quality Score: Current setup rating (0-70)
• Row 2 - SuperTrend: Direction and current level
• Row 3 - Volume: Status (Spike/High/Normal/Low) with color
• Row 4 - Volatility: State (Expanding/Rising/Stable/Contracting)
• Row 5 - Volume Momentum: Ratio and trend
• Row 6 - Duration Statistics: Accuracy metrics and track record
Every cell has detailed tooltip - hover for full explanations.
SIGNAL INTERPRETATION BY QUALITY SCORE:
Excellent Setup (60-70 points):
• Quality Score: 60-70
• Volume: Spike or High
• Volatility: Expanding
• Volume Momentum: Strong (1.2x+)
• MTF Confluence (if enabled): 5-6/6
• Action: Primary trade - maximum position size (within risk limits)
• Statistical reliability: Highest - duration estimates most accurate
Strong Setup (45-59 points):
• Quality Score: 45-59
• Volume: High or Above Average
• Volatility: Rising
• Volume Momentum: Rising (1.0-1.2x)
• MTF Confluence (if enabled): 3-4/6
• Action: Standard trade - normal position size
• Statistical reliability: Good - duration estimates reliable
Good Setup (30-44 points):
• Quality Score: 30-44
• Volume: Above Average
• Volatility: Stable or Rising
• Volume Momentum: Neutral to Rising
• MTF Confluence (if enabled): 3-4/6
• Action: Cautious trade - reduced position size, wait for additional confirmation
• Statistical reliability: Moderate - duration estimates less certain
Weak Setup (Below 30 points):
• Quality Score: Below 30
• Volume: Low or Normal
• Volatility: Contracting or Stable
• Volume Momentum: Weak
• MTF Confluence (if enabled): 1-2/6
• Action: Pass or wait for improvement
• Statistical reliability: Low - duration estimates unreliable
USING duration analysis boxES FOR TRADE MANAGEMENT:
Entry Timing:
• Enter on SuperTrend flip (signal bar close)
• duration analysis box appears simultaneously
• Note the median duration - this is your expected hold time
Profit Targets:
• Conservative: Use MEDIAN duration as profit target (50% probability)
• Moderate: Use AVERAGE duration (mean of similar trends)
• Aggressive: Aim for MAX duration from range (best historical outcome)
Position Management:
• Scale out at median duration (take partial profits)
• Trail stop as trend extends beyond median
• Full exit at average duration or SuperTrend flip (whichever comes first)
• Re-evaluate if trend exceeds estimated range
analysis mode Selection:
• Simple: Clean trending markets, beginners, minimal complexity
• Standard: Most markets, most traders (recommended default)
• Advanced: Volatile markets, complex instruments, experienced traders seeking highest accuracy
Asset Type Configuration (Advanced Mode):
If using Advanced analysis mode, configure Asset Type for optimal accuracy:
• Small Cap: Stocks under $2B market cap, low liquidity
• Biotech / Speculative: Clinical-stage pharma, penny stocks, high-risk
• Blue Chip / Large Cap: S&P 500, mega-cap tech, stable large companies
• Tech Growth: High-growth tech (TSLA, NVDA, growth SaaS)
• Dividend / Value: Dividend aristocrats, value stocks, utilities
• Cyclical: Energy, materials, industrials (macro-driven)
• Crypto / High Volatility: Bitcoin, altcoins, highly volatile assets
Correct asset type selection improves Statistical accuracy by 15-20%.
RISK MANAGEMENT GUIDELINES:
1. Stop Loss Placement:
Long positions:
• Place stop below recent swing low OR
• Place stop below SuperTrend level (whichever is tighter)
• Use 1-2 ATR distance as guideline
• Recommended: SuperTrend level (built-in volatility adjustment)
Short positions:
• Place stop above recent swing high OR
• Place stop above SuperTrend level (whichever is tighter)
• Use 1-2 ATR distance as guideline
• Recommended: SuperTrend level
2. Position Sizing by Quality Score:
• Excellent (60-70): Maximum position size (2% risk per trade)
• Strong (45-59): Standard position size (1.5% risk per trade)
• Good (30-44): Reduced position size (1% risk per trade)
• Weak (Below 30): Pass or micro position (0.5% risk - learning trades only)
3. Exit Strategy Options:
Option A - Statistical Duration-Based Exit:
• Exit at median estimated duration (conservative)
• Exit at average estimated duration (moderate)
• Trail stop beyond average duration (aggressive)
Option B - Signal-Based Exit:
• Exit on opposite signal (SELL after BUY, or vice versa)
• Exit on SuperTrend flip (trend reversal)
• Exit if quality score drops below 30 mid-trend
Option C - Hybrid (Recommended):
• Take 50% profit at median estimated duration
• Trail stop on remaining 50% using SuperTrend as trailing level
• Full exit on SuperTrend flip or quality collapse
4. Trade Filtering:
For higher win-rate (fewer trades, better quality):
• Increase minimum quality score (try 60 for swing, 50 for day trading)
• Enable volume momentum filter (ensure institutional participation)
• Require higher MTF confluence (5-6/6 alignment)
• Use Advanced analysis mode with appropriate asset type
For more opportunities (more trades, lower quality threshold):
• Decrease minimum quality score (40 for day trading, 35 for scalping)
• Disable volume momentum filter
• Lower MTF confluence requirement
• Use Simple or Standard analysis mode
SETTINGS OVERVIEW
Quick Setup Section:
• Trading Style Preset: Auto / Scalping / Day Trading / Swing / Position / Custom
Dashboard & Display:
• Show Dashboard (ON/OFF)
• Dashboard Position (9 options: Top/Middle/Bottom + Left/Center/Right)
• Text Size (Auto/Tiny/Small/Normal/Large/Huge)
• Show Ribbon Fill (ON/OFF)
• Show SuperTrend Line (ON/OFF)
• Bullish Color (default: Green)
• Bearish Color (default: Red)
• Show Entry Labels - BUY/SELL signals (ON/OFF)
• Show Info Labels - Volume events (ON/OFF)
• Label Size (Auto/Tiny/Small/Normal/Large/Huge)
Supertrend Configuration:
• ATR Length (default varies by preset: 7-21)
• ATR Multiplier Base (default varies by preset: 2.0-4.0)
• Use Adaptive Multiplier (ON/OFF) - Dynamic 0.8x-1.2x adjustment
• Smoothing Factor (0.0-0.5) - EMA smoothing applied to bands
• Neutral Bars After Flip (0-10) - Hide ST immediately after flip
Volume Momentum:
• Enable Volume Momentum Filter (ON/OFF)
• Fast Period (default varies by preset: 3-20)
• Slow Period (default varies by preset: 10-50)
Volume Analysis:
• Volume MA Length (default varies by preset: 10-50)
• High Volume Threshold (default: 1.5x)
• Spike Threshold (default: 2.5x)
• Low Volume Threshold (default: 0.7x)
Quality Filters:
• Minimum Quality Score (0-70, varies by preset)
• Require Volume Confirmation (ON/OFF)
Trend Duration Analysis:
• Show Duration Analysis (ON/OFF) - Display duration analysis boxes
• analysis mode - Simple / Standard / Advanced
• Asset Type - 7 options (Small Cap, Biotech, Blue Chip, Tech Growth, Dividend, Cyclical, Crypto)
• Use Exponential Weighting (ON/OFF) - Recent trends weighted more
• Decay Factor (0.5-0.99) - How much more recent trends matter
• Structure Lookback (3-30) - Pivot detection period for support/resistance
• Proximity Threshold (xATR) - How close to level qualifies as "near"
• Enable Error Learning (ON/OFF) - System learns from estimation errors
• Memory Depth (3-20) - How many past errors to remember
Box Visual Settings:
• duration analysis box Border Color
• duration analysis box Background Color
• duration analysis box Text Color
• duration analysis box Border Width
• duration analysis box Transparency
Multi-Timeframe (Optional Feature):
• Enable MTF Confluence (ON/OFF)
• Minimum Alignment Required (0-6)
• Individual timeframe enable/disable toggles
• Custom timeframe selection options
All preset configurations override manual inputs except when "Custom" is selected.
ADVANCED FEATURES
1. Scalpel Mode (Optional)
Advanced pullback entry system that waits for healthy retracements within established trends before signaling entry:
• Monitors price distance from SuperTrend levels
• Requires pullback to configurable range (default: 30-50%)
• Ensures trend remains intact before entry signal
• Reduces whipsaw and false breakouts
• Inspired by Mark Minervini's VCP pullback entries
Best for: Swing traders and day traders seeking precision entries
Scalpers: Consider disabling for faster entries
2. Error Learning System (Advanced analysis mode Only)
The system learns from its own estimation errors:
• Tracks last 10-20 completed duration estimates (configurable memory depth)
• Calculates error ratio for each: estimated duration / Actual Duration
• If system consistently over-estimates: Applies negative correction (-15%)
• If system consistently under-estimates: Applies positive correction (+15%)
• Adapts to current market regime automatically
This self-correction mechanism improves accuracy over time as the system gathers more data on your specific symbol and timeframe.
3. Regime Detection (Advanced analysis mode Only)
Automatically detects whether market is in trending or choppy regime:
• Compares last 3 trends to historical average
• Recent trends 20%+ longer → Trending regime (+20% to estimates)
• Recent trends 20%+ shorter → Choppy regime (-20% to estimates)
• Applied separately to bullish and bearish trends
Helps duration estimates adapt to changing market conditions without manual intervention.
4. Exponential Weighting
Option to weight recent trends more heavily than distant history:
• Default decay factor: 0.9
• Recent trends get higher weight in statistical calculations
• Older trends gradually decay in importance
• Rationale: Recent market behavior more relevant than old data
• Can be disabled for equal weighting
5. Backtest Statistics
System backtests its own duration estimates using historical data:
• Walks through past trends chronologically
• Calculates what duration estimate WOULD have been at each flip
• Compares to actual duration that occurred
• Displays accuracy metrics in duration analysis boxes and dashboard
• Helps assess statistical reliability on your specific chart
Note: Backtest uses only data available AT THE TIME of each historical flip (no lookahead bias).
TECHNICAL SPECIFICATIONS
• Pine Script Version: v6
• Indicator Type: Overlay (draws on price chart)
• Max Boxes: 500 (for duration analysis box storage)
• Max Bars Back: 5000 (for comprehensive historical analysis)
• Security Calls: 1 (for MTF if enabled - optimized)
• Repainting: NO - All signals and duration estimates confirmed on bar close
• Lookahead Bias: NO - All HTF data properly offset, all duration estimates use only historical data
• Real-time Updates: YES - Dashboard and quality scores update live
• Alert Capable: YES - Both automatic alerts and customizable alert conditions
• Multi-Symbol: Works on stocks, crypto, forex, futures, indices
Performance Optimization:
• Conditional calculations (duration analysis can be disabled to reduce load)
• Efficient array management (circular buffers for trend storage)
• Streamlined gradient rendering (26 layers, can be toggled off)
• Smart label cooldown system (prevents label spam)
• Optimized similarity matching (analyzes only relevant trends)
Data Requirements:
• Minimum 50-100 bars for initial duration analysis (builds historical database)
• Optimal: 500+ bars for robust statistical analysis
• Longer history = more accurate duration estimates
• Works on any timeframe from 1 minute to monthly
KNOWN LIMITATIONS
• Trending Markets Only: Performs best in clear trends. May generate false signals in choppy/sideways markets (use quality score filtering and regime detection to mitigate)
• Lagging Nature: Like all trend-following systems, signals occur AFTER trend establishment, not at exact tops/bottoms. Use duration analysis boxes to set realistic profit targets.
• Initial Learning Period: Duration analysis system requires 10-15 completed trends to build reliable historical database. Early duration estimates less accurate (first few weeks on new symbol/timeframe).
• Visual Load: 26-layer gradient ribbon may slow performance on older devices. Disable ribbon if experiencing lag.
• Statistical accuracy Variables: Duration estimates are statistical estimates, not guarantees. Accuracy varies by:
- Market regime (trending vs choppy)
- Asset volatility characteristics
- Quality of historical pattern matches
- Timeframe traded (higher TF = more reliable)
• Not Best Suitable For:
- Ultra-short-term scalping (sub-1-minute charts)
- Mean-reversion strategies (designed for trend-following)
- Range-bound trading (requires trending conditions)
- News-driven spikes (estimates based on technical patterns, not fundamentals)
FREQUENTLY ASKED QUESTIONS
Q: Does this indicator repaint?
A: Absolutely not. All signals, duration analysis boxes, labels, and alerts use barstate.isconfirmed checks. They only appear after the bar closes. What you see in history is exactly what you would have seen in real-time. Zero repaint guarantee.
Q: How accurate are the trend duration estimates?
A: Accuracy varies by mode, market conditions, and historical data quality:
• Simple mode: 60-70% accuracy (within ±20% of actual duration)
• Standard mode: 70-80% accuracy (within ±20% of actual duration)
• Advanced mode: 75-85% accuracy (within ±20% of actual duration)
Best accuracy achieved on:
• Higher timeframes (4H, Daily, Weekly)
• Trending markets (not choppy/sideways)
• Assets with consistent behavior (Blue Chip, Large Cap)
• After 20+ historical trends analyzed (builds robust database)
Remember: All duration estimates are statistical calculations based on historical patterns, not guarantees.
Q: Which analysis mode should I use?
A:
• Simple: Beginners, clean trending markets, want minimal complexity
• Standard: Most traders, general market conditions (RECOMMENDED DEFAULT)
• Advanced: Experienced traders, volatile/complex markets (biotech, small-cap, crypto), seeking maximum accuracy
Advanced mode requires correct Asset Type configuration for optimal results.
Q: What's the difference between the trading style presets?
A: Each preset optimizes ALL parameters for a specific trading approach:
• Scalping: Ultra-sensitive (ATR 7, Mult 2.0), more signals, shorter holds
• Day Trading: Balanced (ATR 10, Mult 2.5), moderate signals, intraday holds
• Swing Trading: Stable (ATR 14, Mult 3.0), fewer signals, multi-day holds
• Position Trading: Very stable (ATR 21, Mult 4.0), rare signals, week/month holds
Auto mode automatically selects based on your chart timeframe.
Q: Should I use Auto mode or manually select a preset?
A: Auto mode is recommended for most traders. It automatically matches settings to your timeframe and re-optimizes if you switch charts. Only use manual preset selection if:
• You want scalping settings on a 15m chart (overriding auto-detection)
• You want swing settings on a 1h chart (more conservative than auto would give)
• You're testing different approaches on same timeframe
Q: Can I use this for scalping and day trading?
A: Absolutely! The preset system is specifically designed for all trading styles:
• Select "Scalping (1-5m)" for 1-5 minute charts
• Select "Day Trading (15m-1h)" for 15m-1h charts
• Or use "Auto" mode and it configures automatically
Volume momentum filter is auto-disabled in Scalping mode for faster signals.
Q: What is Volume Momentum and why does it matter?
A: Volume Momentum compares short-term volume (fast MA) to long-term volume (slow MA). It answers: "Is money flowing into this asset faster now than historically?"
Why it matters:
• Volume often leads price (early warning system)
• Confirms institutional participation (smart money)
• No lag like price-based indicators
• More intuitive than complex mathematical filters
When the ratio is above 1.2, you have strong evidence that institutions are accumulating (bullish) or distributing (bearish).
Q: How do I set up alerts?
A: Two options:
Option 1 - Automatic Alerts:
1. Right-click on chart → Add Alert
2. Condition: Select this indicator
3. Choose "Any alert() function call"
4. Configure notification method (app, email, webhook)
5. You'll receive detailed alerts on every BUY and SELL signal
Option 2 - Customizable Alert Conditions:
1. Right-click on chart → Add Alert
2. Condition: Select this indicator
3. You'll see three options in dropdown:
- "BUY Signal" (long signals only)
- "SELL Signal" (short signals only)
- "ANY Signal" (both BUY and SELL)
4. Choose desired option and customize message template
5. Uses TradingView placeholders: {{ticker}}, {{close}}, {{time}}, etc.
All alerts fire only on confirmed bar close (no repaint).
Q: What is Scalpel Mode and should I use it?
A: Scalpel Mode waits for healthy pullbacks within established trends before signaling entry. It reduces whipsaws and improves entry timing.
Recommended ON for:
• Swing traders (want precision entries on pullbacks)
• Day traders (willing to wait for better prices)
• Risk-averse traders (prefer fewer but higher-quality entries)
Recommended OFF for:
• Scalpers (need immediate entries, can't wait for pullbacks)
• Momentum traders (want to enter on breakout, not pullback)
• Aggressive traders (prefer more opportunities over precision)
Q: Why do some duration estimates show wider ranges than others?
A: Range width reflects historical trend variability:
• Narrow range: Similar historical trends had consistent durations (high confidence)
• Wide range: Similar historical trends had varying durations (lower confidence)
Wide ranges often occur:
• Early in analysis (fewer historical trends to learn from)
• In volatile/choppy markets (inconsistent trend behavior)
• On lower timeframes (more noise, less consistency)
The median and average still provide useful targets even when range is wide.
Q: Can I customize the dashboard position and appearance?
A: Yes! Dashboard settings include:
• Position: 9 options (Top/Middle/Bottom + Left/Center/Right)
• Text Size: Auto, Tiny, Small, Normal, Large, Huge
• Show/Hide: Toggle entire dashboard on/off
Choose position that doesn't overlap important price action on your specific chart.
Q: Which timeframe should I trade on?
A: Depends on your trading style and time availability:
• 1-5 minute: Active scalping, requires constant monitoring
• 15m-1h: Day trading, check few times per session
• 4h-Daily: Swing trading, check once or twice daily
• Daily-Weekly: Position trading, check weekly
General principle: Higher timeframes produce:
• Fewer signals (less frequent)
• Higher quality setups (stronger confirmations)
• More reliable duration estimates (better statistical data)
• Less noise (clearer trends)
Start with Daily chart if new to trading. Move to lower timeframes as you gain experience.
Q: Does this work on all markets (stocks, crypto, forex)?
A: Yes, it works on all markets with trending characteristics:
Excellent for:
• Stocks (especially growth and momentum names)
• Crypto (BTC, ETH, major altcoins)
• Futures (indices, commodities)
• Forex majors (EUR/USD, GBP/USD, etc.)
Best results on:
• Trending markets (not range-bound)
• Liquid instruments (tight spreads, good fills)
• Volatile assets (clear trend development)
Less effective on:
• Range-bound/sideways markets
• Ultra-low volatility instruments
• Illiquid small-caps (use caution)
Configure Asset Type (in Advanced analysis mode) to match your instrument for best accuracy.
Q: How many signals should I expect per day/week?
A: Highly variable based on:
By Timeframe:
• 1-5 minute: 5-15 signals per session
• 15m-1h: 2-5 signals per day
• 4h-Daily: 2-5 signals per week
• Daily-Weekly: 1-2 signals per month
By Market Volatility:
• High volatility = more SuperTrend flips = more signals
• Low volatility = fewer flips = fewer signals
By Quality Filter:
• Higher threshold (60-70) = fewer but better signals
• Lower threshold (30-40) = more signals, lower quality
By Volume Momentum Filter:
• Enabled = Fewer signals (only volume-confirmed)
• Disabled = More signals (all SuperTrend flips)
Adjust quality threshold and filters to match your desired signal frequency.
Q: What's the difference between entry labels and info labels?
A:
Entry Labels (BUY/SELL):
• Your primary trading signals
• Based on SuperTrend flip + all confirmations (quality, volume, momentum)
• Include quality score and confirmation icons
• These are actionable entry points
Info Labels (Volume Spike):
• Additional market context
• Show volume events that may support or contradict trend
• 8-bar cooldown to prevent spam
• NOT necessarily entry points - contextual information only
Control separately: Can show entry labels without info labels (recommended for clean charts).
Q: Can I combine this with other indicators?
A: Absolutely! This works well with:
• RSI: For divergences and overbought/oversold conditions
• Support/Resistance: Confluence with key levels
• Fibonacci Retracements: Pullback targets in Scalpel Mode
• Price Action Patterns: Flags, pennants, cup-and-handle
• MACD: Additional momentum confirmation
• Bollinger Bands: Volatility context
This indicator provides trend direction and duration estimates - complement with other tools for entry refinement and additional confluence.
Q: Why did I get a low-quality signal? Can I filter them out?
A: Yes! Increase the Minimum Quality Score in settings.
If you're seeing signals with quality below your preference:
• Day Trading: Set minimum to 50
• Swing Trading: Set minimum to 60
• Position Trading: Set minimum to 70
Only signals meeting the threshold will appear. This reduces frequency but improves win-rate.
Q: How do I interpret the MTF Confluence count?
A: Shows how many of 6 timeframes agree with current trend:
• 6/6 aligned: Perfect agreement (extremely rare, highest confidence)
• 5/6 aligned: Very strong alignment (high confidence)
• 4/6 aligned: Good alignment (standard quality setup)
• 3/6 aligned: Moderate alignment (acceptable)
• 2/6 aligned: Weak alignment (caution)
• 1/6 aligned: Very weak (likely counter-trend)
Higher confluence typically correlates with longer, stronger trends. However, MTF analysis is optional - you can disable it and rely solely on quality scoring.
Q: Is this suitable for beginners?
A: Yes, but requires foundational knowledge:
You should understand:
• Basic trend-following concepts (higher highs, higher lows)
• Risk management principles (position sizing, stop losses)
• How to read candlestick charts
• What volume and volatility mean
Beginner-friendly features:
• Auto preset mode (zero configuration)
• Quality scoring (tells you signal strength)
• Dashboard tooltips (hover for explanations)
• duration analysis boxes (visual profit targets)
Recommended for beginners:
1. Start with "Auto" or "Swing Trading" preset on Daily chart
2. Use Standard Analysis Mode (not Advanced)
3. Set minimum quality to 60 (fewer but better signals)
4. Paper trade first for 2-4 weeks
5. Study methodology references (Minervini, O'Neil, Zanger)
Q: What is the Asset Type setting and why does it matter?
A: Asset Type (in Advanced analysis mode) adjusts duration estimates based on volatility characteristics:
• Small Cap: Explosive moves, extended trends (+30-40%)
• Biotech / Speculative: Parabolic potential, news-driven (+40%)
• Blue Chip / Large Cap: Baseline, steady trends (0% adjustment)
• Tech Growth: Momentum-driven, longer trends (+20%)
• Dividend / Value: Slower, grinding trends (-20%)
• Cyclical: Macro-driven, variable (±10%)
• Crypto / High Volatility: Parabolic potential (+30%)
Correct configuration improves Statistical accuracy by 15-20%. Using Blue Chip settings on a biotech stock may underestimate trend length (you'll exit too early).
Q: Can I backtest this indicator?
A: Yes! TradingView's Strategy Tester works with this indicator's signals.
To backtest:
1. Note the entry conditions (SuperTrend flip + quality threshold + filters)
2. Create a strategy script using same logic
3. Run Strategy Tester on historical data
Additionally, the indicator includes BUILT-IN duration estimate validation:
• System backtests its own duration estimates
• Shows accuracy metrics in dashboard and duration analysis boxes
• Helps assess reliability on your specific symbol/timeframe
Q: Why does Volume Momentum auto-disable in Scalping mode?
A: Scalping requires ultra-fast entries to catch quick moves. Volume Momentum filter adds friction by requiring volume confirmation before signaling, which can cause missed opportunities in rapid scalping.
Scalping preset is optimized for speed and frequency - the filter is counterproductive for that style. It remains enabled for Day Trading, Swing Trading, and Position Trading presets where patience improves results.
You can manually enable it in Custom mode if desired.
Q: How much historical data do I need for accurate duration estimates?
A:
Minimum: 50-100 bars (indicator will function but duration estimates less reliable)
Recommended: 500+ bars (robust statistical database)
Optimal: 1000+ bars (maximum Statistical accuracy)
More history = more completed trends = better pattern matching = more accurate duration estimates.
New symbols or newly-switched timeframes will have lower Statistical accuracy initially. Allow 2-4 weeks for the system to build historical database.
IMPORTANT DISCLAIMERS
No Guarantee of Profit:
This indicator is an educational tool and does not guarantee any specific trading results. All trading involves substantial risk of loss. Duration estimates are statistical calculations based on historical patterns and are not guarantees of future performance.
Past Performance:
Historical backtest results and Statistical accuracy statistics do not guarantee future performance. Market conditions change constantly. What worked historically may not work in current or future markets.
Not Financial Advice:
This indicator provides technical analysis signals and statistical duration estimates only. It is not financial, investment, or trading advice. Always consult with a qualified financial advisor before making investment decisions.
Risk Warning:
Trading stocks, options, futures, forex, and cryptocurrencies involves significant risk. You can lose all of your invested capital. Never trade with money you cannot afford to lose. Only risk capital you can lose without affecting your lifestyle.
Testing Required:
Always test this indicator on a demo account or with paper trading before risking real capital. Understand how it works in different market conditions. Verify Statistical accuracy on your specific instruments and timeframes before trusting it with real money.
User Responsibility:
You are solely responsible for your trading decisions. The developer assumes no liability for trading losses, incorrect duration estimates, software errors, or any other damages incurred while using this indicator.
Statistical Estimation Limitations:
Trend Duration estimates are statistical estimates based on historical pattern matching. They are NOT guarantees. Actual trend durations may differ significantly from duration estimates due to unforeseen news events, market regime changes, or lack of historical precedent for current conditions.
CREDITS & ACKNOWLEDGMENTS
Methodology Inspiration:
• Mark Minervini - Volatility Contraction Pattern (VCP) concepts and pullback entry techniques
• William O'Neil - Volume analysis principles and CANSLIM institutional buying patterns
• Dan Zanger - Momentum breakout strategies and volatility expansion entries
Technical Components:
• SuperTrend calculation - Classic ATR-based trend indicator (public domain)
• Statistical analysis - Standard median, average, range calculations
• k-Nearest Neighbors - Classic machine learning similarity matching concept
• Multi-timeframe analysis - Standard request.security implementation in Pine Script
For questions, feedback, or support, please comment below or send a private message.
Happy Trading!
RSI Driven ATR Trend [NeuraAlgo]
RSI Driven ATR Trend
Dynamic Trend Detection and Strength Analysis
Unlock the market’s hidden rhythm with the RSI Driven ATR Trend , a sophisticated tool designed to measure trend direction and strength using a combination of RSI momentum and ATR-based volatility . This indicator provides real-time insights into bullish and bearish phases, helping traders identify potential turning points and optimize entry and exit decisions.
1.Core In Logic:
Dynamically calculates trend levels based on RSI and ATR interactions.
Highlights trend direction with intuitive color coding: green for bullish, red for bearish.
Displays trend strength as a percentage to quantify momentum intensity.
Automatic visual cues for potential trend reversals with “Turn Up” and “Turn Down” labels.
Advanced smoothing and dynamic gating ensure responsive yet stable trend detection.
Compatible with all timeframes and instruments.
2.Inputs Explained:
Rsi Factor: Adjusts the sensitivity of the RSI in trend calculation. Higher values make the trend detection more responsive to momentum changes.
Multiplier: Multiplies the effect of Rsi Factor to fine-tune trend responsiveness.
Bar Back: Number of bars used for peak and dip calculations, determining how far back the indicator looks for trend changes.
Period: Lookback period used in trend gating and ATR calculations.
Source: Price source for calculations (default is close).
Main Colors: Customize bullish and bearish trend colors.
3.How it Works:
The indicator calculates RSI values and ATR-based dynamic ranges to determine upper and lower trend levels.
Trend direction is determined by price crossing above (bullish) or below (bearish) the dynamic trend line.
Trend strength is expressed as a percentage relative to the trend line, helping you assess momentum intensity.
Visual cues like "Turn Up" and "Turn Down" labels indicate potential trend reversals.
Bars are colored dynamically based on trend direction for quick interpretation.
Ideal for traders seeking a clear, actionable view of market trends without the clutter of multiple indicators. RSI Driven ATR Trend translates complex price behavior into an easy-to-read visual guide, helping you make smarter trading decisions.
Happy Trading!
BT Strateji Asistanı (S/R + Trend)BT Strateji Asistanı (S/R + Trend) aistanı ile trend belirleme, destek ve direnç tespit etme
Naveen Prabhu with EMA//@version=6
indicator('Naveen Prabhu with EMA', overlay = true, max_labels_count = 500, max_lines_count = 500, max_boxes_count = 500)
a = input(2, title = 'Key Vaule. \'This changes the sensitivity\'')
c = input(5, title = 'ATR Period')
h = input(false, title = 'Signals from Heikin Ashi Candles')
BULLISH_LEG = 1
BEARISH_LEG = 0
BULLISH = +1
BEARISH = -1
GREEN = #089981
RED = #F23645
BLUE = #2157f3
GRAY = #878b94
MONO_BULLISH = #b2b5be
MONO_BEARISH = #5d606b
HISTORICAL = 'Historical'
PRESENT = 'Present'
COLORED = 'Colored'
MONOCHROME = 'Monochrome'
ALL = 'All'
BOS = 'BOS'
CHOCH = 'CHoCH'
TINY = size.tiny
SMALL = size.small
NORMAL = size.normal
ATR = 'Atr'
RANGE = 'Cumulative Mean Range'
CLOSE = 'Close'
HIGHLOW = 'High/Low'
SOLID = '⎯⎯⎯'
DASHED = '----'
DOTTED = '····'
SMART_GROUP = 'Smart Money Concepts'
INTERNAL_GROUP = 'Real Time Internal Structure'
SWING_GROUP = 'Real Time Swing Structure'
BLOCKS_GROUP = 'Order Blocks'
EQUAL_GROUP = 'EQH/EQL'
GAPS_GROUP = 'Fair Value Gaps'
LEVELS_GROUP = 'Highs & Lows MTF'
ZONES_GROUP = 'Premium & Discount Zones'
modeTooltip = 'Allows to display historical Structure or only the recent ones'
styleTooltip = 'Indicator color theme'
showTrendTooltip = 'Display additional candles with a color reflecting the current trend detected by structure'
showInternalsTooltip = 'Display internal market structure'
internalFilterConfluenceTooltip = 'Filter non significant internal structure breakouts'
showStructureTooltip = 'Display swing market Structure'
showSwingsTooltip = 'Display swing point as labels on the chart'
showHighLowSwingsTooltip = 'Highlight most recent strong and weak high/low points on the chart'
showInternalOrderBlocksTooltip = 'Display internal order blocks on the chart Number of internal order blocks to display on the chart'
showSwingOrderBlocksTooltip = 'Display swing order blocks on the chart Number of internal swing blocks to display on the chart'
orderBlockFilterTooltip = 'Method used to filter out volatile order blocks It is recommended to use the cumulative mean range method when a low amount of data is available'
orderBlockMitigationTooltip = 'Select what values to use for order block mitigation'
showEqualHighsLowsTooltip = 'Display equal highs and equal lows on the chart'
equalHighsLowsLengthTooltip = 'Number of bars used to confirm equal highs and equal lows'
equalHighsLowsThresholdTooltip = 'Sensitivity threshold in a range (0, 1) used for the detection of equal highs & lows Lower values will return fewer but more pertinent results'
showFairValueGapsTooltip = 'Display fair values gaps on the chart'
fairValueGapsThresholdTooltip = 'Filter out non significant fair value gaps'
fairValueGapsTimeframeTooltip = 'Fair value gaps timeframe'
fairValueGapsExtendTooltip = 'Determine how many bars to extend the Fair Value Gap boxes on chart'
showPremiumDiscountZonesTooltip = 'Display premium, discount, and equilibrium zones on chart'
modeInput = input.string( HISTORICAL, 'Mode', group = SMART_GROUP, tooltip = modeTooltip, options = )
styleInput = input.string( COLORED, 'Style', group = SMART_GROUP, tooltip = styleTooltip,options = )
showTrendInput = input( false, 'Color Candles', group = SMART_GROUP, tooltip = showTrendTooltip)
showInternalsInput = input( false, 'Show Internal Structure', group = INTERNAL_GROUP, tooltip = showInternalsTooltip)
showInternalBullInput = input.string( ALL, 'Bullish Structure', group = INTERNAL_GROUP, inline = 'ibull', options = )
internalBullColorInput = input( GREEN, '', group = INTERNAL_GROUP, inline = 'ibull')
showInternalBearInput = input.string( ALL, 'Bearish Structure' , group = INTERNAL_GROUP, inline = 'ibear', options = )
internalBearColorInput = input( RED, '', group = INTERNAL_GROUP, inline = 'ibear')
internalFilterConfluenceInput = input( false, 'Confluence Filter', group = INTERNAL_GROUP, tooltip = internalFilterConfluenceTooltip)
internalStructureSize = input.string( TINY, 'Internal Label Size', group = INTERNAL_GROUP, options = )
showStructureInput = input( false, 'Show Swing Structure', group = SWING_GROUP, tooltip = showStructureTooltip)
showSwingBullInput = input.string( ALL, 'Bullish Structure', group = SWING_GROUP, inline = 'bull', options = )
swingBullColorInput = input( GREEN, '', group = SWING_GROUP, inline = 'bull')
showSwingBearInput = input.string( ALL, 'Bearish Structure', group = SWING_GROUP, inline = 'bear', options = )
swingBearColorInput = input( RED, '', group = SWING_GROUP, inline = 'bear')
swingStructureSize = input.string( SMALL, 'Swing Label Size', group = SWING_GROUP, options = )
showSwingsInput = input( false, 'Show Swings Points', group = SWING_GROUP, tooltip = showSwingsTooltip,inline = 'swings')
swingsLengthInput = input.int( 50, '', group = SWING_GROUP, minval = 10, inline = 'swings')
showHighLowSwingsInput = input( false, 'Show Strong/Weak High/Low',group = SWING_GROUP, tooltip = showHighLowSwingsTooltip)
showInternalOrderBlocksInput = input( true, 'Internal Order Blocks' , group = BLOCKS_GROUP, tooltip = showInternalOrderBlocksTooltip, inline = 'iob')
internalOrderBlocksSizeInput = input.int( 5, '', group = BLOCKS_GROUP, minval = 1, maxval = 20, inline = 'iob')
showSwingOrderBlocksInput = input( true, 'Swing Order Blocks', group = BLOCKS_GROUP, tooltip = showSwingOrderBlocksTooltip, inline = 'ob')
swingOrderBlocksSizeInput = input.int( 5, '', group = BLOCKS_GROUP, minval = 1, maxval = 20, inline = 'ob')
orderBlockFilterInput = input.string( 'Atr', 'Order Block Filter', group = BLOCKS_GROUP, tooltip = orderBlockFilterTooltip, options = )
orderBlockMitigationInput = input.string( HIGHLOW, 'Order Block Mitigation', group = BLOCKS_GROUP, tooltip = orderBlockMitigationTooltip, options = )
internalBullishOrderBlockColor = input.color(color.new(GREEN, 80), 'Internal Bullish OB', group = BLOCKS_GROUP)
internalBearishOrderBlockColor = input.color(color.new(#f77c80, 80), 'Internal Bearish OB', group = BLOCKS_GROUP)
swingBullishOrderBlockColor = input.color(color.new(GREEN, 80), 'Bullish OB', group = BLOCKS_GROUP)
swingBearishOrderBlockColor = input.color(color.new(#b22833, 80), 'Bearish OB', group = BLOCKS_GROUP)
showEqualHighsLowsInput = input( false, 'Equal High/Low', group = EQUAL_GROUP, tooltip = showEqualHighsLowsTooltip)
equalHighsLowsLengthInput = input.int( 3, 'Bars Confirmation', group = EQUAL_GROUP, tooltip = equalHighsLowsLengthTooltip, minval = 1)
equalHighsLowsThresholdInput = input.float( 0.1, 'Threshold', group = EQUAL_GROUP, tooltip = equalHighsLowsThresholdTooltip, minval = 0, maxval = 0.5, step = 0.1)
equalHighsLowsSizeInput = input.string( TINY, 'Label Size', group = EQUAL_GROUP, options = )
showFairValueGapsInput = input( false, 'Fair Value Gaps', group = GAPS_GROUP, tooltip = showFairValueGapsTooltip)
fairValueGapsThresholdInput = input( true, 'Auto Threshold', group = GAPS_GROUP, tooltip = fairValueGapsThresholdTooltip)
fairValueGapsTimeframeInput = input.timeframe('', 'Timeframe', group = GAPS_GROUP, tooltip = fairValueGapsTimeframeTooltip)
fairValueGapsBullColorInput = input.color(color.new(#00ff68, 70), 'Bullish FVG' , group = GAPS_GROUP)
fairValueGapsBearColorInput = input.color(color.new(#ff0008, 70), 'Bearish FVG' , group = GAPS_GROUP)
fairValueGapsExtendInput = input.int( 1, 'Extend FVG', group = GAPS_GROUP, tooltip = fairValueGapsExtendTooltip, minval = 0)
showDailyLevelsInput = input( false, 'Daily', group = LEVELS_GROUP, inline = 'daily')
dailyLevelsStyleInput = input.string( SOLID, '', group = LEVELS_GROUP, inline = 'daily', options = )
dailyLevelsColorInput = input( BLUE, '', group = LEVELS_GROUP, inline = 'daily')
showWeeklyLevelsInput = input( false, 'Weekly', group = LEVELS_GROUP, inline = 'weekly')
weeklyLevelsStyleInput = input.string( SOLID, '', group = LEVELS_GROUP, inline = 'weekly', options = )
weeklyLevelsColorInput = input( BLUE, '', group = LEVELS_GROUP, inline = 'weekly')
showMonthlyLevelsInput = input( false, 'Monthly', group = LEVELS_GROUP, inline = 'monthly')
monthlyLevelsStyleInput = input.string( SOLID, '', group = LEVELS_GROUP, inline = 'monthly', options = )
monthlyLevelsColorInput = input( BLUE, '', group = LEVELS_GROUP, inline = 'monthly')
showPremiumDiscountZonesInput = input( false, 'Premium/Discount Zones', group = ZONES_GROUP , tooltip = showPremiumDiscountZonesTooltip)
premiumZoneColorInput = input.color( RED, 'Premium Zone', group = ZONES_GROUP)
equilibriumZoneColorInput = input.color( GRAY, 'Equilibrium Zone', group = ZONES_GROUP)
discountZoneColorInput = input.color( GREEN, 'Discount Zone', group = ZONES_GROUP)
type alerts
bool internalBullishBOS = false
bool internalBearishBOS = false
bool internalBullishCHoCH = false
bool internalBearishCHoCH = false
bool swingBullishBOS = false
bool swingBearishBOS = false
bool swingBullishCHoCH = false
bool swingBearishCHoCH = false
bool internalBullishOrderBlock = false
bool internalBearishOrderBlock = false
bool swingBullishOrderBlock = false
bool swingBearishOrderBlock = false
bool equalHighs = false
bool equalLows = false
bool bullishFairValueGap = false
bool bearishFairValueGap = false
type trailingExtremes
float top
float bottom
int barTime
int barIndex
int lastTopTime
int lastBottomTime
type fairValueGap
float top
float bottom
int bias
box topBox
box bottomBox
type trend
int bias
type equalDisplay
line l_ine = na
label l_abel = na
type pivot
float currentLevel
float lastLevel
bool crossed
int barTime = time
int barIndex = bar_index
type orderBlock
float barHigh
float barLow
int barTime
int bias
// @variable current swing pivot high
var pivot swingHigh = pivot.new(na,na,false)
// @variable current swing pivot low
var pivot swingLow = pivot.new(na,na,false)
// @variable current internal pivot high
var pivot internalHigh = pivot.new(na,na,false)
// @variable current internal pivot low
var pivot internalLow = pivot.new(na,na,false)
// @variable current equal high pivot
var pivot equalHigh = pivot.new(na,na,false)
// @variable current equal low pivot
var pivot equalLow = pivot.new(na,na,false)
// @variable swing trend bias
var trend swingTrend = trend.new(0)
// @variable internal trend bias
var trend internalTrend = trend.new(0)
// @variable equal high display
var equalDisplay equalHighDisplay = equalDisplay.new()
// @variable equal low display
var equalDisplay equalLowDisplay = equalDisplay.new()
// @variable storage for fairValueGap UDTs
var array fairValueGaps = array.new()
// @variable storage for parsed highs
var array parsedHighs = array.new()
// @variable storage for parsed lows
var array parsedLows = array.new()
// @variable storage for raw highs
var array highs = array.new()
// @variable storage for raw lows
var array lows = array.new()
// @variable storage for bar time values
var array times = array.new()
// @variable last trailing swing high and low
var trailingExtremes trailing = trailingExtremes.new()
// @variable storage for orderBlock UDTs (swing order blocks)
var array swingOrderBlocks = array.new()
// @variable storage for orderBlock UDTs (internal order blocks)
var array internalOrderBlocks = array.new()
// @variable storage for swing order blocks boxes
var array swingOrderBlocksBoxes = array.new()
// @variable storage for internal order blocks boxes
var array internalOrderBlocksBoxes = array.new()
// @variable color for swing bullish structures
var swingBullishColor = styleInput == MONOCHROME ? MONO_BULLISH : swingBullColorInput
// @variable color for swing bearish structures
var swingBearishColor = styleInput == MONOCHROME ? MONO_BEARISH : swingBearColorInput
// @variable color for bullish fair value gaps
var fairValueGapBullishColor = styleInput == MONOCHROME ? color.new(MONO_BULLISH,70) : fairValueGapsBullColorInput
// @variable color for bearish fair value gaps
var fairValueGapBearishColor = styleInput == MONOCHROME ? color.new(MONO_BEARISH,70) : fairValueGapsBearColorInput
// @variable color for premium zone
var premiumZoneColor = styleInput == MONOCHROME ? MONO_BEARISH : premiumZoneColorInput
// @variable color for discount zone
var discountZoneColor = styleInput == MONOCHROME ? MONO_BULLISH : discountZoneColorInput
// @variable bar index on current script iteration
varip int currentBarIndex = bar_index
// @variable bar index on last script iteration
varip int lastBarIndex = bar_index
// @variable alerts in current bar
alerts currentAlerts = alerts.new()
// @variable time at start of chart
var initialTime = time
// we create the needed boxes for displaying order blocks at the first execution
if barstate.isfirst
if showSwingOrderBlocksInput
for index = 1 to swingOrderBlocksSizeInput
swingOrderBlocksBoxes.push(box.new(na,na,na,na,xloc = xloc.bar_time,extend = extend.right))
if showInternalOrderBlocksInput
for index = 1 to internalOrderBlocksSizeInput
internalOrderBlocksBoxes.push(box.new(na,na,na,na,xloc = xloc.bar_time,extend = extend.right))
// @variable source to use in bearish order blocks mitigation
bearishOrderBlockMitigationSource = orderBlockMitigationInput == CLOSE ? close : high
// @variable source to use in bullish order blocks mitigation
bullishOrderBlockMitigationSource = orderBlockMitigationInput == CLOSE ? close : low
// @variable default volatility measure
atrMeasure = ta.atr(200)
// @variable parsed volatility measure by user settings
volatilityMeasure = orderBlockFilterInput == ATR ? atrMeasure : ta.cum(ta.tr)/bar_index
// @variable true if current bar is a high volatility bar
highVolatilityBar = (high - low) >= (2 * volatilityMeasure)
// @variable parsed high
parsedHigh = highVolatilityBar ? low : high
// @variable parsed low
parsedLow = highVolatilityBar ? high : low
// we store current values into the arrays at each bar
parsedHighs.push(parsedHigh)
parsedLows.push(parsedLow)
highs.push(high)
lows.push(low)
times.push(time)
leg(int size) =>
var leg = 0
newLegHigh = high > ta.highest( size)
newLegLow = low < ta.lowest( size)
if newLegHigh
leg := BEARISH_LEG
else if newLegLow
leg := BULLISH_LEG
leg
startOfNewLeg(int leg) => ta.change(leg) != 0
startOfBearishLeg(int leg) => ta.change(leg) == -1
startOfBullishLeg(int leg) => ta.change(leg) == +1
drawLabel(int labelTime, float labelPrice, string tag, color labelColor, string labelStyle) =>
var label l_abel = na
if modeInput == PRESENT
l_abel.delete()
l_abel := label.new(chart.point.new(labelTime,na,labelPrice),tag,xloc.bar_time,color=color(na),textcolor=labelColor,style = labelStyle,size = size.small)
drawEqualHighLow(pivot p_ivot, float level, int size, bool equalHigh) =>
equalDisplay e_qualDisplay = equalHigh ? equalHighDisplay : equalLowDisplay
string tag = 'EQL'
color equalColor = swingBullishColor
string labelStyle = label.style_label_up
if equalHigh
tag := 'EQH'
equalColor := swingBearishColor
labelStyle := label.style_label_down
if modeInput == PRESENT
line.delete( e_qualDisplay.l_ine)
label.delete( e_qualDisplay.l_abel)
e_qualDisplay.l_ine := line.new(chart.point.new(p_ivot.barTime,na,p_ivot.currentLevel), chart.point.new(time ,na,level), xloc = xloc.bar_time, color = equalColor, style = line.style_dotted)
labelPosition = math.round(0.5*(p_ivot.barIndex + bar_index - size))
e_qualDisplay.l_abel := label.new(chart.point.new(na,labelPosition,level), tag, xloc.bar_index, color = color(na), textcolor = equalColor, style = labelStyle, size = equalHighsLowsSizeInput)
getCurrentStructure(int size,bool equalHighLow = false, bool internal = false) =>
currentLeg = leg(size)
newPivot = startOfNewLeg(currentLeg)
pivotLow = startOfBullishLeg(currentLeg)
pivotHigh = startOfBearishLeg(currentLeg)
if newPivot
if pivotLow
pivot p_ivot = equalHighLow ? equalLow : internal ? internalLow : swingLow
if equalHighLow and math.abs(p_ivot.currentLevel - low ) < equalHighsLowsThresholdInput * atrMeasure
drawEqualHighLow(p_ivot, low , size, false)
p_ivot.lastLevel := p_ivot.currentLevel
p_ivot.currentLevel := low
p_ivot.crossed := false
p_ivot.barTime := time
p_ivot.barIndex := bar_index
if not equalHighLow and not internal
trailing.bottom := p_ivot.currentLevel
trailing.barTime := p_ivot.barTime
trailing.barIndex := p_ivot.barIndex
trailing.lastBottomTime := p_ivot.barTime
if showSwingsInput and not internal and not equalHighLow
drawLabel(time , p_ivot.currentLevel, p_ivot.currentLevel < p_ivot.lastLevel ? 'LL' : 'HL', swingBullishColor, label.style_label_up)
else
pivot p_ivot = equalHighLow ? equalHigh : internal ? internalHigh : swingHigh
if equalHighLow and math.abs(p_ivot.currentLevel - high ) < equalHighsLowsThresholdInput * atrMeasure
drawEqualHighLow(p_ivot,high ,size,true)
p_ivot.lastLevel := p_ivot.currentLevel
p_ivot.currentLevel := high
p_ivot.crossed := false
p_ivot.barTime := time
p_ivot.barIndex := bar_index
if not equalHighLow and not internal
trailing.top := p_ivot.currentLevel
trailing.barTime := p_ivot.barTime
trailing.barIndex := p_ivot.barIndex
trailing.lastTopTime := p_ivot.barTime
if showSwingsInput and not internal and not equalHighLow
drawLabel(time , p_ivot.currentLevel, p_ivot.currentLevel > p_ivot.lastLevel ? 'HH' : 'LH', swingBearishColor, label.style_label_down)
drawStructure(pivot p_ivot, string tag, color structureColor, string lineStyle, string labelStyle, string labelSize) =>
var line l_ine = line.new(na,na,na,na,xloc = xloc.bar_time)
var label l_abel = label.new(na,na)
if modeInput == PRESENT
l_ine.delete()
l_abel.delete()
l_ine := line.new(chart.point.new(p_ivot.barTime,na,p_ivot.currentLevel), chart.point.new(time,na,p_ivot.currentLevel), xloc.bar_time, color=structureColor, style=lineStyle)
l_abel := label.new(chart.point.new(na,math.round(0.5*(p_ivot.barIndex+bar_index)),p_ivot.currentLevel), tag, xloc.bar_index, color=color(na), textcolor=structureColor, style=labelStyle, size = labelSize)
deleteOrderBlocks(bool internal = false) =>
array orderBlocks = internal ? internalOrderBlocks : swingOrderBlocks
for in orderBlocks
bool crossedOderBlock = false
if bearishOrderBlockMitigationSource > eachOrderBlock.barHigh and eachOrderBlock.bias == BEARISH
crossedOderBlock := true
if internal
currentAlerts.internalBearishOrderBlock := true
else
currentAlerts.swingBearishOrderBlock := true
else if bullishOrderBlockMitigationSource < eachOrderBlock.barLow and eachOrderBlock.bias == BULLISH
crossedOderBlock := true
if internal
currentAlerts.internalBullishOrderBlock := true
else
currentAlerts.swingBullishOrderBlock := true
if crossedOderBlock
orderBlocks.remove(index)
storeOrdeBlock(pivot p_ivot,bool internal = false,int bias) =>
if (not internal and showSwingOrderBlocksInput) or (internal and showInternalOrderBlocksInput)
array a_rray = na
int parsedIndex = na
if bias == BEARISH
a_rray := parsedHighs.slice(p_ivot.barIndex,bar_index)
parsedIndex := p_ivot.barIndex + a_rray.indexof(a_rray.max())
else
a_rray := parsedLows.slice(p_ivot.barIndex,bar_index)
parsedIndex := p_ivot.barIndex + a_rray.indexof(a_rray.min())
orderBlock o_rderBlock = orderBlock.new(parsedHighs.get(parsedIndex), parsedLows.get(parsedIndex), times.get(parsedIndex),bias)
array orderBlocks = internal ? internalOrderBlocks : swingOrderBlocks
if orderBlocks.size() >= 100
orderBlocks.pop()
orderBlocks.unshift(o_rderBlock)
drawOrderBlocks(bool internal = false) =>
array orderBlocks = internal ? internalOrderBlocks : swingOrderBlocks
orderBlocksSize = orderBlocks.size()
if orderBlocksSize > 0
maxOrderBlocks = internal ? internalOrderBlocksSizeInput : swingOrderBlocksSizeInput
array parsedOrdeBlocks = orderBlocks.slice(0, math.min(maxOrderBlocks,orderBlocksSize))
array b_oxes = internal ? internalOrderBlocksBoxes : swingOrderBlocksBoxes
for in parsedOrdeBlocks
orderBlockColor = styleInput == MONOCHROME ? (eachOrderBlock.bias == BEARISH ? color.new(MONO_BEARISH,80) : color.new(MONO_BULLISH,80)) : internal ? (eachOrderBlock.bias == BEARISH ? internalBearishOrderBlockColor : internalBullishOrderBlockColor) : (eachOrderBlock.bias == BEARISH ? swingBearishOrderBlockColor : swingBullishOrderBlockColor)
box b_ox = b_oxes.get(index)
b_ox.set_top_left_point( chart.point.new(eachOrderBlock.barTime,na,eachOrderBlock.barHigh))
b_ox.set_bottom_right_point(chart.point.new(last_bar_time,na,eachOrderBlock.barLow))
b_ox.set_border_color( internal ? na : orderBlockColor)
b_ox.set_bgcolor( orderBlockColor)
displayStructure(bool internal = false) =>
var bullishBar = true
var bearishBar = true
if internalFilterConfluenceInput
bullishBar := high - math.max(close, open) > math.min(close, open - low)
bearishBar := high - math.max(close, open) < math.min(close, open - low)
pivot p_ivot = internal ? internalHigh : swingHigh
trend t_rend = internal ? internalTrend : swingTrend
lineStyle = internal ? line.style_dashed : line.style_solid
labelSize = internal ? internalStructureSize : swingStructureSize
extraCondition = internal ? internalHigh.currentLevel != swingHigh.currentLevel and bullishBar : true
bullishColor = styleInput == MONOCHROME ? MONO_BULLISH : internal ? internalBullColorInput : swingBullColorInput
if ta.crossover(close,p_ivot.currentLevel) and not p_ivot.crossed and extraCondition
string tag = t_rend.bias == BEARISH ? CHOCH : BOS
if internal
currentAlerts.internalBullishCHoCH := tag == CHOCH
currentAlerts.internalBullishBOS := tag == BOS
else
currentAlerts.swingBullishCHoCH := tag == CHOCH
currentAlerts.swingBullishBOS := tag == BOS
p_ivot.crossed := true
t_rend.bias := BULLISH
displayCondition = internal ? showInternalsInput and (showInternalBullInput == ALL or (showInternalBullInput == BOS and tag != CHOCH) or (showInternalBullInput == CHOCH and tag == CHOCH)) : showStructureInput and (showSwingBullInput == ALL or (showSwingBullInput == BOS and tag != CHOCH) or (showSwingBullInput == CHOCH and tag == CHOCH))
if displayCondition
drawStructure(p_ivot,tag,bullishColor,lineStyle,label.style_label_down,labelSize)
if (internal and showInternalOrderBlocksInput) or (not internal and showSwingOrderBlocksInput)
storeOrdeBlock(p_ivot,internal,BULLISH)
p_ivot := internal ? internalLow : swingLow
extraCondition := internal ? internalLow.currentLevel != swingLow.currentLevel and bearishBar : true
bearishColor = styleInput == MONOCHROME ? MONO_BEARISH : internal ? internalBearColorInput : swingBearColorInput
if ta.crossunder(close,p_ivot.currentLevel) and not p_ivot.crossed and extraCondition
string tag = t_rend.bias == BULLISH ? CHOCH : BOS
if internal
currentAlerts.internalBearishCHoCH := tag == CHOCH
currentAlerts.internalBearishBOS := tag == BOS
else
currentAlerts.swingBearishCHoCH := tag == CHOCH
currentAlerts.swingBearishBOS := tag == BOS
p_ivot.crossed := true
t_rend.bias := BEARISH
displayCondition = internal ? showInternalsInput and (showInternalBearInput == ALL or (showInternalBearInput == BOS and tag != CHOCH) or (showInternalBearInput == CHOCH and tag == CHOCH)) : showStructureInput and (showSwingBearInput == ALL or (showSwingBearInput == BOS and tag != CHOCH) or (showSwingBearInput == CHOCH and tag == CHOCH))
if displayCondition
drawStructure(p_ivot,tag,bearishColor,lineStyle,label.style_label_up,labelSize)
if (internal and showInternalOrderBlocksInput) or (not internal and showSwingOrderBlocksInput)
storeOrdeBlock(p_ivot,internal,BEARISH)
fairValueGapBox(leftTime,rightTime,topPrice,bottomPrice,boxColor) => box.new(chart.point.new(leftTime,na,topPrice),chart.point.new(rightTime + fairValueGapsExtendInput * (time-time ),na,bottomPrice), xloc=xloc.bar_time, border_color = boxColor, bgcolor = boxColor)
deleteFairValueGaps() =>
for in fairValueGaps
if (low < eachFairValueGap.bottom and eachFairValueGap.bias == BULLISH) or (high > eachFairValueGap.top and eachFairValueGap.bias == BEARISH)
eachFairValueGap.topBox.delete()
eachFairValueGap.bottomBox.delete()
fairValueGaps.remove(index)
// @function draw fair value gaps
// @returns fairValueGap ID
drawFairValueGaps() =>
= request.security(syminfo.tickerid, fairValueGapsTimeframeInput, [close , open , time , high , low , time , high , low ],lookahead = barmerge.lookahead_on)
barDeltaPercent = (lastClose - lastOpen) / (lastOpen * 100)
newTimeframe = timeframe.change(fairValueGapsTimeframeInput)
threshold = fairValueGapsThresholdInput ? ta.cum(math.abs(newTimeframe ? barDeltaPercent : 0)) / bar_index * 2 : 0
bullishFairValueGap = currentLow > last2High and lastClose > last2High and barDeltaPercent > threshold and newTimeframe
bearishFairValueGap = currentHigh < last2Low and lastClose < last2Low and -barDeltaPercent > threshold and newTimeframe
if bullishFairValueGap
currentAlerts.bullishFairValueGap := true
fairValueGaps.unshift(fairValueGap.new(currentLow,last2High,BULLISH,fairValueGapBox(lastTime,currentTime,currentLow,math.avg(currentLow,last2High),fairValueGapBullishColor),fairValueGapBox(lastTime,currentTime,math.avg(currentLow,last2High),last2High,fairValueGapBullishColor)))
if bearishFairValueGap
currentAlerts.bearishFairValueGap := true
fairValueGaps.unshift(fairValueGap.new(currentHigh,last2Low,BEARISH,fairValueGapBox(lastTime,currentTime,currentHigh,math.avg(currentHigh,last2Low),fairValueGapBearishColor),fairValueGapBox(lastTime,currentTime,math.avg(currentHigh,last2Low),last2Low,fairValueGapBearishColor)))
getStyle(string style) =>
switch style
SOLID => line.style_solid
DASHED => line.style_dashed
DOTTED => line.style_dotted
drawLevels(string timeframe, bool sameTimeframe, string style, color levelColor) =>
= request.security(syminfo.tickerid, timeframe, [high , low , time , time],lookahead = barmerge.lookahead_on)
float parsedTop = sameTimeframe ? high : topLevel
float parsedBottom = sameTimeframe ? low : bottomLevel
int parsedLeftTime = sameTimeframe ? time : leftTime
int parsedRightTime = sameTimeframe ? time : rightTime
int parsedTopTime = time
int parsedBottomTime = time
if not sameTimeframe
int leftIndex = times.binary_search_rightmost(parsedLeftTime)
int rightIndex = times.binary_search_rightmost(parsedRightTime)
array timeArray = times.slice(leftIndex,rightIndex)
array topArray = highs.slice(leftIndex,rightIndex)
array bottomArray = lows.slice(leftIndex,rightIndex)
parsedTopTime := timeArray.size() > 0 ? timeArray.get(topArray.indexof(topArray.max())) : initialTime
parsedBottomTime := timeArray.size() > 0 ? timeArray.get(bottomArray.indexof(bottomArray.min())) : initialTime
var line topLine = line.new(na, na, na, na, xloc = xloc.bar_time, color = levelColor, style = getStyle(style))
var line bottomLine = line.new(na, na, na, na, xloc = xloc.bar_time, color = levelColor, style = getStyle(style))
var label topLabel = label.new(na, na, xloc = xloc.bar_time, text = str.format('P{0}H',timeframe), color=color(na), textcolor = levelColor, size = size.small, style = label.style_label_left)
var label bottomLabel = label.new(na, na, xloc = xloc.bar_time, text = str.format('P{0}L',timeframe), color=color(na), textcolor = levelColor, size = size.small, style = label.style_label_left)
topLine.set_first_point( chart.point.new(parsedTopTime,na,parsedTop))
topLine.set_second_point( chart.point.new(last_bar_time + 20 * (time-time ),na,parsedTop))
topLabel.set_point( chart.point.new(last_bar_time + 20 * (time-time ),na,parsedTop))
bottomLine.set_first_point( chart.point.new(parsedBottomTime,na,parsedBottom))
bottomLine.set_second_point(chart.point.new(last_bar_time + 20 * (time-time ),na,parsedBottom))
bottomLabel.set_point( chart.point.new(last_bar_time + 20 * (time-time ),na,parsedBottom))
higherTimeframe(string timeframe) => timeframe.in_seconds() > timeframe.in_seconds(timeframe)
updateTrailingExtremes() =>
trailing.top := math.max(high,trailing.top)
trailing.lastTopTime := trailing.top == high ? time : trailing.lastTopTime
trailing.bottom := math.min(low,trailing.bottom)
trailing.lastBottomTime := trailing.bottom == low ? time : trailing.lastBottomTime
drawHighLowSwings() =>
var line topLine = line.new(na, na, na, na, color = swingBearishColor, xloc = xloc.bar_time)
var line bottomLine = line.new(na, na, na, na, color = swingBullishColor, xloc = xloc.bar_time)
var label topLabel = label.new(na, na, color=color(na), textcolor = swingBearishColor, xloc = xloc.bar_time, style = label.style_label_down, size = size.tiny)
var label bottomLabel = label.new(na, na, color=color(na), textcolor = swingBullishColor, xloc = xloc.bar_time, style = label.style_label_up, size = size.tiny)
rightTimeBar = last_bar_time + 20 * (time - time )
topLine.set_first_point( chart.point.new(trailing.lastTopTime, na, trailing.top))
topLine.set_second_point( chart.point.new(rightTimeBar, na, trailing.top))
topLabel.set_point( chart.point.new(rightTimeBar, na, trailing.top))
topLabel.set_text( swingTrend.bias == BEARISH ? 'Strong High' : 'Weak High')
bottomLine.set_first_point( chart.point.new(trailing.lastBottomTime, na, trailing.bottom))
bottomLine.set_second_point(chart.point.new(rightTimeBar, na, trailing.bottom))
bottomLabel.set_point( chart.point.new(rightTimeBar, na, trailing.bottom))
bottomLabel.set_text( swingTrend.bias == BULLISH ? 'Strong Low' : 'Weak Low')
drawZone(float labelLevel, int labelIndex, float top, float bottom, string tag, color zoneColor, string style) =>
var label l_abel = label.new(na,na,text = tag, color=color(na),textcolor = zoneColor, style = style, size = size.small)
var box b_ox = box.new(na,na,na,na,bgcolor = color.new(zoneColor,80),border_color = color(na), xloc = xloc.bar_time)
b_ox.set_top_left_point( chart.point.new(trailing.barTime,na,top))
b_ox.set_bottom_right_point(chart.point.new(last_bar_time,na,bottom))
l_abel.set_point( chart.point.new(na,labelIndex,labelLevel))
// @function draw premium/discount zones
// @returns void
drawPremiumDiscountZones() =>
drawZone(trailing.top, math.round(0.5*(trailing.barIndex + last_bar_index)), trailing.top, 0.95*trailing.top + 0.05*trailing.bottom, 'Premium', premiumZoneColor, label.style_label_down)
equilibriumLevel = math.avg(trailing.top, trailing.bottom)
drawZone(equilibriumLevel, last_bar_index, 0.525*trailing.top + 0.475*trailing.bottom, 0.525*trailing.bottom + 0.475*trailing.top, 'Equilibrium', equilibriumZoneColorInput, label.style_label_left)
drawZone(trailing.bottom, math.round(0.5*(trailing.barIndex + last_bar_index)), 0.95*trailing.bottom + 0.05*trailing.top, trailing.bottom, 'Discount', discountZoneColor, label.style_label_up)
parsedOpen = showTrendInput ? open : na
candleColor = internalTrend.bias == BULLISH ? swingBullishColor : swingBearishColor
plotcandle(parsedOpen,high,low,close,color = candleColor, wickcolor = candleColor, bordercolor = candleColor)
if showHighLowSwingsInput or showPremiumDiscountZonesInput
updateTrailingExtremes()
if showHighLowSwingsInput
drawHighLowSwings()
if showPremiumDiscountZonesInput
drawPremiumDiscountZones()
if showFairValueGapsInput
deleteFairValueGaps()
getCurrentStructure(swingsLengthInput,false)
getCurrentStructure(5,false,true)
if showEqualHighsLowsInput
getCurrentStructure(equalHighsLowsLengthInput,true)
if showInternalsInput or showInternalOrderBlocksInput or showTrendInput
displayStructure(true)
if showStructureInput or showSwingOrderBlocksInput or showHighLowSwingsInput
displayStructure()
if showInternalOrderBlocksInput
deleteOrderBlocks(true)
if showSwingOrderBlocksInput
deleteOrderBlocks()
if showFairValueGapsInput
drawFairValueGaps()
if barstate.islastconfirmedhistory or barstate.islast
if showInternalOrderBlocksInput
drawOrderBlocks(true)
if showSwingOrderBlocksInput
drawOrderBlocks()
lastBarIndex := currentBarIndex
currentBarIndex := bar_index
newBar = currentBarIndex != lastBarIndex
if barstate.islastconfirmedhistory or (barstate.isrealtime and newBar)
if showDailyLevelsInput and not higherTimeframe('D')
drawLevels('D',timeframe.isdaily,dailyLevelsStyleInput,dailyLevelsColorInput)
if showWeeklyLevelsInput and not higherTimeframe('W')
drawLevels('W',timeframe.isweekly,weeklyLevelsStyleInput,weeklyLevelsColorInput)
if showMonthlyLevelsInput and not higherTimeframe('M')
drawLevels('M',timeframe.ismonthly,monthlyLevelsStyleInput,monthlyLevelsColorInput)
xATR = ta.atr(c)
nLoss = a * xATR
src = h ? request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close, lookahead = barmerge.lookahead_off) : close
xATRTrailingStop = 0.0
iff_1 = src > nz(xATRTrailingStop , 0) ? src - nLoss : src + nLoss
iff_2 = src < nz(xATRTrailingStop , 0) and src < nz(xATRTrailingStop , 0) ? math.min(nz(xATRTrailingStop ), src + nLoss) : iff_1
xATRTrailingStop := src > nz(xATRTrailingStop , 0) and src > nz(xATRTrailingStop , 0) ? math.max(nz(xATRTrailingStop ), src - nLoss) : iff_2
pos = 0
iff_3 = src > nz(xATRTrailingStop , 0) and src < nz(xATRTrailingStop , 0) ? -1 : nz(pos , 0)
pos := src < nz(xATRTrailingStop , 0) and src > nz(xATRTrailingStop , 0) ? 1 : iff_3
xcolor = pos == -1 ? color.red : pos == 1 ? color.green : color.blue
ema = ta.ema(src, 1)
above = ta.crossover(ema, xATRTrailingStop)
below = ta.crossover(xATRTrailingStop, ema)
buy = src > xATRTrailingStop and above
sell = src < xATRTrailingStop and below
barbuy = src > xATRTrailingStop
barsell = src < xATRTrailingStop
//---------------------------------------------------------------------------------------------------------------------}
//ALERTS
//---------------------------------------------------------------------------------------------------------------------{
alertcondition(currentAlerts.internalBullishBOS, 'Internal Bullish BOS', 'Internal Bullish BOS formed')
alertcondition(currentAlerts.internalBullishCHoCH, 'Internal Bullish CHoCH', 'Internal Bullish CHoCH formed')
alertcondition(currentAlerts.internalBearishBOS, 'Internal Bearish BOS', 'Internal Bearish BOS formed')
alertcondition(currentAlerts.internalBearishCHoCH, 'Internal Bearish CHoCH', 'Internal Bearish CHoCH formed')
alertcondition(currentAlerts.swingBullishBOS, 'Bullish BOS', 'Internal Bullish BOS formed')
alertcondition(currentAlerts.swingBullishCHoCH, 'Bullish CHoCH', 'Internal Bullish CHoCH formed')
alertcondition(currentAlerts.swingBearishBOS, 'Bearish BOS', 'Bearish BOS formed')
alertcondition(currentAlerts.swingBearishCHoCH, 'Bearish CHoCH', 'Bearish CHoCH formed')
alertcondition(currentAlerts.internalBullishOrderBlock, 'Bullish Internal OB Breakout', 'Price broke bullish internal OB')
alertcondition(currentAlerts.internalBearishOrderBlock, 'Bearish Internal OB Breakout', 'Price broke bearish internal OB')
alertcondition(currentAlerts.swingBullishOrderBlock, 'Bullish Swing OB Breakout', 'Price broke bullish swing OB')
alertcondition(currentAlerts.swingBearishOrderBlock, 'Bearish Swing OB Breakout', 'Price broke bearish swing OB')
alertcondition(currentAlerts.equalHighs, 'Equal Highs', 'Equal highs detected')
alertcondition(currentAlerts.equalLows, 'Equal Lows', 'Equal lows detected')
alertcondition(currentAlerts.bullishFairValueGap, 'Bullish FVG', 'Bullish FVG formed')
alertcondition(currentAlerts.bearishFairValueGap, 'Bearish FVG', 'Bearish FVG formed')
alertcondition(buy, 'UT Long', 'UT Long')
alertcondition(sell, 'UT Short', 'UT Short')
plotshape(buy, title = 'Buy', text = 'Buy', style = shape.labelup, location = location.belowbar, color = color.new(color.green, 0), textcolor = color.new(color.white, 0), size = size.tiny)
plotshape(sell, title = 'Sell', text = 'Sell', style = shape.labeldown, location = location.abovebar, color = color.new(color.red, 0), textcolor = color.new(color.white, 0), size = size.tiny)
//--------------------------------------------------------------------------------------
// EMA ADDITIONS (Editable)
//--------------------------------------------------------------------------------------
ema5Len = input.int(5, "5 EMA Length", minval = 1)
ema9Len = input.int(9, "9 EMA Length", minval = 1)
ema5 = ta.ema(src, ema5Len)
ema9 = ta.ema(src, ema9Len)
plot(ema5, "EMA 5", color = color.red, linewidth = 2)
plot(ema9, "EMA 9", color = color.blue, linewidth = 2)
barcolor(barbuy ? color.green : na)
barcolor(barsell ? color.red : na)






















