Follow BreakoutThe indicator tracks trend breakouts. It generates multiple signals during sideways trends.
Cycles
Atlas 8 Currency Session Momentum (6H, London)This indicator calculates real-time currency strength for the 8 major currencies (USD, EUR, GBP, JPY, AUD, NZD, CAD, CHF) using a balanced multi-pair engine and a 6-hour momentum reset.
🔍 How it works
The indicator computes the relative strength of each currency by averaging the percentage change of 7 major cross-pairs for each currency.
A currency's value increases when pairs where it is the base appreciate, and decreases when pairs where it is the quote depreciate.
This creates a symmetric and stable strength calculation similar to institutional relative-value models.
🕒 Session-based Momentum Reset
The global trading day is split into 4 × 6-hour blocks:
• 00:00–06:00 Tokyo
• 06:00–12:00 London
• 12:00–18:00 New York
• 18:00–24:00 Late US/Asia pre-open
At each new 6-hour session, all strength lines reset to 0.
This highlights fresh intraday momentum generated by liquidity transitions between sessions.
🎯 What the indicator shows
• Relative strength of all 8 currencies
• Smooth momentum curves using EMA smoothing
• Vertical dividers at each new session
• Background color for each session
• Real intraday build-up of strength/weakness (not cumulative from previous day)
This tool is designed for intraday traders who follow cross-currency momentum during session transitions (Tokyo → London → NY).
🧭 How to use it
• Look for the strongest vs weakest currency after each session reset
• Identify fresh trends during London and NY opens
• Confirm currency-pair bias using strength divergence
• Track momentum exhaustion when lines flatten or converge
Thirdeyechart Gold DoomsdayThirdeyechart Gold Doomsday – Full Description
Thirdeyechart Gold Simulation Final 3 is a professional-grade TradingView indicator designed to monitor the global gold market across multiple XAU pairs simultaneously. This version is engineered to provide a complete, multi-timeframe view of gold’s momentum while incorporating buy/sell simulation, trend strength, and safe/unsafe trade detection, all in a clean, visually organized table.
Key Functions and Features
Custom Pairs Input
Traders can specify any number of XAU-related pairs using a comma-separated input.
The script dynamically handles all pairs without requiring manual adjustments.
Percent Change Function (f_change)
Calculates the percentage change for a given symbol and timeframe:
pct_change = ((close_tf - open_tf) / open_tf) * 100
Supports weekly (W), daily (D), 4-hour (H4), and 1-hour (H1) timeframes.
Positive changes are colored blue, negative changes red for instant visual assessment.
Table Setup
Dynamically generates a table based on the number of XAU pairs.
Displays Symbol, Week %, Day %, H4 %, H1 %, BuySim, SellSim in a clean, boxed format.
Color-coded cells for easy recognition of positive vs negative momentum.
Buy & Sell Simulation
Separates each timeframe into positive (buy) and negative (sell) contributions:
Positive value → added to BuySim
Negative value → added to SellSim
Summed across all timeframes per symbol, allowing a macro-level simulation of market pressure.
Total BuySim / SellSim provides a clear view of dominance without signaling actual trades.
Total Row Calculation
Sums Week, Day, H4, H1 across all symbols to show aggregate market movement.
BuySim and SellSim totals highlight overall market pressure.
Provides context for trend alignment across multiple pairs.
Strength Row (f_strength)
Interprets total movement per timeframe:
>0 → Strong
<0 → Weak
0 → Neutral
Combined with BuySim/SellSim to display a trend bias: “Buy Bias” or “Sell Bias.”
Safe / Unsafe Trade Detection
Compares total BuySim and SellSim:
distance = abs(totalBuy - totalSell)
threshold = totalAll * 0.50
Trade considered safe if distance ≥ threshold → green label.
Trade considered unsafe if distance < threshold → red label.
Provides a reasoning context (e.g., “clear dominance by buyers” or “sellers can dominate the market”), allowing quick risk assessment.
This function ensures traders know whether market momentum is decisive or uncertain.
Visual Design
Uses background colors for header, cells, total, and strength rows to improve readability.
All data is organized in a compact, easy-to-read table, with dynamic scaling depending on the number of pairs.
Why This Indicator is Advanced
Multi-Timeframe Analysis: Simultaneously monitors W, D, H4, H1 for each XAU pair.
Global Perspective: Shows aggregated momentum across 8 gold pairs to track overall market direction.
Risk Awareness: Safe/Unsafe trade detection helps identify strong trends versus indecisive conditions.
Institutional Approach: Combines global data and technical calculation similar to professional trading terminals.
Disclaimer
This indicator is educational and analytical only. It does not provide financial advice or direct trade signals. Users are responsible for their own trading decisions, and all markets carry risk.
© 2025 Thirdeyechart. All rights reserved. Redistribution or commercial use without permission is prohibited.
dr ram's banknifty fad%banknifty fad% calculation as per dr ram sir. based on 4 quadrant analysis . one of the criteria is calculating future asset difference for predicting market direction and entry plan.
Ultra Reversion DCA Strategy with Manual Leverage - V.1Ultra Reversion DCA Strategy with Manual Leverage - V.1
2025-10-27
HTF FVG + SessionsThis indicator combines multi-timeframe FVG A–C detection with intraday session boxes on a single chart.
It automatically finds bullish and bearish Fair Value Gaps on 15m, 30m, 1H, 4H, 1D and 1W timeframes.
Fresh FVGs are drawn in a transparent gold color, then dynamically shrink as price trades back into the gap.
Once price fully fills the gap, the FVG box and its label are automatically removed from the chart.
After the first touch, each FVG changes to a per-timeframe gray shade, making overlapping HTF gaps easy to see.
You can toggle each timeframe on/off and also globally enable/disable all FVGs from the settings panel.
Session boxes highlight Asia, London, NY AM, NY Lunch and NY PM using soft colored rectangles.
Each session box is plotted from the high to the low of that session and labeled with its name in white text.
A global “Show all session boxes” switch allows you to quickly hide or display the session structure.
This tool is designed for traders who want to combine FVG liquidity maps with clear intraday session context.
Adaptive Trend Navigator [ATH Filter & Risk Engine]Description:
This strategy implements a systematic Trend Following approach designed to capture major moves while actively protecting capital during severe bear markets. It combines a classic Moving Average "Fan" logic with two advanced risk management layers: a 4-Stage Dynamic Stop Loss and a macro-economic "Circuit Breaker" filter.
Core Concepts:
1. Trend Identification (Entry Logic) The script uses a cascade of Simple Moving Averages (SMA 25, 50, 100, 200) to identify the maturity of a trend.
Entries are triggered by specific crossovers (e.g., SMA 25 crossing SMA 50) or by breaking above the previous trade's high ("High-Water Mark" Re-Entry).
2. The "Circuit Breaker" (Crash Protection) To prevent trading during historical market collapses (like 2000 or 2008), the strategy monitors the Nasdaq 100 (QQQ) as a global benchmark:
Normal Regime: If the market is within 20% of its All-Time High, the strategy operates normally.
Crisis Regime: If the QQQ falls more than 20% from its ATH, the "Circuit Breaker" activates (Visualized by a Red Background).
Recovery Rule: In a Crisis Regime, new long positions are blocked unless the QQQ reclaims its SMA 200. This filters out "bull traps" in secular bear markets.
3. 4-Stage Risk Engine (Exit Logic) Once in a trade, the risk management adapts to the position's performance:
Stage 1: Fixed initial Stop Loss (default 10%) for breathing room.
Stage 2: Moves to Break-Even area once the price rises 12%.
Stage 3: Tightens to a trailing stop (8%) after 25% profit.
Stage 4: Maximizes gains with a tight trailing stop (5%) during parabolic moves (>40% profit).
Visual Guide:
SMAs: 25/50/100/200 period lines for trend visualization.
Red Background: Indicates the "Crisis Regime" where trading is halted due to broad market weakness.
Blue Background: Indicates a "Recovery Phase" (Crisis is active, but market is above SMA 200).
Red Line: Shows the dynamic Stop Loss level for active positions.
Settings: All parameters (SMA lengths, Drawdown threshold, Risk Stages) are fully customizable. The QQQ benchmark ticker can also be changed to SPY or other indices depending on the asset class traded.
Dynamic SMA Trend System [Multi-Stage Risk Engine]Description:
This script implements a robust Trend Following strategy based on a multiple Simple Moving Average (SMA) crossover logic (25, 50, 100, 200). What sets this strategy apart is its advanced "4-Stage Risk Engine" and a smart "High-Water Mark" Re-Entry system, designed to protect profits during parabolic moves while filtering out chop during sideways markets.
How it works:
The strategy operates on three core pillars: Trend Identification, Dynamic Risk Management, and Momentum Re-Entry.
1. Entry Logic (Trend Identification) The script looks for crossovers at different trend stages to capture early reversals as well as established trends:
Short-Term: SMA 25 crosses over SMA 50.
Mid-Term: SMA 50 crosses over SMA 100.
Macro-Trend: SMA 100 crosses over SMA 200.
2. The 4-Stage Risk Engine (Dynamic Stop Loss) Instead of a static Stop Loss, this strategy uses a progressive system that adapts as the price increases:
Stage 1 (Protection): Starts with a fixed Stop Loss (default -10%) to give the trade room to breathe.
Stage 2 (Break-Even): Once the price rises by 12%, the Stop is moved to trailing mode (10% distance), effectively securing a near break-even state.
Stage 3 (Profit Locking): At 25% profit, the trailing stop tightens to 8% to lock in gains.
Stage 4 (Parabolic Mode): At 40% profit, the trailing stop tightens further to 5% to capture the peak of parabolic moves.
3. Dual Exit Mechanism The strategy exits a position if EITHER of the following happens:
Stop Loss Hit: Price falls below the dynamic red line (Risk Engine).
Dead Cross: The trend structure breaks (e.g., SMA 25 crosses under SMA 50), signaling a momentum loss even if the Stop Loss wasn't hit.
4. "High-Water Mark" Re-Entry To avoid "whipsaws" in choppy markets, the script does not re-enter immediately after a stop-out.
It marks the highest price of the previous trade (Green Dotted Line).
A Re-Entry only occurs if the price breaks above this previous high (showing renewed strength) AND the long-term trend is bullish (Price > SMA 200).
Visuals:
SMAs: 25 (Yellow), 50 (Orange), 100 (Blue), 200 (White).
Red Line: Visualizes the dynamic Stop Loss level.
Green Dots: Visualizes the target price needed for a valid re-entry.
Settings: All parameters (SMA lengths, Stop Loss percentages, Staging triggers) are fully customizable in the settings menu to fit different assets (Crypto, Stocks, Forex) and timeframes.
Viprasol Elite Flow Pro - Premium Order Flow & Trend System═══════════════════════════════════════════════════════════════
🔥 VIPRASOL ELITE FLOW PRO
Professional Order Flow & Trend Detection System
═══════════════════════════════════════════════════════════════
📊 WHAT IS THIS INDICATOR?
Viprasol Elite Flow Pro is a comprehensive trading system that combines institutional order flow analysis with adaptive trend detection. Unlike basic indicators, this tool identifies high-probability setups by analyzing where smart money is likely positioning, while filtering signals through multiple confirmation layers.
This indicator is designed for traders who want to:
✓ Identify premium (supply) and discount (demand) zones automatically
✓ Detect trend direction with adaptive cloud technology
✓ Spot high-volume rejection points before major moves
✓ Filter low-quality signals with intelligent confirmation logic
✓ Track market strength in real-time via elite dashboard
═══════════════════════════════════════════════════════════════
🎯 CORE FEATURES
═══════════════════════════════════════════════════════════════
1️⃣ ELITE TREND ENGINE
• Adaptive Moving Average system (Fast/Adaptive/Smooth modes)
• Dynamic trend cloud that expands/contracts with volatility
• Real-time trend state tracking (Bullish/Bearish/Ranging)
• Trend strength meter (0-10 scale)
• ATR-based volatility adjustments
2️⃣ ORDER FLOW DETECTION
• Automatic Premium Zone (Supply) identification
• Automatic Discount Zone (Demand) identification
• Smart zone extension - zones remain valid until broken
• Zone rejection detection with price action confirmation
• Customizable zone strength (5-30 bars lookback)
3️⃣ VOLUME INTELLIGENCE
• Volume spike detection (configurable threshold)
• Climax bar identification (exhaustion signals)
• Volume filter for signal validation
• Institutional activity detection
4️⃣ SMART SIGNAL SYSTEM
• 3 Signal Modes: Aggressive, Balanced, Conservative
• Multi-layer confirmation logic
• Automatic profit targets (2:1 risk-reward)
• Stop loss suggestions based on ATR
• Prevents overtrading with bars-since-signal filter
5️⃣ ELITE DASHBOARD (HUD)
• Real-time trend direction and strength
• Volume status monitoring
• Active zones counter
• Market volatility gauge
• Current signal status
• 4 positioning options, compact mode available
6️⃣ PREMIUM STYLING
• 4 Professional color themes (Cyber/Gold/Ocean/Fire)
• Adjustable transparency and label sizes
• Clean, institutional-grade visuals
• Optimized for all chart types
═══════════════════════════════════════════════════════════════
📖 HOW TO USE THIS INDICATOR
═══════════════════════════════════════════════════════════════
STEP 1: TREND IDENTIFICATION
→ Green Cloud = Bullish trend - look for LONG opportunities
→ Red Cloud = Bearish trend - look for SHORT opportunities
→ Purple Cloud = Ranging - wait for breakout or fade extremes
STEP 2: ZONE ANALYSIS
→ PREMIUM (Red) zones = Potential resistance/supply areas
→ DISCOUNT (Green) zones = Potential support/demand areas
→ Price rejecting from zones = high-probability setups
STEP 3: SIGNAL CONFIRMATION
→ Wait for "LONG" or "SHORT" labels to appear
→ Check dashboard for trend strength (Moderate/Strong preferred)
→ Confirm volume status is "HIGH" or "CLIMAX"
→ Entry: Enter when label appears
→ Stop Loss: Use dotted line (1 ATR away)
→ Take Profit: Use dashed line (2 ATR away)
STEP 4: RISK MANAGEMENT
→ Never risk more than 1-2% per trade
→ Use the provided stop loss levels
→ Trail stops as price moves in your favor
→ Avoid trading during low volatility periods
═══════════════════════════════════════════════════════════════
⚙️ RECOMMENDED SETTINGS
═══════════════════════════════════════════════════════════════
FOR SCALPING (1M - 5M):
- Trend Type: Fast
- Sensitivity: 15
- Signal Mode: Aggressive
- Zone Strength: 8
FOR DAY TRADING (15M - 1H):
- Trend Type: Adaptive
- Sensitivity: 21 (default)
- Signal Mode: Balanced
- Zone Strength: 12 (default)
FOR SWING TRADING (4H - Daily):
- Trend Type: Smooth
- Sensitivity: 34
- Signal Mode: Conservative
- Zone Strength: 20
BEST MARKETS:
✓ Crypto (BTC, ETH, major altcoins)
✓ Forex (Major pairs: EUR/USD, GBP/USD)
✓ Indices (S&P 500, NASDAQ, DAX)
✓ High-liquidity stocks
═══════════════════════════════════════════════════════════════
🎓 UNDERSTANDING THE METHODOLOGY
═══════════════════════════════════════════════════════════════
This indicator is built on three core concepts:
1. ORDER FLOW THEORY
Markets move between premium (expensive) and discount (cheap) zones. Smart money accumulates in discount zones and distributes in premium zones. This indicator identifies these zones automatically.
2. ADAPTIVE TREND FOLLOWING
Unlike fixed-period moving averages, the Elite Trend Engine adjusts to current market volatility, providing more accurate trend signals in both trending and ranging conditions.
3. CONFLUENCE-BASED ENTRIES
Signals only trigger when multiple conditions align:
- Price in correct zone (premium for shorts, discount for longs)
- Trend confirmation (cloud color matches direction)
- Volume validation (spike or climax present)
- Price action strength (strong rejection candles)
This multi-layer approach dramatically reduces false signals.
═══════════════════════════════════════════════════════════════
🔔 ALERT SETUP
═══════════════════════════════════════════════════════════════
This indicator includes 5 alert types:
1. Long Signal → Triggers when buy conditions met
2. Short Signal → Triggers when sell conditions met
3. Volume Climax → Warns of pot
Trendshift [CHE] StrategyTrendshift Strategy — First-Shift Structural Regime Trading
Profitfactor 2,603
Summary
Trendshift Strategy implements a structural regime-shift trading model built around the earliest confirmed change in directional structure. It identifies major swing highs and lows, validates breakouts through optional ATR-based conviction, and reacts only to the first confirmed shift in each direction. After a regime reversal, the strategy constructs a premium and discount band between the breakout candle and the previous opposite swing. This band is used as contextual bias and may optionally inform stop placement and position sizing.
The strategy focuses on clear, interpretable structural events rather than continuous signal generation. By limiting entries to the first valid shift, it reduces false recycles and allows the structural state to stabilize before a new trade occurs. All signals operate on closed-bar logic, and the strategy avoids higher-timeframe calls to stabilize execution behavior.
Motivation: Why this design?
Many structure-based systems repeatedly trigger as price fluctuates around prior highs and lows. This often leads to multiple flips during volatile or choppy conditions. Trendshift Strategy addresses this problem by restricting execution to the first confirmed structural event in each direction. ATR-based filters help differentiate genuine structural breaks from noise, while the contextual band ensures that the breakout is meaningful in relation to recent volatility.
The design aims to represent a minimalistic structural trading framework focused on regime turns rather than continuous trend signaling. This reduces chart noise and clarifies where the market transitions from one regime to another.
What’s different vs. standard approaches?
Baseline reference
Typical swing-based structure indicators report every break above or below recent swing points.
Architecture differences
First-shift-only regime logic that blocks repeated signals until direction reverses
ATR-filtered validation to avoid weak or momentum-less breaks
Premium and discount bands derived from breakout structure
Optional band-driven stop placement
Optional band-dependent position-sizing factor
Regime timeout system to neutralize structure after extended inactivity
Persistent-state architecture to prevent re-triggering
Practical effect
Only the earliest actionable structure change is traded
Fewer but higher-quality signals
Premium/discount tint assists contextual evaluation
Stops and sizing can be aligned with structural context rather than arbitrary volatility measures
Improved chart interpretability due to reduced marker frequency
How it works (technical)
The algorithm evaluates symmetric swing points using a fixed bar window. When a swing forms, its value and bar index are stored as persistent state. A structural shift occurs when price closes beyond the most recent major swing on the opposite side. If ATR filtering is enabled, the breakout must exceed a volatility-scaled distance to prevent micro-breaks from firing.
Once a valid shift is confirmed, the regime is updated to bullish or bearish. The script records the breakout level, the opposite swing, and derives a band between them. This band is checked for minimum size relative to ATR to avoid unrealistic contexts.
The first shift in a new direction generates both the strategy entry and a visual marker. Additional shifts in the same direction are suppressed until a reversal occurs. If a timeout is enabled, the regime resets after a specified number of bars without structural change, optionally clearing the band.
Stop placement, if enabled, uses either the opposite or same band edge depending on configuration. Position size is computed from account percentage and may optionally scale with the price-span-to-ATR relationship.
Parameter Guide
Market Structure
Swing length (default 5): Controls swing sensitivity. Lower values increase responsiveness.
Use ATR filter (default true): Requires breakouts to show momentum relative to ATR. Reduces false shifts.
ATR length (default 14): Volatility estimation for breakout and band validation.
Break ATR multiplier (default 1.0): Required breakout strength relative to ATR.
Premium/Discount Framework
Enable framework (default true): Activates premium/discount evaluation.
Persist band on timeout (default true): Keeps structural band after timeout.
Min band ATR mult (default 0.5): Rejects narrow bands.
Regime timeout bars (default 500): Neutralizes regime after inactivity.
Invert colors (default false): Color scheme toggle.
Visuals
Show zone tint (default true): Background shade in premium or discount region.
Show shift markers (default true): Display first-shift markers.
Execution and Risk
Risk per trade percent (default 1.0): Determines position size as account percentage.
Use band for size (default false): Scales size relative to band width behavior.
Flat on opposite shift (default true): Forces reversal behavior.
Use stop at band (default false): Stop anchored to band edges.
Stop band side: Chooses which band edge is used for stop generation.
Reading & Interpretation
A green background indicates discount conditions within the structural band; red indicates premium conditions. A green triangle below price marks the first bullish structural shift after a bearish regime. A red triangle above price marks the first bearish structural shift after a bullish regime.
When stops are active, the opposite band edge typically defines the protective level. Band width relative to ATR indicates how significant a structural change is: wider bands imply stronger volatility structure, while narrow bands may be suppressed by the minimum-size filter.
Practical Workflows & Combinations
Trend following: Use first-shift entries as initial regime confirmation. Add higher-timeframe trend filters for additional context.
Swing trading: Combine with simple liquidity or fair-value-gap concepts to refine entries.
Bias mapping: Use higher timeframes for structural regime and lower timeframes for execution within the premium/discount context.
Exit management: When using stops, consider ATR-scaling or multi-stage profit targets. When not using stops, reversals become the primary exit.
Behavior, Constraints & Performance
The strategy uses only confirmed swings and closed-bar logic, avoiding intrabar repaint. Pivot-based swings inherently appear after the pivot window completes, which is standard behavior. No higher-timeframe calls are used, preventing HTF-related repaint issues.
Persistent variables track regime and structural levels, minimizing recomputation. The maximum bars back setting is five-thousand. The design avoids loops and arrays, keeping performance stable.
Known limitations include limited signal density during consolidations, delayed swing confirmation, and sensitivity to extreme gaps that stretch band logic. ATR filtering mitigates some of these effects but does not eliminate them entirely.
Sensible Defaults & Quick Tuning
Fewer but stronger entries: Increase swing length or ATR breakout multiplier.
More responsive entries: Reduce swing length to capture earlier shifts.
More active band behavior: Lower the minimum band ATR threshold.
Stricter stop logic: Use the opposite band edge for stop placement.
Volatile markets: Increase ATR length slightly to stabilize behavior.
What this indicator is—and isn’t
Trendshift Strategy is a structural-regime trading engine that evaluates major directional shifts. It is not a complete trading system and does not include take-profit logic or prediction features. It does not attempt to forecast future price movement and should be used alongside broader market structure, volatility context, and disciplined risk management.
Disclaimer
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
Best regards and happy trading
Chervolino
Trendshift [CHE]Trendshift — First-Shift Regime Turns with Premium/Discount Context
Summary
Trendshift highlights the first confirmed directional structure shift in price and overlays a premium or discount context based on the most recent structural range. It identifies the major swing levels, detects a regime transition when price closes beyond these levels with optional ATR-based conviction, and marks only the first shift per direction to reduce repetition and noise. The indicator then establishes a premium or discount band around the break and tints the background when price operates in either region. This produces a clean regime-aware view that emphasizes only the earliest actionable turn while maintaining contextual bias information.
Motivation: Why this design?
Conventional swing-based structure tools often fire repeated signals after each minor break, especially in volatile environments. This leads to cluttered charts and little informational value. Trendshift focuses on the core trading need: isolating the first confirmed change in directional structure and providing a premium or discount context after the break. By limiting signals to the initial flip and suppressing further markers until direction reverses again, the script reduces noise and highlights only the structural event that materially matters. The band logic further addresses the challenge of distinguishing contextual extremes and avoiding trades taken too late after a shift.
What’s different vs. standard approaches?
Baseline reference: Most structure indicators repeatedly plot every new break of a swing high or swing low.
Differences:
Only the first confirmed bullish or bearish shift is plotted until the opposite direction occurs.
ATR-filtered breakout validation to reduce false breaks during volatility spikes.
A reduced premium and discount band derived from the breakout candle and prior swing structure.
Tinted background for contextual positioning rather than explicit entry signals.
Practical effect:
Fewer but more meaningful shift markers.
Clear visual context of where price operates relative to the structural band.
Cleaner regime transitions and less chart clutter.
How it works (technical)
The indicator continuously evaluates major swing highs and lows using a symmetric window length. When a swing is confirmed, the script stores its price and bar index. A structure shift occurs when price closes beyond the most recent major swing in the opposite direction. Optional ATR filtering requires the breakout distance to exceed an ATR-scaled threshold.
Upon a confirmed shift, the script sets a regime state that remains active until a new shift or an optional timeout. It also establishes a structural band anchored between the breakout candle extremum and the prior opposite swing. The band informs the premium and discount boundaries, each representing a quarter subdivision.
Only the first shift event per direction generates a visual triangle marker. The band is validated by comparing its height to ATR to avoid extremely narrow structures. Background tinting activates whenever price resides within the premium or discount zones. Persistent variables maintain previous structural states and prevent re-triggering until direction reverses.
Parameter Guide
Swing length (default 5): Controls the number of bars used on each side of a swing. Smaller values are more reactive; larger values reduce noise.
Use ATR filter (default true): Requires breakout strength beyond the swing to exceed an ATR-scaled threshold. Disabling increases signal frequency.
ATR length (default 14): Controls volatility estimation for breakout filtering and band validation.
Break ATR multiplier (default 1.0): Higher values require stronger breakouts, reducing false shifts.
Enable framework (default true): Activates the premium and discount context logic.
Persist band on timeout (default true): Retains the current band after a regime timeout.
Min band size ATR mult (default 0.5): Rejects extremely small bands and prevents unrealistic tinting.
Regime timeout bars (default 500): Resets the regime after extended inactivity.
Invert colors (default false): Swaps premium and discount tint color assignments.
Show zone tint (default true): Toggles background shading.
Show shift markers (default true): Enables or disables the first-shift triangles.
Reading & Interpretation
A green or red tint signals that price is operating in the discount or premium region of the most recent structural band. These regions are derived from the breakout event and the prior swing. A green triangle below a bar indicates the first bullish structure shift after a bearish regime. A red triangle above a bar indicates the first bearish shift after a bullish regime. No further markers appear until direction reverses. When tint is active, price location within the band offers simple contextual bias without providing explicit entries.
Practical Workflows & Combinations
Trend following: Treat the first bullish marker as the earliest confirmation of a potential up-regime and the first bearish marker for a potential down-regime. Use price location relative to the premium and discount zones as context for continuation or mean-reversion setups.
Structure-based execution: Combine with simple swing highs and lows to refine entry points within discount after a bullish shift or within premium after a bearish shift.
Higher-timeframe overlays: Apply the indicator on higher timeframes to define macro structure, then trade on lower timeframes using the band as a contextual anchor.
Risk management: When price stays in premium during a bearish regime or in discount during a bullish regime, consider protective actions or position management adjustments.
Behavior, Constraints & Performance
The script uses only confirmed swing points and closed-bar conditions, so repainting from future bars does not occur except the inherent delay of pivot confirmation. No higher-timeframe security calls are used, avoiding HTF repaint paths.
Performance impact is minimal because the script uses no loops or arrays and relies on persistent variables. The maximum bars back setting is five-thousand, required for swing lookback. Known limitations include quiet behavior during long consolidations, occasional delayed recognition of shifts due to swing confirmation, and limited effectiveness during large market gaps where extremum logic may be distorted.
Sensible Defaults & Quick Tunin g
Increase the swing length for smoother trend shifts and fewer signals.
Decrease the swing length for more sensitivity.
Raise the ATR breakout multiplier to reduce noise in volatile markets.
Lower the band size requirement to make premium and discount zones more active on slower markets.
Extend the regime timeout for slow-moving assets.
What this indicator is—and isn’t
This tool is a structural regime-shift detector with contextual premium and discount shading. It is not a complete trading system and does not include entries, exits, or risk models. It does not predict future price movement. It should be combined with broader structure analysis, liquidity considerations, and risk management practices.
Disclaimer
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
Best regards and happy trading
Chervolino
Regime MapRegime Map — Volatility State Detector
This indicator is a PineScript friendly approximation of a more advanced Python regime-analysis engine.
The original backed identifies market regimes using structural break detection, Hidden-Markov Models, wavelet decomposition, and long-horizon volatility clustering. Since Pine Script cannot execute these statistical models directly, this version implements a lightweight, real-time proxy using realised volatility and statistical thresholds.
The purpose is to provide a clear visual map of evolving volatility conditions without requiring any heavy offline computation.
________________________________________
Mathematical Basis: Python vs Pine
1. Volatility Estimation
Python (Realised Volatility):
RVₜ = √N × stdev( log(Pₜ) − log(Pₜ₋₁) )
Pine Approximation:
RVₜ = stdev( log(Pₜ) − log(Pₜ₋₁), lookback )
Rationale:
Realised volatility captures volatility clustering — a key characteristic of regime transitions.
________________________________________
2. Regime Classification
Python (HMM Volatility States):
Volatility is modelled as belonging to hidden states with different means and variances:
State μ₁, σ₁
State μ₂, σ₂
State μ₃, σ₃
with state transitions determined by a probability matrix.
Pine Approximation (Z-Score Regimes):
Zₜ = ( RVₜ − mean(RV) ) / stdev(RV)
Regime assignment:
• Regime 0 (Low Vol): Zₜ < Zₗₒw
• Regime 1 (Normal): Zₗₒw ≤ Zₜ ≤ Zₕᵢgh
• Regime 2 (High Vol): Zₜ > Zₕᵢgh
Rationale:
Z-scores provide clean statistical boundaries that behave similarly to HMM state separation but are computable in real time.
________________________________________
3. Structural Break Detection vs Rolling Windows
Python (Bai–Perron Structural Breaks):
Segments the volatility series into periods with distinct statistical properties by minimising squared error over multiple regimes.
Pine Approximation:
Rolling mean and rolling standard deviation of volatility over a long window.
Rationale:
When structural breaks are not available, long-window smoothing approximates slow regime changes effectively.
________________________________________
4. Multi-Scale Cycles
Python (Wavelet Decomposition):
Volatility decomposed into long-cycle (A₄) and short-cycle components (D bands).
Pine Approximation:
Single-scale smoothing using long-horizon averages of RV.
Rationale:
Wavelets reveal multi-frequency behaviour; Pine captures the dominant low-frequency component.
________________________________________
Indicator Output
The background colour reflects the active volatility regime:
• Low Volatility (Green): trending behaviour, cleaner directional movement
• Normal Volatility (Yellow): balanced environment
• High Volatility (Red): sharp swings, traps, mean-reversion phases
Regime labels appear on the chart, with a status panel displaying the current regime.
________________________________________
Operational Logic
1. Compute log returns
2. Calculate short-horizon realised volatility
3. Compute long-horizon mean and standard deviation
4. Derive volatility Z-score
5. Assign regime classification
6. Update background colour and labels
This provides a stable, real-time map of market state transitions.
________________________________________
Practical Applications
Intraday Trading
• Low-volatility regimes favour trend and breakout continuation
• High-volatility regimes favour mean reversion and wide stop placement
Swing Trading
• Compression phases often precede multi-day trending moves
• Volatility expansions accompany distribution or panic events
Risk Management
• Enables volatility-adjusted position sizing
• Helps avoid leverage during expansion regimes
________________________________________
Notes
• Does not repaint
• Fully configurable thresholds and lookbacks
• Works across indices, stocks, FX, crypto
• Designed for real-time volatility regime identification
________________________________________
Disclaimer
This script is intended solely for educational and research purposes.
It does not constitute financial advice or a recommendation to buy or sell any instrument.
Trading involves risk, and past volatility patterns do not guarantee future outcomes.
Users are responsible for their own trading decisions, and the author assumes no liability for financial loss.
MA200 Deviation Percentile200-Day MA Deviation with Dynamic Thresholds
OVERVIEW
This indicator measures price deviation from the 200-day moving average as a percentage, with dynamically calculated overbought/oversold thresholds based on historical percentiles.
Best suited for broad market indices (SPY, QQQ, IWM, etc.) where the 200-day MA serves as a reliable long-term trend indicator. Individual stocks may exhibit more erratic behavior around this level.
CALCULATION
Deviation (%) = (Close - 200MA) / 200MA x 100
Dynamic thresholds are derived from actual historical distribution rather than assuming normal distribution:
- Overbought threshold = 97.5th percentile of historical deviations
- Oversold threshold = 2.5th percentile of historical deviations
SETTINGS
MA Length (default: 200)
Moving average period.
Lookback Period (default: 1260)
Historical window for threshold calculation. 1260 bars approximates 5 years of daily data.
Threshold Percentile (default: 5%)
Two-tailed threshold. 5% places overbought/oversold boundaries at the 97.5th and 2.5th percentiles respectively.
INTERPRETATION
Deviation Value
- Positive: Price trading above 200MA
- Negative: Price trading below 200MA
- Magnitude indicates extent of deviation
Percentile Ranking (0-100%)
- Shows where current deviation ranks historically
- Above 90%: Historically elevated
- Below 10%: Historically depressed
Dynamic Threshold Lines
- Red line: Upper boundary based on historical distribution
- Green line: Lower boundary based on historical distribution
- These adapt automatically to each asset's volatility characteristics
APPLICATION
Mean Reversion
Extreme deviations tend to normalize over time. When deviation exceeds dynamic thresholds, probability of mean reversion increases.
Trend Assessment
Sustained positive/negative deviation confirms trend direction. Zero-line crossovers may signal trend changes.
NOTES
- Optimized for daily timeframe on market indices
- Requires sufficient historical data (minimum equal to lookback period)
- Extreme readings do not guarantee immediate reversals
- Use in conjunction with other analysis methods
Mean-Reversion with CooldownThis strategy requires no indicators or fundamental analysis. It is designed for longer-term positions and works especially well on unleveraged instruments with strong long-term upward trends, such as precious metals. Feel free to experiment with different timeframes — I’ve found that 1-hour charts work particularly well for cryptocurrencies.
The idea is to filter out ongoing bear phases as effectively as possible and capitalize on long-term bull runs.
The script implements an idea that came to me in a state of complete sleep deprivation: open a random long position with a fixed take-profit (TP) and a tight stop-loss (SL).
If the TP is hit — great, we simply try again.
If the SL is triggered — too bad, we pause for a while and then try again.
## Cooldown (Waiting) Mechanism
The waiting mechanism is simple: the more consecutive SL hits we get, the longer we wait before opening the next trade. The waiting time is measured in closed candles, and thus depends on the timeframe you are using.
## Two cooldown calculation modes are currently supported:
### 1. FIBONACCI
The cooldown follows the Fibonacci sequence, based on the number of consecutive losses:
1st loss → wait 1 bar
2nd loss → wait 1 bar
3rd loss → wait 2 or 3 bars (depending on definition)
4th loss → wait 3 or 5 bars
etc.
### 2. POWER OF TWO
The cooldown increases exponentially:
1st loss → wait 2 bars
2nd loss → wait 4 bars
3rd loss → wait 8 bars
4th loss → wait 16 bars
and so on, using the formula 2ⁿ.
## Configurable Parameters
### Cooldown Pause Calculation
The settings allow you to define the SL and TP as percentages of the position value.
The "Cooldown Pause Calculation" option determines how the next cooldown duration is computed after a losing trade.
The system keeps track of how many consecutive losses have occurred since the last profitable trade. That counter is then used to compute how many bars we must wait before opening the next position.
### Maximum Cooldown
The "Max Cooldown Candles" setting defines the maximum number of bars we are allowed to wait before placing a new trade. This prevents the strategy from “locking itself out” for too long and mitigates the fear of missing out (FOMO).
Once the cooldown duration reaches this maximum, the system essentially wraps around and starts the progression again. In the script, this is handled using a simple modulo operation based on the chosen maximum.
Trend Breakout & Ratchet Stop System [Market Filter]Description:
This strategy implements a robust trend-following system designed to capture momentum moves while strictly managing downside risk through a multi-stage "Ratchet" exit mechanism and broad market filters.
It is designed for swing traders who want to align individual stock entries with the overall market direction.
How it works:
1. Market Regime Filters (The "Safety Check") Before taking any position, the strategy checks the health of the broader market to avoid "catching falling knives."
Broad Market Filter: By default, it checks NASDAQ:QQQ (adjustable). If the benchmark is trading below its SMA 200, the strategy assumes a Bear Market and suppresses all new long entries.
Volatility Filter (VIX): Uses CBOE:VIX to gauge fear. If the VIX is above a specific threshold (Default: 32), entries are paused, and existing positions can optionally be closed to preserve capital.
2. Entry Logic Entries are based on Momentum and Trend confirmation. A position is opened if filters are clear AND one of the following occurs:
Golden Cross: SMA 25 crosses over SMA 50.
SMA Breakouts: A "Three-Bar-Break" logic confirms a breakout above the SMA 50, 100, or 200 (price must establish itself above the moving average).
3. The "Ratchet" Exit System The exit logic evolves as the trade progresses, tightening risk like a ratchet:
Stage 0 (Initial Risk): Starts with a standard percentage Stop Loss from the entry price.
Stage 1 (Breakeven/Lock): Once the price rises by Profit Step 1 (e.g., +10%), the Stop Loss jumps to a tighter level and locks there. This secures the initial move.
Stage 2 (Trailing Mode): If the price continues to rise to Profit Step 2 (e.g., +15%), the Stop Loss converts into a dynamic Trailing Stop relative to the Highest High. This allows the trade to run as long as the trend persists.
Additional Exits:
Dead Cross: Closes position if SMA 25 crosses under SMA 50.
VIX Panic: Emergency exit if volatility spikes above the threshold.
Settings & Customization:
SMAs: Adjustable lengths for all Moving Averages.
Filters: Toggle Market/VIX filters on/off and choose your benchmark ticker (e.g., SPY or QQQ).
Risk Management: Fully customizable percentages for the Ratchet steps (Initial SL, Stage 1 Trigger, Trailing distance).
Dynamic Ratchet Trend Strategy [VIX Filter]Overview This strategy is a long-only trend-following system designed to capture major market moves while strictly managing downside risk through a state-machine based "Ratchet" exit logic. It incorporates a volatility filter using the CBOE VIX index to stay out of (or exit) the market during high-stress environments.
Key Features
1. Multi-Condition Entries The strategy looks for momentum shifts and trend breakouts using four Simple Moving Averages (25, 50, 100, 200).
Momentum Cross: SMA 25 crossover above SMA 50.
Trend Breakouts: A specific "3-Bar Breakout" logic above the SMA 50, 100, or 200. This requires the price to hold above the SMA for 3 consecutive bars after being below it, reducing false signals compared to simple closes.
2. VIX Volatility Filter Before entering any trade, the script checks the CBOE:VIX.
Filter: If VIX is above the threshold (default 32), new entries are blocked.
Panic Exit: If you are in a position and the VIX spikes above the threshold, the strategy executes an immediate "Panic Exit" to preserve capital during market crashes.
3. The "Ratchet" Exit System (3 Stages) Unlike a standard trailing stop, this strategy uses a 3-stage dynamic exit mechanism that tightens as profits grow:
Stage 0 (Initial Risk): Standard percentage-based Stop Loss from the entry price.
Stage 1 (The Lock-In): Triggered when profit hits 10% (configurable).
Unique Logic: Instead of trailing from the highest high, the stop is calculated based on the price at the exact moment this stage was triggered. It "steps up" once and holds, securing the initial move without being prematurely stopped out by normal volatility.
Stage 2 (Trailing Mode): Triggered when profit hits 15% (configurable).
The strategy switches to a classic Trailing Stop, following the percentage distance from the Highest High.
4. Emergency Backup A "Dead Cross" (SMA 25 crossing under SMA 50) acts as a final fail-safe to close positions if the trend reverses completely before hitting a stop.
Settings & Inputs
SMAs: Customize the lengths for all four moving averages.
VIX Filter: Toggle the filter on/off and set the panic threshold.
Exit Logic: Fully customizable percentages for Initial SL, Stage 1 Trigger/Distance, and Stage 2 Trigger/Trailing Distance.
Disclaimer This script is for educational purposes only. Past performance is not indicative of future results. Always manage your risk appropriately.
Ratchet Exit Trend Strategy with VIX FilterThis strategy is a trend-following system designed specifically for volatile markets. Instead of focusing solely on the "perfect entry," this script emphasizes intelligent trade management using a custom **"Ratchet Exit System."**
Additionally, it integrates a volatility filter based on the CBOE Volatility Index (VIX) to minimize risk during extreme market phases.
### 🎯 The Concept: Ratchet Exit
The "Ratchet" system operates like a mechanical ratchet tool: the Stop Loss can only move in one direction (up, for long trades) and "locks" into specific stages. The goal is to give the trade "room to breathe" initially to avoid being stopped out by noise, then aggressively reduce risk as the trade moves into profit.
The exit logic moves through 3 distinct phases:
1. **Phase 0 (Initial Risk):** At the start of the trade, a wide Stop Loss is set (Default: 10%) to tolerate normal market volatility.
2. **Phase 1 (Risk Reduction):** Once the trade reaches a specific floating profit (Default: +10%), the Stop Loss is raised and "pinned" to a fixed value (Default: -8% from entry). This drastically reduces risk while keeping the trade alive.
3. **Phase 2 (Trailing Mode):** If the trend extends to a higher profit zone (Default: +15%), the Stop switches to a dynamic Trailing Mode. It follows the **Highest High** at a fixed percentage distance (Default: 8%).
### 🛡️ VIX Filter & Panic Exit
High volatility is often the enemy of trend-following strategies.
* **Entry Filter:** The system will not enter new positions if the VIX is above a user-defined threshold (Default: 32). This helps avoid entering "falling knife" markets.
* **Panic Exit:** If the VIX spikes above the threshold (32) while a trade is open, the position is closed immediately to protect capital (Emergency Exit).
### 📈 Entry Signals
The strategy trades **LONG only** and uses Simple Moving Averages (SMAs) to identify trends:
* **Golden Cross:** SMA 25 crosses over SMA 50.
* **3-Bar Breakouts:** A confirmation logic where the price must close above the SMA 50, 100, or 200 for 3 consecutive bars.
### ⚙️ Settings (Inputs)
All parameters are fully customizable via the settings menu:
* **SMAs:** Lengths for the trend indicators (Default: 25, 50, 100, 200).
* **VIX Filter:** Toggle the filter on/off and adjust the panic threshold.
* **Ratchet Settings:** Percentages for Initial Stop, Trigger Levels for Stages 1 & 2, and the Trailing Distance.
### ⚠️ Technical Note & Risk Warning
This script uses `request.security` to fetch VIX data. Please ensure you understand the risks associated with trading leveraged or volatile assets. Past performance is not indicative of future results.
Kaufman Adaptive Moving Average + ART**Kaufman Adaptive Moving Average (fixed TF) + ATR Volatility Bands**
This script is a Pine Script v5 extension of the original *Kaufman Adaptive Moving Average* by Alex Orekhov (everget).
It adds:
* a **fixed timeframe option** for KAMA
* a separate **ATR panel under the chart**
* **configurable ATR volatility levels** with dynamic coloring.
KAMA adapts its smoothing to market conditions: it speeds up in strong trends and slows down in choppy phases. Here, KAMA can be calculated on any timeframe (e.g. 1D) and overlaid on a lower-timeframe chart (e.g. 1H), so you can track higher-TF trend structure while trading intraday.
The ATR panel visualizes volatility in the same or a separate timeframe and highlights phases of high/low volatility based on user-defined thresholds.
---
### Features
**KAMA (on chart)**
* Standard KAMA parameters: `Length`, `Fast EMA Length`, `Slow EMA Length`, `Source`
* Input: **KAMA Timeframe**
* empty → uses chart timeframe
* any value (e.g. `60`, `240`, `D`, `W`) → calculates KAMA on that fixed TF and maps it to the chart
* Color-changing KAMA line:
* **green** when the selected-TF KAMA is rising
* **red** when it is falling
* Optional *Await Bar Confirmation* to avoid reacting to still-forming bars
* Built-in alert when the KAMA color changes (potential trend shift).
**ATR panel (separate window under the chart)**
* Own inputs: `Show ATR`, `ATR Length`
* **ATR Timeframe** input:
* empty → ATR uses the same TF as KAMA
* custom value → fully independent ATR timeframe
* Two user-defined volatility levels:
* `ATR High Vol Level` – threshold for **high volatility**
* `ATR Low Vol Level` – threshold for **low volatility**
* ATR line coloring:
* **red** when ATR > High Vol Level (high volatility regime)
* **green** when ATR < Low Vol Level (quiet market)
* **blue** in the normal range between the two levels.
---
### How to use
1. Add the script to your chart.
2. Choose a **KAMA Timeframe** (leave empty for chart TF, or set to a higher TF for multi-timeframe trend following).
3. Optionally set a different **ATR Timeframe** to monitor volatility on yet another TF.
4. Adjust `ATR High Vol Level` and `ATR Low Vol Level` to match the instrument and timeframe you trade.
5. Use:
* the **KAMA color changes** as trend / regime signals, and
* the **ATR colors & levels** to quickly see whether you’re trading in a low-, normal- or high-volatility environment.
This combination is designed to keep the chart itself clean (only KAMA on price) while giving you a dedicated volatility dashboard directly underneath.
Stock whisperer vol 2Below is your updated, copy-paste ready Pine v5 script with 5 bullish targets and 5 bearish targets.
No broken line wraps. No reserved words. No Pine meltdowns.
Dynamic Support and Resistance with Trend LinesMain Purpose
The indicator identifies and visualizes dynamic support and resistance levels using multiple strategies, plus it includes trend analysis and trading signals.
Key Components:
1. Two Support/Resistance Strategies:
Strategy A: Matrix Climax
Identifies the top 10 (configurable) most significant support and resistance levels
Uses a "matrix" calculation method to find price levels where the market has historically reacted
Shows these as horizontal lines or zones on the chart
Strategy B: Volume Extremes
Finds support/resistance levels based on volume analysis
Looks for areas where extreme volume occurred, which often become key price levels
2. Two Trend Line Systems:
Trend Line 1: Pivot Span
Draws trend lines connecting pivot high and pivot low points
Uses configurable pivot parameters (left: 5, right: 5 bars)
Creates a channel showing the trend direction
Styled in pink/purple with dashed lines
Trend Line 2: 5-Point Channel
Creates a channel based on 5 pivot points
Provides another perspective on trend direction
Solid lines in pink/purple
3. Trading Signals:
Buy Signal: Triggers when Fast EMA (9-period) crosses above Slow EMA (21-period)
Sell Signal: Triggers when Fast EMA crosses below Slow EMA
Displays visual shapes (labels) on the chart
Includes alert conditions you can set up in TradingView
4. Visual Features:
Dashboard: Shows key information in a table (top-right by default)
Visual Matrix Map: Displays a heat map of support/resistance zones
Color themes: Dark Mode or Light Mode
Timezone adjustment: For accurate time display
5. Customization Options:
Universal lookback length (100 bars default)
Projection bars (26 bars forward)
Adjustable transparency for different elements
Multiple calculation methods available
Fully customizable colors and line styles
What Traders Use This For:
Entry/Exit Points: The EMA crossovers provide clear buy/sell signals
Risk Management: Support/resistance levels help set stop-losses and take-profit targets
Trend Confirmation: Multiple trend lines confirm trend direction
Key Price Levels: Identifies where price is likely to react (bounce or break through)
The indicator is quite feature-rich and combines technical analysis elements (pivots, EMAs, volume, support/resistance) into one comprehensive tool for trading decisions.






















