Unreached Highs/Lows Oscillator [LuxAlgo]The Unreached Highs/Lows Oscillator highlights the amount of unreached high/low prices as a percentage over time, helping visualize trend strength and momentum from bullish and bearish market participants.
🔶 USAGE
This indicator measures the strength of directional price movements, helping traders visualize the strength of both the bullish and bearish market participants.
When prices are moving up with strength, the price structure will not come back to retest previous lows. Therefore, unreached lows keep adding up.
When prices are moving down with strength, they will not retest previous highs; therefore, unreached highs keep adding up.
As we can see on the chart, high readings of unreached highs (red) and low readings of unreached lows (green) are considered bearish, and a downtrend in price confirms this bias. Conversely, high readings of unreached lows and low readings of unreached highs are considered bullish. On the chart, this is reflected as an uptrend.
Additionally, the oscillator can reveal significant breakouts on the chart, with unreached highs or lows decreasing rapidly indicating that a large number of highs/lows have been reached.
Due to the oscillator being normalized, overbought and oversold levels are included.
In this gold chart, we have different examples of how to use the tool in conjunction with price behavior to understand the market. Let's dissect it step by step:
1. Uptrend: Bullish readings are above 80, and bearish readings are below 20. The market is trending up.
2. Range: Mixed readings around 50 for both bullish and bearish; the market is ranging.
3. Uptrend: The same as before. Bullish above 80 and bearish below 20.
4. Pullback: A bullish dip below 80 to 50 and a bearish reading below 20 indicates a pullback.
5. Range: Mixed readings. In this case, it is bullish above and below 80 and bearish above and below 20. The market is ranging.
6. Uptrend: Bullish above 80 and bearish below 20; the market keeps moving up.
7. Pullback: Bullish dips below 80 and bearish rises to 50 indicate a pullback.
8. Uptrend: As before, bullish is above 80 and bearish is below 20; the market is trending up.
This Bitcoin chart shows how to use extreme readings of 0 and 100 to detect potential reversals. When both readings are at extreme opposites, we set the threshold level at 100 and 0 instead of the default levels of 80 and 20 to better identify these areas.
As we can see, extreme readings at points 1 and 5 identify major reversals that lead to a change in trend. Extreme readings at points 2, 3, 4, and 6 identify minor reversals that do not lead to a change in trend.
From the settings panel, traders can adjust the length parameter. A smaller value measures smaller price movements, while a larger value measures larger price movements. A length value of 20 is used by default.
The chart shows how different values affect bullish and bearish measures.
🔶 SETTINGS
Length: Select the maximum number of highs and lows to be used.
🔹 Style
Bullish: Select a color for unreached lows.
Bearish: Select a color for unreached highs.
Top Threshold: Select the top threshold level and color. Enable the Auto feature to choose the default color.
Bottom Threshold: Select the bottom threshold level and color. Enable the Auto feature to choose the default color.
Indikator dan strategi
Swing Structure Bands [ChartPrime]⯁ OVERVIEW
Swing Structure Bands is a structure-based trend and reaction indicator that builds adaptive price bands directly from swing highs and swing lows.
Instead of using fixed-length moving averages, the bands dynamically adjust their length based on how long price has been forming higher highs or lower lows, allowing the indicator to naturally align with real market structure.
This makes the tool especially effective for identifying swing-based support and resistance, trend continuation zones, and exhaustion reactions.
⯁ CORE CONCEPT
The indicator continuously tracks:
The most recent swing high and swing low over a configurable swing window.
How long price has been developing since each swing point.
Dynamic moving averages whose length grows with the swing itself.
As long as price respects the current swing direction, the bands extend and adapt.
When structure breaks, the system resets and starts forming new swing-based bands.
⯁ SWING DETECTION LOGIC
A Swing High is detected when price forms a local maximum relative to the swing lookback.
A Swing Low is detected when price forms a local minimum relative to the swing lookback.
Direction flips when price transitions from forming highs to forming lows, or vice versa.
Each confirmed swing is marked on the chart, giving clear structural context.
⯁ ADAPTIVE BAND CONSTRUCTION
Upper bands are derived from swing highs.
Lower bands are derived from swing lows.
Band length dynamically increases as the swing develops.
Multiple MA types can be used (SMA, EMA, SMMA/RMA, WMA, VWMA).
ATR is applied as an offset to create upper and lower envelopes around each band, forming a volatility-aware structure channel.
⯁ VOLATILITY FILTERING
If the band moves too aggressively relative to ATR, it is temporarily disabled.
This prevents unstable or noisy bands during sudden expansions.
Bands only remain active when price structure is stable.
This logic keeps the indicator focused on meaningful swings rather than short-term spikes.
⯁ REACTION & SIGNAL LOGIC
Sell signals appear when price crosses down from the upper swing band after sufficient stabilization.
Buy signals appear when price crosses up from the lower swing band after sufficient stabilization.
Cooldown logic prevents signal clustering.
Signals are designed as structure reactions , not momentum breakouts.
⯁ VISUAL STRUCTURE CLARITY
Separate bullish and bearish bands with customizable colors.
Optional band envelopes for visual depth.
Clear swing labels marking structural turning points.
Diamond markers highlight reaction zones.
The visualization emphasizes where price reacts to structure rather than where it accelerates.
⯁ HOW TO USE
Use upper bands as dynamic resistance during bearish or corrective phases.
Use lower bands as dynamic support during bullish phases.
Combine band reactions with higher-timeframe trend direction.
Look for confirmations near bands rather than mid-range entries.
The indicator works best as a structure framework rather than a standalone signal generator.
⯁ IDEAL MARKET CONDITIONS
Trending markets with clear swing development.
Markets transitioning from impulse to correction.
Crypto, forex, indices, and liquid stocks.
⯁ CONCLUSION
Swing Structure Bands offers a structurally grounded alternative to traditional moving average channels.
By anchoring bands to real swing behavior and adapting dynamically over time, it provides traders with a clearer view of where price is reacting, pausing, or potentially reversing within the broader market structure.
Theme TrackerTheme Tracker is a clean, at-a-glance theme rotation dashboard built to help you quickly identify where money is flowing—and where it’s leaving—across the market’s most important macro, sector, and industry themes.
Instead of bouncing between dozens of charts, Theme Tracker tracks a curated basket of 40 major theme ETFs and displays their relative performance across multiple timeframes, so you can instantly spot leadership, momentum shifts, and early rotation.
What it shows
For each theme ETF, the table displays performance over:
1 Day
1 Week
1 Month
3 Months
Year to Date (YTD)
Themes are ranked automatically by the timeframe you choose, allowing you to focus on what matters most in the current market regime—short-term momentum, intermediate rotation, or longer-term trend leadership.
Why it’s useful
Market leaders change. Rotation happens quietly at first, then suddenly.
Theme Tracker helps you:
Find the strongest themes fast (the “winners” attracting capital)
Spot weakening themes early (distribution and risk-off rotation)
Confirm market tone by comparing offensive vs defensive leadership
Generate trade ideas by focusing on the themes that are already being bid up
Avoid laggards by seeing what’s consistently underperforming across timeframes
When a theme is strong across multiple timeframes, that’s often where momentum traders and institutions are concentrating exposure. When it’s weak across timeframes, that’s often where capital is exiting.
How to use it
1) Choose your sort timeframe
Use the Sort setting (1D / 1W / 1M / 3M / YTD) to rank themes based on your trading horizon.
2) Look for alignment
Strong across all columns = sustained leadership
Strong short-term, weak long-term = potential bounce / rotation attempt
Weak short-term, strong long-term = possible pullback in a leader
Weak across the board = consistent capital outflow
3) Pair with your chartwork
Use the strongest themes as a shortlist for deeper chart analysis, setups, and relative strength confirmation.
Visual design
The table uses clear formatting and heat-style shading to make it easy to read quickly. Green tones highlight strength; red tones highlight weakness—so you can interpret rotation in seconds without overthinking.
If you trade momentum, relative strength, or market structure, Theme Tracker gives you one of the simplest edges available: knowing what’s leading right now. Track the best-performing themes, identify emerging rotation, and stay aligned with the areas of the market where capital is actually moving.
BuyLow SellHigh Bands | ProjectSyndicate________________________________________
📊 BuyLow SellHigh (BLSH) Bands
Comprehensive Trading Guide – by ProjectSyndicate
________________________________________
🔰 1. Introduction
The BuyLow SellHigh (BLSH) Bands indicator is a powerful technical analysis tool designed for the TradingView platform. Works with any symbol. Gold/FX/indices/oil/crypto/stocks.
It provides traders with a clear, visual representation of:
• 📈 Overbought conditions
• 📉 Oversold conditions
This makes it easier to identify high-probability entry and exit points.
The indicator is built on:
• Dynamic price channels
• Fibonacci-based zones
• Color-coded market structure
💡 While the BLSH Bands can be used on Forex, Crypto, and Futures, this guide focuses on Gold (XAUUSD) using:
• M5
• M15
• M30 timeframes
________________________________________
🧠 2. Core Concepts
The BLSH Bands structure is created using two key components:
________________________________________
📐 Dynamic Price Bands
• Upper and lower bands are calculated using the highest high and lowest low
• Based on a user-defined lookback period (fiboPeriod)
• Reflects recent volatility and price range
This creates a self-adjusting channel that adapts to market conditions.
________________________________________
🧮 Fibonacci Zones
The space between the bands is divided into six Fibonacci-based zones:
• 0.786
• 0.618
• 0.500
• 0.382
• 0.214
⚠️ These are not traditional retracements — they are used to grade price extremity within the channel.
________________________________________
🎨 Color-Coded Zones Overview
Zone (Fib Level) Color Market Condition Interpretation
1.000 – 0.786 🔴 Red Extreme Overbought High reversal / pullback probability
0.786 – 0.618 🟠 Orange Overbought Selling pressure building
0.618 – 0.500 🟡 Yellow Mildly Overbought Bullish momentum weakening
0.500 – 0.382 🟢 Aqua Mildly Oversold Bearish momentum weakening
0.382 – 0.214 🔵 Deep Sky Blue Oversold Strong buying interest
0.214 – 0.000 🔷 Blue Extreme Oversold High bounce / reversal probability
🖤 Solid black separator lines ensure clean visual separation between zones for precise price location.
________________________________________
🪙 3. Trading Strategies for XAUUSD (Gold)
Gold’s volatility and respect for technical levels make it ideal for BLSH Bands strategies.
________________________________________
⚡ M5 Timeframe – Scalping Strategy
Designed for fast mean-reversion trades from extreme zones.
🟢 BUY Setup
• Price enters Extreme Oversold (Blue) zone
• Bullish confirmation candle appears:
o Hammer
o Bullish engulfing
• Enter BUY
🔴 SELL Setup
• Price enters Extreme Overbought (Red) zone
• Bearish confirmation candle appears:
o Shooting star
o Bearish engulfing
• Enter SELL
🎯 Take Profit:
• Median band (between Yellow & Aqua)
🛑 Stop Loss:
• Just outside the outer band
________________________________________
📆 M15 Timeframe – Day Trading Strategy
Balanced timeframe for higher-probability reversals.
🟢 BUY Setup
• Price enters Oversold (Blue / Deep Sky Blue)
• Strong bullish reversal candle closes back inside bands
• Enter BUY after close
🔴 SELL Setup
• Price enters Overbought (Red / Orange)
• Bearish reversal candle closes back inside bands
• Enter SELL after close
🎯 Take Profit (Multi-Target):
1. Median band
2. Opposite extreme band
🛑 Stop Loss:
• Beyond high/low of confirmation candle
________________________________________
🔄 M30 Timeframe – Swing Trading Strategy
Used for identifying major swing points.
🔍 Trend Filter
• Use 100 or 200 EMA
• Trade only in trend direction
🟢 Uptrend
• Buy pullbacks into Oversold zones
🔴 Downtrend
• Sell rallies into Overbought zones
📉 Confirmation:
• Band rejection
• RSI or MACD divergence
🎯 Take Profit:
• Previous structure levels
• Opposite band extreme
🛑 Stop Loss:
• Below / above recent swing high or low
________________________________________
🚨 4. Alerts System
Alerts are disabled by default to keep charts clean.
✅ How to Enable
• Open indicator settings
• Check “Enable Alerts”
________________________________________
🔔 Available Alerts
🔴 Overbought Alert
• Trigger: Price crosses above 0.786
• Message:
🔴 SELL SIGNAL: Price entered Overbought Zone – Consider selling or taking profits
🟢 Oversold Alert
• Trigger: Price crosses below 0.214
• Message:
🟢 BUY SIGNAL: Price entered Oversold Zone – Consider buying or entering long
________________________________________
⏱ Alert Spacing Logic
• Default: 20/50 bars
• Prevents repeated alerts in choppy markets
• Filters for higher-quality signals
________________________________________
⚙️ 5. Customization Settings
Adjust the indicator in the Settings panel:
🔧 Core Inputs
• fiboPeriod → Band sensitivity
• extremes → Price source (High/Low or Close)
🔔 Alert Controls
• Enable / disable alerts
• Separate control for overbought & oversold
• Alert spacing (bars)
________________________________________
⭐ How You Can Support ProjectSyndicate (3 Steps)
1. ✅ Click “Add to Favorites” to save this script to your TradingView Favorites
2. 🔎 Check out our other scripts to complete your SMC toolkit
3. 👤 Follow ProjectSyndicate for the latest updates, upgrades, and new releases
________________________________________
⚠️ 6. Disclaimer
Trading involves significant risk and may not be suitable for all traders.
This indicator is a decision-support tool, not a standalone trading system.
Always apply:
• Proper risk management
• Additional confirmations
• Sound trading discipline
📉 Past performance does not guarantee future results.
Gamma of Gamma - AnticipationGamma of Gamma — Anticipation Engine
What if you could detect market inflections before they become obvious? Not react to momentum — anticipate the momentum itself.
"Gamma here refers to mathematical acceleration (2nd derivative), NOT options Gamma"
Gamma of Gamma (GoG) operates one abstraction layer above conventional indicators. While RSI tells you what momentum did , GoG tells you what momentum is about to do . This is the difference between chasing price and positioning ahead of it.
Core Innovation: Traditional indicators measure first-order effects (price change) or second-order effects (momentum/acceleration). This system measures the third derivative — the rate of change of acceleration itself. When Gamma-of-Gamma reaches extremes, it signals that pressure dynamics are about to flip — often 2-5 bars before price visibly reacts.
Target Users: Discretionary traders, scalpers, and swing traders who want early positioning signals with statistical rigor. Effective on stocks, crypto, forex, and futures with meaningful volume data.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
WHY THIRD-DERIVATIVE ANALYSIS?
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
The Hierarchy of Market Information
Most traders operate at the wrong level of abstraction:
• Price → What happened (lagging)
• Momentum → How fast it happened (still lagging)
• Gamma (2nd Derivative) → How momentum is changing (coincident)
• Gamma of Gamma (3rd Derivative) → How FAST that change is changing ( leading )
The third derivative captures inflection acceleration — the mathematical signature of regime transition. When GoG reaches extreme values, the market is telegraphing that current pressure dynamics are unsustainable.
Why This Beats RSI
RSI measures momentum magnitude. GoG measures momentum trajectory .
Consider this scenario: RSI reads 70 (overbought). Is the move exhausted or just getting started? RSI cannot tell you. GoG can — because it measures whether buying pressure is accelerating into the high RSI reading (continuation likely) or decelerating despite high RSI (reversal imminent).
RSI answers: "How strong was the move?"
GoG answers: "Is the move strengthening or weakening right now ?"
The first is historical. The second is predictive.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
MATHEMATICAL FOUNDATION
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Layer 1: Cumulative Volume Delta (CVD)
The foundation is order flow approximation:
• Up bar (close > prior close): Volume classified as buying pressure
• Down bar (close < prior close): Volume classified as selling pressure
• CVD = Running sum of signed volume
Interpretation: Rising CVD indicates net aggressive buying. Falling CVD indicates net aggressive selling. CVD divergence from price often precedes reversals.
Layer 2: Gamma (Second Derivative)
Gamma measures acceleration of order flow:
Formula: Gamma = CVD - 2×CVD + CVD
This is the discrete second derivative — the rate of change of the rate of change. When Gamma spikes positive, buying pressure is accelerating . When Gamma spikes negative, selling pressure is accelerating.
Layer 3: Gamma of Gamma (Third Derivative)
GoG measures jerk — the acceleration of acceleration:
Formula: GoG = Gamma - 2×Gamma + Gamma
Critical insight: Extreme GoG readings indicate that current pressure dynamics are reaching an inflection point. The system is "overextended" in its current trajectory and will likely revert or reverse.
Layer 4: Z-Score Normalization
Raw GoG values are normalized against their 50-period distribution:
Formula: GoG_Z = (GoG - Mean_50) / StdDev_50
Benefit: Z-scores are regime-adaptive. A "2.0" reading always means "2 standard deviations from normal" regardless of whether you're trading a penny stock or ES futures. This makes thresholds consistent across instruments and timeframes.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SIGNAL GENERATION LOGIC
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Long Signal (Bullish Anticipation)
Triggers when:
• GoG Z-score < -Threshold (default -2.0)
• Volume > Average Volume × Minimum Multiple (default 1.2×)
Interpretation: Selling pressure acceleration has reached an extreme negative reading. The selling is "exhausting itself" — acceleration is peaking and will soon decelerate. Buyers are likely to step in.
Short Signal (Bearish Anticipation)
Triggers when:
• GoG Z-score > +Threshold (default +2.0)
• Volume > Average Volume × Minimum Multiple (default 1.2×)
Interpretation: Buying pressure acceleration has reached an extreme positive reading. The buying is "exhausting itself" — often occurs at blow-off tops, failed breakouts, or momentum climaxes.
Why Volume Confirmation?
Gamma acceleration in thin liquidity is meaningless noise. The volume filter ensures signals occur only when meaningful participation backs the pressure dynamics. This dramatically reduces false signals during low-activity periods.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CONFIDENCE ENGINE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Not all signals are equal. The Confidence Engine quantifies signal strength:
Confidence Calculation:
Confidence = 50 + ((|Z-Score| - Threshold) / Threshold) × 100
Capped at 100%
Visual Representation:
• Small orb = Low confidence (50-65%)
• Normal orb = Medium confidence (65-80%)
• Large orb = High confidence (80-100%)
Orb transparency also adjusts — high-confidence signals appear brighter and more prominent. This creates intuitive visual hierarchy where stronger signals demand more attention.
Practical Use:
• High confidence (>80%): Consider larger position size, tighter stops
• Medium confidence (50-80%): Standard position size
• Low confidence (<50%): Reduced size or wait for confirmation
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
INTEGRATED BACKTESTER
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Every signal system needs accountability. The onboard backtester provides real-time performance tracking:
Core Metrics:
• Total Trades
• Win Rate
• Profit Factor
• Expectancy (average P&L per trade)
• Net P&L
• Max Drawdown
• Average Win / Average Loss
Methodology:
• Positions held for configurable bar count (default 10 bars)
• Forces objective evaluation independent of discretionary exits
• Updates in real-time as new trades complete
Optimizer Mode:
Enable for parameter tuning research:
• Stability Score (0-100 points): Composite evaluation of parameter robustness
• Trade Density : Signals per 1000 bars — monitors over/under-trading
• Parameter Display : Current settings for documentation
• Robustness Rating : ROBUST / STABLE / FRAGILE / OVERFIT
Stability Scoring Breakdown:
• Win Rate ≥55%: +25 points | ≥50%: +15 points | ≥45%: +5 points
• Expectancy >0.5%: +25 points | >0.1%: +15 points | >0%: +5 points
• Total Trades ≥30: +25 points | ≥20: +15 points | ≥10: +5 points
• Profit Factor ≥1.5: +25 points | ≥1.2: +15 points | ≥1.0: +5 points
Target: 60+ points indicates stable parameters. Below 40 suggests overfitting risk.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CHART EXECUTION SIGNALS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Unique feature: Entry and exit markers display directly on the price chart via force_overlay, even though the indicator runs in a separate pane.
Visual Markers:
• ▲ Green Triangle (below bar): Long entry at exact price level
• ▼ Red Triangle (above bar): Short entry at exact price level
• ✕ Gold X-Cross : Position exit after hold period
Benefit: Immediate visual correlation between GoG signals and price action. Review historical trades without switching between panes.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
DUAL DASHBOARD SYSTEM
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Main Dashboard — Real-Time State
Displays:
• Current GoG regime (EXTREME HIGH / EXTREME LOW / NEUTRAL)
• GoG Z-Score (numerical)
• Raw GoG value
• Gamma value
• CVD (Cumulative Volume Delta)
• Volume status (Active/Low with ratio)
• Signal state (Scanning / Long Signal / Short Signal / In Position)
• Confidence meter with visual bar
• Entry price when in position
Backtest Dashboard — Performance Metrics
Displays all backtester metrics in compact format. Switches to Optimizer view when Optimizer Mode enabled.
Both dashboards feature:
• Configurable position (6 locations including Middle Left/Right)
• Adjustable text size (Tiny/Small/Normal/Large)
• Transparency control for visual integration
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
PARAMETER GUIDE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Calculation Settings
• GoG Extreme Threshold (default 2.0): Z-score level for signal generation. Higher = fewer but stronger signals. Range: 0.5-5.0
• Gamma Smoothing (default 3): SMA period for Gamma. Lower = more responsive, more noise. Higher = smoother, more lag. Range: 1-20
• GoG Smoothing (default 5): SMA period for GoG. Filters micro-spikes while preserving structural inflections. Range: 1-20
• Min Volume Multiple (default 1.2): Volume must exceed this multiple of 20-period average. Ensures signals have participation backing. Range: 0.5-3.0
Backtester Settings
• Backtest Hold Bars (default 10): Forced holding period for backtester evaluation. Adjust based on timeframe and trading style.
• Parameter Optimizer Mode : Enables extended metrics for tuning research.
Tuning by Timeframe
Scalping (1-5 min):
Threshold: 1.5-2.0 | Gamma Smooth: 2-3 | GoG Smooth: 3-4 | Hold: 5-8 bars
Day Trading (15-60 min):
Threshold: 2.0-2.5 | Gamma Smooth: 3-5 | GoG Smooth: 5-7 | Hold: 8-12 bars
Swing Trading (4H-Daily):
Threshold: 2.5-3.0 | Gamma Smooth: 5-7 | GoG Smooth: 7-10 | Hold: 10-15 bars
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
HOW TO USE: PRACTICAL WORKFLOW
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Step 1: Identify Regime
Watch the GoG Z-score line. Most of the time it oscillates within the neutral zone (between thresholds). This is "scanning" mode — no actionable signal.
Step 2: Wait for Extreme
When Z-score crosses threshold AND volume confirms, a signal fires. The orb appears in the indicator pane; the triangle appears on price chart.
Step 3: Assess Confidence
Check orb size and dashboard confidence reading:
• Large bright orb + 80%+ confidence = High conviction setup
• Small faint orb + <60% confidence = Requires additional confirmation
Step 4: Execute with Context
GoG signals anticipate — they don't confirm. Use price structure (support/resistance), higher timeframe trend, or other confirmation before entry.
Step 5: Manage Position
Exit markers show backtester exits. For live trading, consider:
• Time-based exit (signal's hold period)
• Opposite signal exit
• Fixed R:R targets
Step 6: Review Performance
Check Backtest Dashboard regularly. If Win Rate drops below 45% or Expectancy goes negative, reassess parameters or market conditions.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
WHAT THIS INDICATOR IS — AND ISN'T
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
This Indicator IS:
✅ State-transition detector (balance → imbalance)
✅ Early warning system for momentum shifts
✅ Anticipation tool for pre-positioning
✅ Statistical framework with built-in accountability
This Indicator IS NOT:
❌ Mechanical buy/sell system (requires discretion)
❌ Trend-following indicator
❌ Reversal-only indicator
❌ Replacement for risk management
Best Use Cases:
• Detecting early reversals before obvious confirmation
• Anticipating breakouts during volatility compression
• Timing pullback entries in established trends
• Identifying exhaustion at momentum climaxes
Challenging Conditions:
• Extremely low volume environments
• News-driven gaps (no order flow to measure)
• Instruments with unreliable volume data
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ORIGINALITY STATEMENT
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Innovation 1: Third-Derivative Order Flow Analysis
While first and second derivatives are common, applying third-derivative (jerk) analysis to cumulative volume delta is novel. This captures inflection points that lower-order analysis misses entirely.
Innovation 2: Z-Score Adaptive Thresholds
Rather than fixed thresholds that require per-instrument tuning, z-score normalization creates self-adapting signal levels that work consistently across any liquid instrument.
Innovation 3: Confidence-Weighted Visual System
Dynamic orb sizing and transparency based on signal strength provides intuitive visual hierarchy. Stronger signals literally appear larger and brighter.
Innovation 4: Integrated Accountability
Built-in backtester with optimizer mode enables parameter validation directly on chart. No external tools or spreadsheets required.
Innovation 5: Dual-Pane Execution Visualization
Force-overlay chart signals bridge the gap between indicator pane and price action, enabling immediate visual trade review.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
LIMITATIONS & DISCLAIMERS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Technical Limitations
• Volume classification uses bar direction (close vs prior close), not tick-level aggressor data. Precision loss estimated 10-15% vs institutional-grade data.
• CVD approximation assumes volume follows price direction. Works well in trending conditions; less precise in choppy markets.
• Backtester uses fixed hold period, not optimal exit logic. Real performance may vary with proper trade management.
Market Limitations
• Requires meaningful volume data. Avoid instruments with reported volume issues.
• Signals may cluster during high-volatility events. Not every signal should be traded.
• Anticipation signals appear early by design. Patience required — price may continue against signal briefly before reversing.
Risk Disclosure
• Trading involves risk of loss. Past performance does not guarantee future results.
• This indicator provides analysis tools, not financial advice.
• Always use proper position sizing and risk management.
• Backtest results are hypothetical and do not include slippage, commissions, or fees.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
RECOMMENDED SETTINGS BY MARKET
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Crypto (BTC, ETH, SOL)
Threshold: 1.8-2.2 | Gamma: 3 | GoG: 5 | Volume: 1.3x | TF: 15min-4H
Notes: Higher volatility produces more signals. Consider higher threshold to filter.
Forex Majors (EURUSD, GBPUSD)
Threshold: 2.0-2.5 | Gamma: 4 | GoG: 6 | Volume: 1.2x | TF: 5min-1H
Notes: Lower volatility requires patience. Volume proxy via tick volume works adequately.
Stocks (Large Cap)
Threshold: 2.0-2.5 | Gamma: 3-4 | GoG: 5-6 | Volume: 1.2x | TF: 15min-Daily
Notes: Real volume data provides cleanest signals. Watch for opening/closing auction distortions.
Futures (ES, NQ, CL)
Threshold: 2.0-2.3 | Gamma: 3 | GoG: 5 | Volume: 1.2x | TF: 5min-1H
Notes: Excellent volume data. Session boundaries may produce false signals — consider RTH only.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CONCLUSION
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Gamma of Gamma represents a fundamental shift in signal philosophy: from reacting to momentum to anticipating momentum.
By operating at the third derivative of order flow, this system detects the mathematical signatures of regime transition — the moments when current pressure dynamics become unsustainable and reversal becomes probable.
This is not another oscillator telling you what already happened. This is an anticipation engine positioning you for what's about to happen.
Stop chasing. Start anticipating.
RSI tells you where momentum was. GoG tells you where it's going.
Taking you to school. - Dskyz , Trade with probability. Trade with anticipation. Trade with GoG
Smart Money Flow Signals [QuantAlgo]🟢 Overview
The Smart Money Flow Signals indicator synthesizes significant volume-price dynamics through multi-component analysis to identify potential accumulation and distribution phases driven by substantial market participants. It combines Money Flow Index momentum, Chaikin Money Flow accumulation patterns, volume-weighted price momentum, and buying/selling pressure metrics into a unified composite oscillator that quantifies periods of concentrated capital movement, helping traders and investors identify conditions where significant volume participants may be actively positioning across multiple market conditions and timeframes.
🟢 How It Works
The indicator's core methodology lies in its weighted composite approach, where multiple volume-price components are calculated sequentially and then integrated to create a comprehensive significant flow activity signal.
First, the Money Flow Index (MFI) is calculated to measure buying and selling pressure by incorporating volume into price momentum analysis:
raw_money_flow = source * volume
positive_flow = source >= source ? raw_money_flow : 0
negative_flow = source < source ? raw_money_flow : 0
positive_money_flow = math.sum(positive_flow, mfi_period)
negative_money_flow = math.sum(negative_flow, mfi_period)
money_flow_index = 100 - 100 / (1 + positive_money_flow / negative_money_flow)
This creates an RSI-style momentum indicator that tracks whether money (price × volume) is flowing into or out of the asset, with values ranging from 0 to 100 where readings above 50 suggest buying pressure dominance.
Then, Chaikin Money Flow (CMF) is computed to evaluate accumulation and distribution by analyzing where prices close within each bar's range, weighted by volume:
money_flow_multiplier = high != low ? (close - low - (high - close)) / (high - low) : 0
money_flow_volume = money_flow_multiplier * volume
volume_sma = ta.sma(volume, trend_period)
chaikin_money_flow = volume_sma != 0 ? ta.sma(money_flow_volume, trend_period) / volume_sma : 0
Positive CMF values indicate accumulation (closes near the high of the range), while negative values indicate distribution (closes near the low of the range), with volume weighting emphasizing periods of significant participation.
Next, Volume Analysis is performed to quantify current volume intensity relative to historical averages:
volume_average = ta.sma(volume, trend_period)
volume_strength = volume_average != 0 ? volume / volume_average : 1
volume_weight = math.log(volume_strength + 1)
The logarithmic transformation creates a volume weight that amplifies signals during high-volume periods while preventing extreme volume spikes from overwhelming the composite calculation.
Following this, Buy/Sell Pressure is quantified by comparing cumulative volume during bullish versus bearish candles:
buying_pressure = math.sum(volume * (close >= open ? 1 : 0), trend_period)
selling_pressure = math.sum(volume * (close < open ? 1 : 0), trend_period)
pressure_ratio = (buying_pressure - selling_pressure) / (buying_pressure + selling_pressure) * 100
This creates a directional pressure ratio that reveals whether significant participants are predominantly buying or selling, expressed as a percentage between -100 (all selling) and +100 (all buying).
Then, Volume-Weighted Momentum is calculated through an exponential smoothing channel that adjusts price deviation based on volume intensity:
exponential_smooth_average = ta.ema(source, momentum_channel_period)
deviation = ta.ema(math.abs(source - exponential_smooth_average), momentum_channel_period)
channel_index = deviation != 0 ? (source - exponential_smooth_average) / (0.015 * deviation) * (1 + volume_weight * 0.5) : 0
This channel index measures how far price has deviated from its exponential average relative to typical deviation, with the volume weight multiplier (1 + volume_weight * 0.5) amplifying the signal when significant volume accompanies the price movement.
Finally, the Composite Wave is constructed by combining all components with specific weighting to create the final oscillator:
momentum_wave = ta.ema(channel_index, trend_period)
money_flow_wave = (money_flow_index - 50) * 1.2
chaikin_flow_wave = chaikin_money_flow * 100
composite_wave = momentum_wave * 0.5 + chaikin_flow_wave * 0.3 + money_flow_wave * 0.2
smoothed_wave = ta.sma(composite_wave, signal_smoothing)
This creates a multi-dimensional volume flow oscillator that combines price-volume momentum, accumulation-distribution patterns, and buying-selling pressure into a single signal, providing traders with probabilistic insights into periods of concentrated market activity and directional bias based on weighted component convergence.
🟢 Signal Interpretation
▶ Positive Values (Above Zero, Green): Composite money flow above equilibrium indicating net accumulation pressure, positive buying volume dominance, and bullish volume-price alignment = Favorable conditions for long positions, significant capital flowing into the asset = Buy/hold opportunities
▶ Negative Values (Below Zero, Red): Composite money flow below equilibrium indicating net distribution pressure, negative selling volume dominance, and bearish volume-price alignment = Unfavorable conditions for long positions, significant capital flowing out of the asset = Sell/short opportunities
▶ Extreme Overbought Zone: Excessive bullish money flow indicating potential accumulation exhaustion, where buying pressure may have reached unsustainable levels with elevated reversal risk = Caution on new longs, potential distribution phase beginning, profit-taking zone for existing positions
▶ Extreme Oversold Zone: Excessive bearish money flow indicating potential distribution exhaustion, where selling pressure may have reached unsustainable levels with elevated reversal risk = Caution on new shorts, potential accumulation phase beginning, buying opportunity zone for contrarian entries
▶ Smoothed Trend Line (White) Alignment: When the smoothed trend line confirms the composite wave direction, it validates the underlying volume-price trend and filters false signals caused by short-term noise
▶ Volume Intensity Correlation: Gradient intensity (color saturation) reflects combined wave strength, volume participation, and directional alignment, where darker/more saturated colors indicate stronger concentrated activity and higher-probability directional moves
🟢 Features
▶ Preconfigured Presets: Three optimized parameter configurations accommodate different trading styles, timeframes, and market analysis approaches.
1. "Default" provides balanced volume flow measurement suitable for swing trading on 4-hour and daily charts, offering moderate responsiveness to money flow shifts with standard RSI-equivalent MFI period and moderate smoothing for most market conditions.
2. "Fast Response" delivers heightened sensitivity optimized for active intraday trading and scalping on 1-minute to 1-hour charts, using compressed calculation periods across all components and minimal smoothing to capture rapid volume flow changes and quick trend shifts as they develop, ideal for early entry/exit opportunities with acceptance of increased signal frequency during consolidation.
3. "Smooth Trend" offers conservative extreme identification ideal for position trading and long-term analysis on daily to weekly charts, employing extended periods across all money flow components with substantial smoothing to filter short-term noise and isolate only strong, sustained accumulation and distribution phases driven by significant volume participants.
▶ Built-in Alerts: Seven alert conditions enable comprehensive automated monitoring of significant money flow transitions and extreme market states.
1. "Bullish Flow" triggers when the composite wave crosses above zero, signaling the shift from distribution to accumulation and concentrated buying activity beginning.
2. "Bearish Flow" activates when the composite wave crosses below zero, signaling the shift from accumulation to distribution and concentrated selling activity starting.
3. "Any Flow Direction Change" provides a combined notification for either bullish or bearish crossover regardless of direction, useful for general money flow momentum shifts.
4. "Extreme Overbought" alerts when the composite wave reaches or exceeds the overbought threshold (default +60), indicating excessive buying pressure and potential exhaustion.
5. "Extreme Oversold" notifies when the composite wave reaches or falls below the oversold threshold (default -60), indicating excessive selling pressure and potential capitulation.
6. "Overbought Reversal" triggers specifically when the wave crosses back down through the overbought level after being extended, signaling the beginning of distribution from extreme levels.
7. "Oversold Reversal" activates when the wave crosses back up through the oversold level after being extended, signaling the beginning of accumulation from extreme levels.
▶ Color Customization: Six visual themes (Classic, Aqua, Cosmic, Ember, Neon, plus Custom) accommodate different chart backgrounds and visual preferences, ensuring optimal contrast and immediate identification of bullish versus bearish volume flow conditions across various devices and screen sizes. Optional bar coloring provides instant visual context of current significant volume activity intensity and direction without switching between the price pane and indicator pane, enabling traders and investors to immediately assess volume-price positioning dynamics while analyzing price action.
ChannellerChanneller Pro - Multi-Pivot Regression Channels with Trend Validation
What This Indicator Does
Channeller Pro automatically detects and draws price channels by connecting multiple pivot points using linear regression rather than simply connecting two points. The indicator displays parallel support and resistance lines that define the current trend channel, along with an optional mid-line for mean reversion analysis.
Channels automatically appear when valid trend conditions are met and disappear when the trend structure breaks, keeping your chart clean and showing only actionable information.
---
How It Works (Methodology)
1. Multi-Pivot Linear Regression
Unlike simple channel indicators that connect only 2 pivot points, this indicator collects 3-5 pivot lows (for bullish channels) or pivot highs (for bearish channels) and calculates a least-squares linear regression line through them. This produces a statistically best-fit trendline that is more resistant to noise from a single errant pivot.
The regression calculation outputs:
- Slope: The angle/direction of the trend
- Intercept: The starting price level
- R² (coefficient of determination): A value from 0 to 1 measuring how well the pivot points align. Higher R² means the pivots form a cleaner, more reliable trendline. The default minimum is 0.70.
2. Higher-Low / Lower-High Pattern Validation
For a bullish channel to form, the indicator requires each successive pivot low to be higher than the previous pivot low (the definition of an uptrend). For bearish channels, each pivot high must be lower than the previous (downtrend structure). This filter prevents channels from forming during choppy, non-trending conditions.
3. ADX Trend Strength Filter
The indicator calculates the Average Directional Index (ADX) to measure trend strength. Channels only appear when ADX exceeds a user-defined threshold (default: 20). When ADX drops below this level, indicating the trend has weakened, channels automatically disappear. This prevents false channels during sideways/ranging markets.
4. Channel Width Calculation
Once the regression support line is established, the indicator finds the highest high (for bull channels) or lowest low (for bear channels) between the first and last pivot. A parallel line is drawn at this distance to form the opposite channel boundary.
5. Channel Respect Monitoring
The indicator tracks how price interacts with channel boundaries:
- Bounces: Price touches the boundary and reverses
- Pierces: Price closes beyond the boundary
If price pierces through a channel boundary multiple times, the channel is invalidated and removed, signaling the trend structure has broken.
---
How to Use This Indicator
Identifying Trends
- A green channel (bullish) indicates an uptrend with higher lows
- A red channel (bearish) indicates a downtrend with lower highs
- The R² value in the label shows channel quality (higher = more reliable)
Trading Applications
- Trend Following: Trade in the direction of the channel slope
- Support/Resistance: Use channel boundaries as potential reaction zones
- Mean Reversion: The optional mid-line (dashed) can serve as a target for pullback entries
- Breakout Preparation: When a channel disappears, it signals the prior trend structure has ended
Reading the Labels
- "BULL R²:0.85 (4 pivots)" means a bullish channel with 85% regression fit using 4 pivot points
- Orange-colored labels indicate weaker channels (R² between 0.70-0.85)
- Green/red labels indicate stronger channels (R² above 0.85)
---
Input Settings Explained
| Setting | Description |
|---------|-------------|
| Pivot Lookback Left/Right | Bars required on each side to confirm a pivot high/low |
| Min Pivots for Channel | Minimum pivot points required (more = stricter) |
| Max Pivots to Track | Maximum pivots stored (older pivots are dropped) |
| Min R² Score | Minimum regression quality (0.70 = 70% fit) |
| ADX Threshold | Minimum ADX value to show channels (20 = moderate trend) |
| Require HL/LH Pattern | Enforce higher-lows for bull, lower-highs for bear |
---
What Makes This Different
This indicator combines multiple validation layers that work together:
1. Regression vs. 2-point lines: More statistically robust trendlines
2. R² quality scoring: Quantifies how clean the trend structure is
3. Pattern validation: Ensures proper trend structure (HL/LH)
4. ADX filtering: Confirms trend exists before drawing channels
5. Auto-invalidation: Channels disappear when broken, not manually
These components create a self-cleaning channel system that only displays high-probability trend channels.
---
Alerts Available
- Bull/Bear Channel Formed
- Bull/Bear Channel Broken
- New Pivot High/Low Detected
Hooke's Law: Market ElasticityHooke's Law: Market Elasticity is a physics-based mean reversion system that models price action using the principles of Classical Mechanics.
Most technical indicators treat the market as a purely statistical entity. This script takes a different approach, treating the market as a physical object with Mass (Volume) and Stiffness (Volatility) . By adapting Hooke’s Law of Elasticity (𝐹=−𝑘𝑋), it visualizes the "Tensile Stress" between price and its equilibrium, identifying the exact moment when a trend becomes unsustainable and must "snap back."
The Physics of Trading
In physics, Hooke's Law states that the force needed to extend a spring is proportional to the distance it is stretched. We map this to financial markets using four key components:
Equilibrium (𝑋=0): The "Resting State" of the market, calculated using a Volume-Weighted Moving Average (VWMA) . This represents the fair value where buyers and sellers agree.
2. Displacement (𝑋): The distance price travels away from this equilibrium.
3. Spring Constant (𝑘): We use Volatility (Standard Deviation) to measure the market's "stiffness."
• Low Volatility: The spring is loose; price can wander far without snapping.
• High Volatility: The spring is stiff; even small deviations create massive tension.
4. Force (𝐹): The calculation is weighted by Relative Volume . A price spike on low volume has low force (easy to reverse), while a spike on high volume carries high momentum (harder to reverse).
Visual Guide & Signals
The indicator uses a hierarchy of visuals to guide you through the trade lifecycle:
1. The Elastic Ribbon (Heatmap)
Connects Price to the Baseline. As the ribbon turns Solid White , the market has reached its Elastic Limit (Critical Zone). This is your warning that a move is overextended.
2. The "Golden" Labels (LONG / SHORT)
These are your Entry Signals . They appear only when the physics "snap" is confirmed by an internal momentum filter and price action.
3. The Small Circles (Minor Reversions)
These dots represent "Minor Snaps." They occur when the elastic tension releases, but the momentum filter hasn't fully confirmed a major reversal.
• Usage: These are excellent Early Warning signs or Scale-In points for aggressive traders.
Strategy: Entries, Exits & Take Profits
This script is designed as a complete system. Here is how to manage the trade using the visual cues:
• Entry: Wait for a LONG or SHORT label to appear.
• Stop Loss: Use the Solid White Line that appears automatically with the signal. If price touches this line, the physics setup has failed—exit immediately.
• Take Profit 1 (The Equilibrium): The Gray Baseline represents the market's center of gravity. In mean reversion trading, price tends to snap back to this line. This is the statistically highest-probability target.
• Take Profit 2 (The Circles): If you are in a trade and a Circle appears in the opposite direction, it indicates the market is experiencing counter-tension. This is an ideal place to secure partial profits or trail your stop.
Settings & Configuration
• Baseline Length (Default: 34): The lookback period for the Center of Gravity.
• Elasticity Limit (Default: 2.618): The Golden Ratio is used as the standard deviation threshold for the "Critical Zone."
• Volume Weighting (Default: True): Recommended. Adds the "Mass" component to the physics calculation.
• Stop Loss Buffer (Default: 0.5): The distance (in Sigma) for the Stop Loss placement.
Risk Disclaimer
Not Financial Advice: This indicator is designed for educational and analytical purposes only. It visualizes market data based on mathematical formulas (Hooke's Law and Statistical Deviation) and does not guarantee future performance or profits.
Market Risks: Financial trading involves significant risk. The "Critical Zones" and "Signals" generated by this script identify statistical extremes, but markets can remain irrational or overextended for long periods ("Plastic Deformation").
Usage: Do not trade blindly based on these signals. Always use this tool in conjunction with your own analysis, risk management, and stop-losses. The author assumes no responsibility for any trading losses incurred while using this script.
Universal Adaptive Tracking🙏🏻 Behold, this is UAT (Universal Adaptive Tracker) , with less words imma proceed how it compares with alternatives:
^^ comparison with non-adaptive quadratic regression (purple line), that has higher overshoots, less precision
^^ comparison with JMA and its adaptive gain. JMA’s gain is heavily limited, while UAT’s negative and positive gains are soft-saturated with p-order Möbius transform
This drop is inspired by, dedicated to, and made will all love towards Jurik Research , who retired in October 2k21. When some1 steps out, some1 has to step in, and that time it’s me (again xd). But there’s some history u gotta know:
Some history u gotta know:
In ~2008 dudes from forexfactory reverse engineered Jurik Moving Average
In late 1990s dudes from Jurik Research approximated the best possible adaptive tracking filter for evolution of prices via engineering miracles
Today in 2k26, me I'm gonna present to you the real mathematical objects/entities behind JMA top-edge engineered approximates. You will prolly be even more happy now then all the dem together back then.
Why all this?
When we talk about object tracking stuff, e.g. air defense, drones, missiles, projectiles, prices, etc, it all comes down to adaptive control and (Position & Velocity & Acceleration) aka PVA state space models (the real stuff many of you count as DSP ).
Why? Cuz while position (P) : (mean), or position & velocity (PV) : (linear regression) are stable enough in dem own ways, Position & Velocity & Acceleration (PVA) : (quadratic regression+) require adaptivity do be stable. And real world stuff needs PVA, due to non-linearity for starters.
So that’s why. If your goal is Really smoothing and no lag, u gotta go there. I see a lot of folks are crazy with it and want it, so here is it, for y’all. And good news, this is perfect for your favorite Moving Windows.
How to use it
The upper study:
The final filter (main state): just as you use other fast smoothers, MAs, etc, you know better than me here
You can also turn in volatility bands in script’s style settings, these do not require any adjustments
Finally, you can turn on, in the same place, separate trackers each based on negative and positive volatility exclusively. When both are almost equal, that indicates stability & persistence in markets. May sound like it’s nothing important, but I've never seen anything like it before. Also, if you'd allow your our inner mental gym hero gloriously arise, you can argue that these 2 separate trackers represent 2 fair prices (one for sellers, one for buyers). All better then 1 imaginary fair price for both (forget about it)
The lower study:
The lower study: you can analyze streams of upward of downward volatilities separately. This is incredibly powerful
You can also turn these off and turn on neg & pos intensities, and use them as trend detector, when each or both cross 1.5 (naturally neutral) threshold.
^^ Upper study with expected typical and maximum volatility bands turned On
...
The method explained
What you got in the end is non-linear, adaptive, lighting fast when needed and slow when required price tracking. All built upon real math entities/objects, not a brilliantly engineered approximation of them. No parameters to optimize, data tells it all.
... It all starts from a process model, in our cause this is...
MFPM (Mechanical Feedback Price Model)
Doesn’t make gaussian assumptions like most quant mainstream tech, accepts that innovations are Laplace “at best”, relies in L inf and L0 spaces.
I created this model neither trynna fit non-fitting ARMA / variants, nor trynna be silly assuming that price state evolution and markets are random.
Theory behind it: if no new volume comes, then price evolution would be simply guided by the feedback based on previous trading activity, pushing prices towards the midrange between 2 latest datapoints, being the main force behind so called “pullbacks” and reason why most pullbacks end just a bit past 50% of a move.
This is the Real mechanical feedback based mean reversion, that is always there in the markets no matter what, think of it as a background process that is always there, and fresh new volume deviates prices away from it. Btw, this can also be expressed as AR2 with both phis = 0.5 .
Then I separate positive and negative innovations from this model and process them separately, reflecting the asymmetry between buy and sell forces, smth that most forget. Both of these follow exponential distribution . Each stream has its own memory so here we use recursive operators . We track maximum innovations (differences between real and expected datapoints) with exponentially decaying damping factor, and keep tracking typical innovation, with the same factor.
Then we calculate what’s called in lovely audio engineering as “ crest factor ”, the difference is we don’t do RMS and stuff. But hey again we work with laplace innovations, so we keep things in L0 and L inf spirit. Then we go a couple of steps further, making this crest factor truly relative (resolution agnostic), and then, most importantly, we apply a natural saturation on it based on p-order Möbius transform, but not with arbitrary p and L, but guided by informational limits of the data. These final "intensity" parameters are what we need next to make our object tracking adaptive.
Extended Beta(2, 2) Window
This is imo the main part of this. Looking at tapering windows in DSP and how wavelets are made from derivatives of PDF functions of probability distributions, I figured that why use just one derivative? That made me come up with Universal Moving Average , that combines PDF and CDF of Beta(2, 2) distribution . And that is fine for P (position) tracking model.
Here we need PVA (position & velocity & acceleration). We can realize that everything starts from PDF, and by adding derivatives and anti-derivatives of it as factors of final window weights, we can create smth truly unique, a weightset that is non-arbitrary and naturally provides response alike quadratic regression does, But, naturally smoothed.
Why do I consider this a discovery, a primordial math object? Because x^2 itself and Beta(2, 2) based on it are the only primitives, esp out of all these dozens of DSP tapering windows, that provide you a finite amount of derivatives. You can keep differentiating Hann window until the kingdom f come, while Welch window aka Beta(2, 2) has a natural stopping point, because the 3rd derivative is 0, so we can’t use it. Symmetrically, we do 2 steps up from PDF, getting 1st and second anti-derivatives. What’s lovely, symmetrically, 3rd antiderivative even tho exist, it stops making any sense. 2nd one still makes sense, it’s smth like “potential” of probability distribution, not really discussed in mainstream open access sources.
Finally, the last part is to introduce adaptivity using these intensity exponents we’ve calculated with MFPM. We do 2 separate trackers, one using the negative intensity exponent, another one uses positive intensity exponent.
And at the end, even tho using both together is cool, the final state estimate is calculated simply as the state which intensity has higher.
^^ impulse response of our final kernel with fixed (non adaptive) intensity exponents: 1 (blue) and 2 (red). You see it's all about phase
…
And that’s all folks.
…
Actually no …
Last, not least, is the ability to add additional innovation weight to the kernel:
^^ Weighting by innovations “On”. Provides incredible tracking precision, paid with smoothness. I think this screenshot, showing what happened after the gap, and how the tracker managed to react, explains it all.
...
Live Long and Prosper, all good TradingView
∞
Smart Signal Assistant (Kewme)Smart Signal Assistant (Kewme) – Professional Trading Suite
Overview The Smart Signal Assistant (Kewme) is a comprehensive, all-in-one trading toolkit designed to bring institutional-grade discipline and visual clarity to your trading. Unlike clutter-heavy indicators, this system focuses on precision and risk management. It combines a powerful trend-following engine with an automated trade manager that visualizes your risk and reward in real-time.
Key Features
1. 🛡️ Disciplined Trade Management (One Trade at a Time) Stop over-trading with the built-in "Focus Mode."
No Signal Spam: The system will never generate a new signal while a trade is currently running.
Active Management: A new signal is only generated after the current trade has either hit the Take Profit (TP) or the Stop Loss (SL). This enforces strict trading discipline.
2. 📦 Dynamic Risk/Reward Boxes Visualizing your trade has never been easier.
Instant Zones: Upon a signal, the script automatically draws a Green Profit Zone and a Red Loss Zone directly on the chart.
ATR-Based Precision: Stop Loss levels are calculated dynamically using Average True Range (ATR), ensuring your stops breathe with market volatility.
Auto-Cutoff: The boxes automatically stop drawing the moment price hits your TP or SL, keeping your chart clean and historical performance visible.
3. 🎯 Clear Exit Labels No more guessing. The script clearly marks the exact candle where your trade closed:
TP Hit 🎯: Appears when your target is reached.
SL Hit ❌: Appears if the market goes against you.
4. 🚀 Smart Trend Engine & Filters
Hybrid Modes: Choose between "Swing" (for reliable, long-term trends) or "Scalping" (for quick, short-term moves).
Trend-Range Classifier (TRC): An intelligent filter system that monitors ADX and market volatility. It automatically blocks signals during choppy, sideways markets to protect your capital.
5. 📊 Live Status Dashboard A sleek, on-chart dashboard provides real-time data at a glance:
Trade Status: Shows if a trade is "RUNNING" or "SEARCHING."
Market Bias: Bullish or Bearish.
Trend Strength: Indicates if the market is Strong or Sideways.
How to Use
Select Mode: Choose 'Swing' for higher timeframes or 'Scalping' for lower timeframes in settings.
Adjust Risk: Set your preferred Risk/Reward Ratio (e.g., 1:2) and SL Multiplier.
Follow the Boxes: Enter when the box appears, and exit exactly when the "TP Hit" or "SL Hit" label pops up.
Disclaimer: This tool is for educational and assistance purposes only. Always use proper risk management.
Magnitude of Price DiscoveryThis script is a simple attempt to show the magnitude of price discovery
Before we discuss how it works we need to discuss our terms.
Universal Truth of Price #1 - Price only trades in 3 distinct ways
Scenario 1 - Inside bar to previous range, consolidation.
Scenario 2 - Trending bar up or down, HH + HL to previous bar or LL + LH to previous bar
Scenario 3 - Outside bar, Higher highs AND lower lows to previous bar. Also known as a broadening formation.
If you are interested in the 2nd universal truth my indicator 'Timeframe Continuity Bars' discusses it there.
Given one of the 3 scenarios price can trade in is a broadening formation it proves that price discovery occurs as a series of new highs and new lows.
Notice the scenario 3 marked by SimpleStratNumbers
This scenario 3 is a broadening formation on the 1min and on the 30min basis.
Given this is true we know if price rejects the broadening highs it is attempting to make new lows to the broadening range
So, what this indicator does is it uses previous swing highs and swing lows and it shows you when price reclaims them and gives you a target.
The target of this indicator is guaranteed to be hit if the 2nd universal truth of price is in your favor.
This means if we reclaim a previous high to the downside. At the time of all known participation groups selling we know the magnitude of this selling would be the other side of the range
So it's simple, the solid line shows you the reclaimed level.
The dotted line shows you the magnitude.
Full timeframe continuity tells you when it is FOR SURE going to your target price via MTF analysis of the aggressiveness of the buyers/sellers.
However timeframe continuity is subject to change every 60min, every day, every week, and every month! That's the risk you take when trading.
Here's one example for you.
NASDAQ:AAPL monthly made a new low and changed to green this was your evidence price is attempting to take the other side of the range.
NASDAQ:AAPL monthly opened green again and re-confirmed the upside which meant the other side
of the range was still for certain going to be taken out.
After being taken out, breakout traders buy the highs and any shorts in aapl are forced to cover.
BOOM!
This indicator is likely to be updated in the near future to align entries on multiple timeframes.
Nothing spoken here is financial advice and it is ONLY what we know to be true about price action.
Mobius Trend Pivot (NPR21 v6)Mobius Trend Pivot (NPR21 v6)
Overview
This indicator identifies trend pivots using higher highs with higher lows (bullish trends) and lower lows with lower highs (bearish trends). Originally created by Mobius (V01.01.29.2019) for ThinkOrSwim, this Pine Script conversion maintains the original logic while fixing critical rendering issues found in previous TradingView versions.
How It Works
The indicator tracks price trends over a user-defined lookback period (default n=5) to establish pivot points. When a valid trend pivot forms, the indicator plots:
Red zone (bearish): Upper pivot line with confirmation level below
Green zone (bullish): Lower pivot line with confirmation level above
White dashed lines: Risk-off levels for position management
Confirmation levels are calculated as a multiple (R_Mult, default 0.7) of the Average True Range at the pivot.
Trading Rules (from Mobius original code)
Entry: Trade when price crosses and closes outside the pivot confirmation line
Risk Management: Use the pivot line itself as your risk point - exit if crossed (avoid hard stops)
Risk-Off: Target an ATR multiple for initial profit taking to achieve a risk-free trade
Stop Management: Move mental stop to break-even once risk-off is achieved
Runner Management: Adjust mental stop to new support/resistance levels as they form
What Makes This Version Different
NPR21 v6 fixes critical bugs present in other TradingView versions:
✅ Consistent transparency - The red/green cloud fills maintain constant 85% transparency and no longer progressively darken over time
✅ No overlapping renders - Eliminated the issue where multiple indicator instances would layer on top of each other, creating visual clutter
✅ Proper memory management - Implements linefill deletion/recreation logic to prevent object accumulation
✅ Clean visual display - Matches the original ThinkOrSwim appearance with professional-looking zones
Key Features
Automatic pivot detection based on price structure
Dynamic support/resistance zones
Built-in risk management levels
Alert capability for pivot confirmation crossovers
Minimal lag - responds quickly to trend changes
Works on all timeframes and instruments
Settings
n (default 5): How many bars to look back for trend confirmation
R_Mult (default 0.7): Adjusts how far the confirmation lines sit from pivots
Lower n = more sensitive, more signals
Higher n = less sensitive, fewer signals
Color Scheme
Red lines/zones: Bearish pivots and short trade setups
Green lines/zones: Bullish pivots and long trade setups
White dashed lines: Risk-off target levels
Best Practices
Use 2+ contracts to implement the risk-off strategy
Combine with price action and volume for confirmation
Adjust n and R_Mult based on instrument volatility
Works best on liquid futures and forex pairs
Consider using higher timeframes for swing trades
Credits
Original indicator concept and logic: Mobius (ThinkOrSwim, January 2019)
Pine Script conversion and optimization: NPR21
Note: This indicator is for educational purposes. Past performance does not guarantee future results. Always practice proper risk management and position sizing.
RSI Sigmoid (Saturation)# 📊 RSI Sigmoid (Saturation) Indicator
---
## 🎯 What Does This Indicator Do?
This indicator transforms the traditional **RSI (Relative Strength Index)** using a **sigmoid function**, creating a mathematically "saturated" version that provides smoother, more controlled momentum signals.
---
## ✨ Key Features
### 🌊 **Saturation Effect**
Unlike standard RSI which oscillates wildly between 0-100, this version uses a **hyperbolic tangent function** to compress extreme values:
- 🔴 **Extreme readings** (very high/low) are dampened → pushed toward saturation zones (10 & 90)
- 🟡 **Middle range** (30-70) remains responsive and dynamic
- 🟢 **Sharp spikes** are smoothed while maintaining trend direction
### 👁️ **Dual Visualization**
- **🔵 Blue Line**: RSI Sigmoid (Saturated) - Your primary signal
- **🟠 Orange Circles**: Traditional RSI - For comparison
- **🟣 Purple Area**: Difference plot showing transformation intensity
### 🎯 **Smart Signals**
- **▲ Green Triangle**: Buy Signal when RSI Sigmoid crosses **above 50**
- **▼ Red Triangle**: Sell Signal when RSI Sigmoid crosses **below 50**
- **🎨 Background Colors**: Highlight oversold, overbought, and saturation zones
---
## ⚙️ How to Use
### 📐 **RSI Period** (Default: 50)
```
Higher Values (70-100) → Smoother, slower, fewer signals
Lower Values (14-30) → More responsive, more signals, noisier
```
### 🎚️ **Sigmoid Coefficient** (Default: 0.5)
```
Low (0.1-0.2) → Gentle saturation, closer to standard RSI
Medium (0.25) → Balanced transformation
High (0.3-0.5) → Aggressive saturation, strong dampening
```
### 📍 **Oversold/Overbought Levels**
Customize based on your:
- Trading timeframe (1m, 5m, 1h, 1D, etc.)
- Asset volatility
- Trading style (scalping, swing, position)
---
## 🔍 What to Watch For
| Signal | Meaning | Action |
|--------|---------|--------|
| 🟢 **Cross Above 50** | Bullish momentum shift | Consider long positions |
| 🔴 **Cross Below 50** | Bearish momentum shift | Consider short positions |
| ⚡ **Saturation < 10** | Extreme oversold | Potential reversal up |
| 🔥 **Saturation > 90** | Extreme overbought | Potential reversal down |
| 🟣 **Large Difference** | High transformation intensity | Strong momentum dampening |
---
## 💡 Trading Tips
✅ **DO:**
- Use multiple timeframes for confirmation
- Combine with support/resistance levels
- Apply proper risk management (stop-loss, position sizing)
- Backtest settings on your specific asset
- Watch for divergences between price and indicator
❌ **DON'T:**
- Rely solely on this indicator
- Ignore market context and fundamentals
- Over-leverage based on signals
- Use default settings without testing
- Trade without a clear strategy
---
## ⚠️ IMPORTANT DISCLAIMERS
### 🚨 **NOT Financial Advice**
This indicator is provided for **educational and informational purposes only**. It does not constitute financial, investment, or trading advice.
### 🛡️ **Risk Warning**
- ❌ **No guarantee of profits** - Past performance ≠ future results
- ❌ **Do not rely on this alone** - Always use multiple analysis methods
- ❌ **Markets are unpredictable** - No indicator can predict with certainty
- ❌ **You can lose money** - Never risk more than you can afford to lose
### 🎛️ **Customization Required**
All settings are **user-configurable** for a reason:
- Default values may NOT suit your strategy
- Different assets require different parameters
- Always backtest before live trading
- Adjust based on your timeframe and risk tolerance
### 📜 **Your Responsibility**
- ✓ You are responsible for your own trading decisions
- ✓ Always do your own research (DYOR)
- ✓ Understand the risks before trading
- ✓ Consider consulting a licensed financial advisor
---
## 📋 Quick Settings Guide
| Trading Style | RSI Period | Sigmoid K | Notes |
|---------------|------------|-----------|-------|
| **Scalping** | 14-21 | 0.3-0.4 | Fast signals, higher noise |
| **Day Trading** | 30-50 | 0.4-0.5 | Balanced responsiveness |
| **Swing Trading** | 50-70 | 0.5 | Smoother, fewer false signals |
| **Position Trading** | 70-100 | 0.5 | Very smooth, major trends only |
---
## 🏷️ License & Liability
**Use at your own risk.** The creator assumes **no liability** for any trading losses, damages, or consequences resulting from the use of this indicator.
---
### 🤝 Happy Trading & Stay Safe! 📈
*Remember: The best indicator is your own knowledge and discipline.*
Dynamic MTF Reversal Sequential [Realtime]SMA Reversal Sequential MTF Engine
Professional Pivot Identification & Squeeze Analysis
1. Overview
The SMA Reversal Sequential MTF Engine is a sophisticated environment recognition tool that monitors 8 timeframes (1m to Monthly) to identify objective Pivot Highs and Lows.
Unlike standard indicators that rely on simple price-crosses, this engine determines structural market turns based on the curvature (slope) of the SMA. By automating the detection of price consolidation (Squeeze) and synchronizing it with higher timeframe trends, it provides a systematic approach to capturing high-probability breakout opportunities.
2. Input Settings & Operations
Each parameter is designed to help you filter noise and focus on the market structure that suits your trading style.
■ Main Settings
Use Short Period:
ON: Uses (5, 3, 7) periods. Ideal for scalping. It identifies micro-pivots and sensitive trend shifts.
OFF: Uses (20, 6, 20) periods. Designed for Day/Swing trading. It filters out noise and focuses on major structural highs and lows.
Hide Lower Timeframes:
Automatically hides labels from timeframes shorter than your current chart (e.g., hiding 1m labels while on a 1H chart) to maintain a clean workspace.
Break Label Right Offset:
Adjusts the horizontal position of the "Breakout" price labels on the right side of the chart.
■ Drawing Options
Show Only Current TF Labels:
When enabled, it hides "15", "1H" labels from other timeframes on the chart. Note: The MTF Dashboard will still track all timeframes regardless of this setting.
Show Trendlines & Channels:
Plots lines connecting determined Pivot Highs and Lows, visualizing the current "Trading Range" or "Channel."
Show ZigZag Line:
Connects the confirmed Highs and Lows with straight lines, making "Market Structure" (Higher Highs / Lower Lows) instantly recognizable.
Hide Outer Channel on Squeeze:
During a Squeeze (consolidation), this hides older wide channels to highlight the immediate converging boundaries.
3. Core Logic: Determining Highs & Lows
This engine determines "Pivots" through a logical three-step process:
SMA Reversal Detection: The engine calculates when the SMA slope changes from down to up (or vice versa) using a sequential offset comparison.
Pivot Determination: Once an SMA turn is confirmed, the highest/lowest price point during that turn is determined as a structural Pivot High/Low.
Squeeze Identification: When the last two determined Highs are "Lower Highs" and the last two Lows are "Higher Lows," the engine identifies a Squeeze (Triangle Consolidation) and marks it with a Green Dot (●).
4. How to Trade (Step-by-Step)
Check the MTF Dashboard: Look at the top-right table. If the higher timeframes (4H, 1D) are Blue, the market is in a structural uptrend (making new Highs).
Wait for the Squeeze: Wait for the Green Dot (●) on your current timeframe. This signifies that energy is being stored within a tight range.
The Breakout Signal: When the price breaks the squeeze in the direction of the higher timeframe trend, a Rocket (🚀) or Lightning (⚡) icon appears. This is a high-probability entry point where a lower-timeframe consolidation resolves into a higher-timeframe trend.
5. Important Notes
As an SMA-based tool, it is a "Lagging Indicator" by nature. It focuses on structural confirmation rather than predicting unpredictable price spikes.
Always prioritize the MTF Dashboard colors. Trading against the higher timeframe trend is not recommended.
SMA Reversal Sequential MTF Engine
〜多時間軸SMA反転による高値安値確定と保合い分析〜
1. 概要 (Overview)
本スクリプトは、8つの時間軸(1分足〜月足)におけるSMA(単純移動平均線)の傾きを解析し、**「主観を排除した客観的な高値・安値」**を自動で決定するマルチタイムフレーム(MTF)環境認識エンジンです。
最大の特徴は、価格の上下に一喜一憂するのではなく、移動平均線という「相場の平均的な流れ」が反転したポイントを「真の節目(Pivot)」として定義する点にあります。これにより、ボラティリティの収束(スクイーズ)と、上位足に同期した高確率なブレイクアウトをシステマチックに捉えることができます。
2. インプット設定の完全解説 (Input Settings)
ユーザーが設定画面で調整できる各項目の具体的な意味と、変更による効果を解説します。
■ 基本設定 (Main Settings)
短期設定を使用 (Use Short Period):
ON: 期間 (5, 3, 7) を使用。スキャルピングや短期トレード向け。非常に細かく高値・安値を決定し、微細な反転も逃さず捉えます。
OFF: 期間 (20, 6, 20) を使用。デイトレード〜スイング向け。ノイズを排除し、主要な大きな波の高値・安値のみを決定します。
下位足を非表示 (Hide Lower Timeframes):
ON: 現在のチャートより短い足(例:1時間足を表示中に1分・5分足のサインなど)を隠します。上位足の構造把握に集中し、チャートをスッキリさせたい時に有効です。
ブレイク文字の右オフセット:
チャート右側の余白に表示される価格情報の位置を調整します。数値が大きいほど右側に移動します。
■ 表示設定 (Drawing Options)
現在足のラベルのみ表示 (Show Only Current TF Labels):
ON: チャート上の「15」「1H」といった他時間足のサインを非表示にします。
利点: 右上のダッシュボードには全情報が維持されるため、視認性を高めつつ、MTF分析の精度を維持できます。
トレンドライン&チャネル (Show Trendlines & Channels):
確定した高値同士・安値同士を線で結びます。現在の価格が「どの価格幅の範囲内(チャネル)」で推移しているかを可視化します。
ZigZagライン (Show ZigZag Line):
確定した高値と安値を交互に直線で結びます。ダウ理論的な「上昇・下落の波」の推移が一目で把握可能になります。
保合い中は外側ラインを非表示:
収束(スクイーズ)が発生した際、古い広いチャネルを隠し、今まさに機能している収束ラインのみを際立たせます。
3. 核心ロジック:高値・安値の決定プロセス
本ツールは以下の手順でチャート上の構造を構築します。
SMA反転の検知: SMAの傾きが「下落→上昇」または「上昇→下落」に転じた瞬間を計算。
節点の確定: その反転が起きた前後の最高値・最安値を**「確定した高値・安値」**として決定し、ラベルを打ちます。
スクイーズ判定: 決定された「直近2つの高値」が切り下がり、かつ「直近2つの安値」が切り上がった場合を**三角保合い(スクイーズ)**と定義し、緑のドット(●)を表示します。
4. 実戦的な操作フロー
このインジケーターを使ってどのようにトレードを組み立てるかの推奨ステップです。
環境認識 (Environment Check): 右上のダッシュボードで上位足(4H, 1D等)の色を確認。青なら「買いの高値更新中」、赤なら「売りの安値更新中」です。
保合い待機 (Squeeze Watching): 現在の足に**緑のドット(●)**が出るのを待ちます。これは決定された節目が収束し、次に大きく動くためのエネルギーを蓄積している合図です。
ブレイクの判断 (Decision): 保合いを抜けた際、ダッシュボードの上位足と同じ方向であれば、**🚀(ロケット)や⚡(稲妻)**のアイコンが出現します。これが「上位足の勢いに乗った、下位足の収束解消」という、最も期待値の高いエントリーポイントです。
5. 注意事項
本ツールは移動平均線に基づく「遅行指標」の性質を持ちます。そのため、急激なスパイク(一瞬の突発的な動き)には反応しない場合があります。
常に「上位足のトレンドがどちらを向いているか」をダッシュボードで確認し、逆張りでの使用は避けることを推奨します。
Order Blocks INDIBOT 3D | INDIBOT ABO SALTAN 11 //@version=6
indicator("Order Blocks INDIBOT 3D | INDIBOT ABO SALTAN ", overlay = true,
max_boxes_count = 500, max_labels_count = 500, max_lines_count = 500, max_polylines_count = 100, max_bars_back = 5000)
//#region CONSTANTS
// Core constants that control stored OB capacity and label size.
const int MAX_STORED_OBS = 50
const int retestSize = 4
//#endregion
//#region INPUTS
// Core user controls for OB behavior, volume delta, 3D style and alerts.
grpOB = "ORDER BLOCKS"
swingLen = input.int(5, "Swing Length", minval = 1, group = grpOB, inline = "sw", display = display.none)
bullObColor = input.color(color.new(color.teal, 55), "", group = grpOB, inline = "sw")
bearObColor = input.color(color.new(color.red, 55), "", group = grpOB, inline = "sw")
invMethod = input.string("Wick", "Invalidation", options = , group = grpOB, display = display.none)
showNearestX = input.int(3, "Show Nearest", minval = 1, maxval = 20, group = grpOB, display = display.none)
extendZones = input.int(10, "Extend Zones", minval = 0, group = grpOB,
tooltip = "This will extend the zones by X candles.", display = display.none)
showRetestLbl = input.bool(true, "Retest Labels", group = grpOB, inline = "tog")
hideInvalid = input.bool(true, "Hide Invalidated Zones", group = grpOB, inline = "tog")
grpVD = "VOLUME DELTA"
vdEnable = input.bool(true, "Enable", group = grpVD, inline = "vd")
vdBullColor = input.color(color.new(color.teal, 65), "", group = grpVD, inline = "vd")
vdBearColor = input.color(color.new(color.red, 65), "", group = grpVD, inline = "vd")
vd3D = input.bool(true, "3D", group = grpVD, inline = "3d", tooltip = "Adds 3D-style depth faces.") and vdEnable
vd3DDepth = input.int(5, "", group = grpVD, inline = "3d", minval = 1, maxval = 5, display = display.none)
displayStyle = input.string("Vertical", "Display Style", options = , group = grpVD,
tooltip = "Horizontal: split shown top/bottom. Vertical: split shown left/right across the zone.", display = display.none)
vdTfIn = input.timeframe("", "Volume Delta Timeframe", group = grpVD,
tooltip = "Lower timeframe used to estimate delta")
showTotalVol = input.bool(true, "Display Total Volume", group = grpVD,
tooltip = "Displays total volume (Bull+Bear) from the active delta source.", inline = "vd2") and vdEnable
showDeltaPct = input.bool(true, "Show Delta %", group = grpVD, inline = "vd2",
tooltip = "Shows bullish vs bearish volume split. If selected TF is lower than chart TF, uses LTF data; otherwise uses chart TF.") and vdEnable
vdTextColor = input.color(color.white, "", group = grpVD, inline = "vd2")
grpAL = "ALERTS"
alBullOB = input.bool(true, "Bullish Order Block", group = grpAL, inline = "oba")
alBearOB = input.bool(true, "Bearish Order Block", group = grpAL, inline = "oba")
alBullRetest = input.bool(true, "Bullish OB Retest", group = grpAL, inline = "obr")
alBearRetest = input.bool(true, "Bearish OB Retest", group = grpAL, inline = "obr")
//#endregion
//#region TYPES
// Custom structs for order blocks and 3D poly drawing.
type PolyParams
array points
color lineColor
color fillColor
int lineWidth
type ObRec
int leftIndex
int leftTime
int createdIndex
int createdTime
float top
float bottom
bool isBull
bool active
bool retested
int retestIndex
int retestTime
int invalidIndex
int invalidTime
float bullVol
float bearVol
float totalVol
float bullPct
float bearPct
bool hasDelta
type RetestRec
int barIndex
bool isBull
int obLeftIndex
int obCreatedIndex
//#endregion
//#region GENERIC HELPERS
// Small utilities: clearing drawings, geometry helpers, nearest-OB picking.
method clearAll(array bx, array pl, array lb) =>
if bx.size() > 0
for i = 0 to bx.size() - 1
bx.get(i).delete()
bx.clear()
if pl.size() > 0
for i = 0 to pl.size() - 1
pl.get(i).delete()
pl.clear()
if lb.size() > 0
for i = 0 to lb.size() - 1
lb.get(i).delete()
lb.clear()
// Builds a simple side face for 3D-style boxes using chart points.
method sideBox(array pts, int x, float btm, float top, float depthY, int widthX) =>
pts.unshift(chart.point.from_index(x, btm))
pts.unshift(chart.point.from_index(x + widthX, btm + depthY))
pts.unshift(chart.point.from_index(x + widthX, top + depthY))
pts.unshift(chart.point.from_index(x, top))
pts.unshift(chart.point.from_index(x, btm))
// Returns true if a candle's high/low intersects the OB zone.
touchesZone(float zTop, float zBot, float cHigh, float cLow) =>
cHigh >= zBot and cLow <= zTop
// Distance from price to zone in price units, used to rank nearest zones.
zoneDistance(float px, float zTop, float zBot) =>
px > zTop ? px - zTop : px < zBot ? zBot - px : 0.0
// Inserts a distance+index pair into a sorted list, capped at kMax.
method insertBest(array dists, array idxs, float dist, int idx, int kMax) =>
if dists.size() == 0
dists.push(dist)
idxs.push(idx)
else
int pos = dists.size()
if dists.size() > 0
for j = 0 to dists.size() - 1
if dist < dists.get(j)
pos := j
break
dists.insert(pos, dist)
idxs.insert(pos, idx)
while dists.size() > kMax
dists.pop()
idxs.pop()
// Picks the k nearest bull/bear OBs to current price (optionally including invalid).
pickNearest(array store, bool wantBull, int kMax, bool includeInvalid) =>
array dists = array.new_float()
array idxs = array.new_int()
if store.size() > 0
for i = 0 to store.size() - 1
ObRec ob = store.get(i)
if ob.isBull == wantBull
bool ok = includeInvalid ? true : ob.active
if ok
float dist = zoneDistance(close, ob.top, ob.bottom)
dists.insertBest(idxs, dist, i, kMax)
idxs
formatVol(float v) =>
str.tostring(v, format.volume)
//#endregion
//#region VOLUME ENGINE (CHART OR LOWER TF)
// Per-bar total / bull / bear volume
tfSec(string tf) =>
timeframe.in_seconds(tf)
int chartSec = tfSec(timeframe.period)
int srcSec = tfSec(vdTfIn)
bool useLtf = not na(chartSec) and not na(srcSec) and srcSec < chartSec
getBarVols() =>
float tot = na
float bull = na
float bear = na
if not useLtf or vdTfIn == ""
float v = volume
bool up = close > open
bool dn = close < open
tot := v
bull := up ? v : 0.0
bear := dn ? v : 0.0
else
array oArr = request.security_lower_tf(syminfo.tickerid, vdTfIn, open)
array cArr = request.security_lower_tf(syminfo.tickerid, vdTfIn, close)
array vArr = request.security_lower_tf(syminfo.tickerid, vdTfIn, volume)
float tSum = 0.0
float bSum = 0.0
float sSum = 0.0
int n = array.size(vArr)
if n > 0
for i = 0 to n - 1
float v2 = array.get(vArr, i)
float o2 = array.get(oArr, i)
float c2 = array.get(cArr, i)
tSum += v2
if c2 > o2
bSum += v2
else if c2 < o2
sSum += v2
tot := tSum
bull := bSum
bear := sSum
= getBarVols()
//#endregion
//#region POC ENGINE (MOST-TOUCHED PRICE + VOLUME)
// Finds a POC between swing and BOS, then aggregates volume.
findMostTouchedPrice(int fromIdx, int toIdx, int nBins) =>
int span = toIdx - fromIdx
if span <= 0 or na(fromIdx) or na(toIdx)
else
float minP = 1e10
float maxP = -1e10
for idx = fromIdx to toIdx
int rel = bar_index - idx
if rel >= 0
float lo = low
float hi = high
if not na(lo) and not na(hi)
if lo < minP
minP := lo
if hi > maxP
maxP := hi
if not (minP < maxP)
else
float step = (maxP - minP) / nBins
step := step <= 0 ? syminfo.mintick : step
array diffCnt = array.new_float(nBins, 0.0)
for idx = fromIdx to toIdx
int rel2 = bar_index - idx
if rel2 >= 0
float lo2 = low
float hi2 = high
if not na(lo2) and not na(hi2)
int sBin = int(math.floor((lo2 - minP) / step))
int eBin = int(math.floor((hi2 - minP) / step))
sBin := sBin < 0 ? 0 : sBin > nBins - 1 ? nBins - 1 : sBin
eBin := eBin < 0 ? 0 : eBin > nBins - 1 ? nBins - 1 : eBin
float cStart = diffCnt.get(sBin)
diffCnt.set(sBin, cStart + 1.0)
if eBin + 1 < nBins
float cEnd = diffCnt.get(eBin + 1)
diffCnt.set(eBin + 1, cEnd - 1.0)
int bestBin = 0
float bestCnt = 0.0
float runCnt = 0.0
for i = 0 to nBins - 1
runCnt += diffCnt.get(i)
if runCnt > bestCnt
bestCnt := runCnt
bestBin := i
float poc = minP + (bestBin + 0.5) * step
// Aggregates total / bull / bear volume at a single price level (POC) for a range.
volumeAtPrice(int fromIdx, int toIdx, float poc) =>
int touches = 0
float totVol = 0.0
float bullVol = 0.0
float bearVol = 0.0
int span = toIdx - fromIdx
if not na(poc) and span >= 0
for step = 0 to span
int idx = toIdx - step
int rel = bar_index - idx
if rel >= 0
float lo = low
float hi = high
if not na(lo) and not na(hi) and lo <= poc and hi >= poc
touches += 1
float vTot = barTotVol
float vBull = barBullVol
float vBear = barBearVol
if not na(vTot)
totVol += vTot
if not na(vBull)
bullVol += vBull
if not na(vBear)
bearVol += vBear
// Wrapper: find POC first, then compute volume at that POC for the BOS range.
calcMostTouchedPriceVol(int fromIdx, int toIdx, int nBins) =>
= findMostTouchedPrice(fromIdx, toIdx, nBins)
= volumeAtPrice(fromIdx, toIdx, poc)
//#endregion
//#region ORDER BLOCK ENGINE (POC-BASED)
// Detects swing highs/lows, confirms BOS, anchors OB at first POC touch.
var array obs = array.new()
var array obRetests = array.new()
var int lastBullRetestBar = na
var int lastBearRetestBar = na
var float shPrice = na
var int shIdx = na
var float slPrice = na
var int slIdx = na
bool evNewBullOB = false
bool evNewBearOB = false
bool evBullRetest = false
bool evBearRetest = false
float ph = ta.pivothigh(high, swingLen, swingLen)
float pl = ta.pivotlow(low, swingLen, swingLen)
if not na(ph)
shPrice := ph
shIdx := bar_index - swingLen
if not na(pl)
slPrice := pl
slIdx := bar_index - swingLen
bool bosBearNow = not na(slPrice) and bar_index > slIdx and close < slPrice and close >= slPrice
bool bosBullNow = not na(shPrice) and bar_index > shIdx and close > shPrice and close <= shPrice
bool bosBear = bosBearNow
bool bosBull = bosBullNow
// Precompute BOS ranges and POC stats in global scope
int bosIdxBear = bar_index - 1
int fromIdxBear = slIdx
int toIdxBear = bosIdxBear
= calcMostTouchedPriceVol(fromIdxBear, toIdxBear, 40)
int bosIdxBull = bar_index - 1
int fromIdxBull = shIdx
int toIdxBull = bosIdxBull
= calcMostTouchedPriceVol(fromIdxBull, toIdxBull, 40)
// Keeps OB array trimmed to recent history and limits max stored OBs.
pruneObs() =>
int minLeft = math.max(0, bar_index - 4999)
if obs.size() > 0
for i = obs.size() - 1 to 0
ObRec ob = obs.get(i)
if ob.leftIndex < minLeft
obs.remove(i)
while obs.size() > MAX_STORED_OBS
bool removed = false
if obs.size() > 0
for j = obs.size() - 1 to 0
ObRec ob2 = obs.get(j)
if not ob2.active
obs.remove(j)
removed := true
break
if not removed and obs.size() > 0
obs.pop()
// Creates and seeds an OB record using a POC-anchored candle and BOS volumes.
addObFromPoc(int baseIdx, float top, float bottom, bool isBull, float totSeed, float bullSeed, float bearSeed, int createdIdx) =>
int offLeft = bar_index - baseIdx
int offCreated = bar_index - createdIdx
int leftTime = time
int createdTm = time
float tot = totSeed
float bVol = bullSeed
float sVol = bearSeed
bool hasDelta = tot > 0.0
float bullPct = hasDelta ? math.round((bVol / tot) * 100.0) : 50.0
float bearPct = hasDelta ? 100.0 - bullPct : 50.0
obs.unshift(ObRec.new(baseIdx, leftTime, createdIdx, createdTm, top, bottom, isBull,
true, false, na, na, na, na, bVol, sVol, tot, bullPct, bearPct, hasDelta))
pruneObs()
// Returns true if a proposed zone overlaps any active OB
obOverlapsActive(float zoneTop, float zoneBottom) =>
float zTop = math.max(zoneTop, zoneBottom)
float zBot = math.min(zoneTop, zoneBottom)
bool overlaps = false
if obs.size() > 0
for i = 0 to obs.size() - 1
ObRec ob = obs.get(i)
if ob.active
float oTop = math.max(ob.top, ob.bottom)
float oBot = math.min(ob.top, ob.bottom)
bool rangeOverlap = zTop >= oBot and zBot <= oTop
if rangeOverlap
overlaps := true
break
overlaps
// Returns true if there is a price gap between anchorIdx and bosIdx.
hasGapBetween(int anchorIdx, int bosIdx, bool isBull) =>
bool gap = false
int fromIdx = math.min(anchorIdx, bosIdx)
int toIdx = math.max(anchorIdx, bosIdx)
if toIdx - fromIdx >= 1
for absIdx = fromIdx + 1 to toIdx
int relNow = bar_index - absIdx
int relPrev = relNow + 1
if relNow >= 0 and relPrev >= 0
float hiPrev = high
float loPrev = low
float hiNow = high
float loNow = low
if not na(hiPrev) and not na(loPrev) and not na(hiNow) and not na(loNow)
if isBull
if loNow > hiPrev
gap := true
break
else
if hiNow < loPrev
gap := true
break
gap
// Bearish BOS → Bearish OB
if bosBear
int bosIdx = bosIdxBear
int fromIdx = fromIdxBear
int toIdx = toIdxBear
if not na(pocB) and touchesB > 0 and not na(fromIdx) and not na(toIdx)
int spanB = toIdx - fromIdx
int bestIdx = na
float runMaxHigh = na
if spanB >= 0
for step = 0 to spanB
int idx = toIdx - step
int rel = bar_index - idx
if rel >= 0
float lo = low
float hi = high
if not na(lo) and not na(hi)
runMaxHigh := na(runMaxHigh) ? hi : math.max(runMaxHigh, hi)
bool touches = lo <= pocB and hi >= pocB
if touches and hi == runMaxHigh
bestIdx := idx
bool gapLeg = not na(bestIdx) ? hasGapBetween(bestIdx, bosIdx, false) : false
if not na(bestIdx) and not gapLeg
int relBest = bar_index - bestIdx
float top = high
float bottom = low
if not obOverlapsActive(top, bottom)
addObFromPoc(bestIdx, top, bottom, false, totVolB, bullVolB, bearVolB, bosIdx)
evNewBearOB := true
slPrice := na
slIdx := na
// Bullish BOS → Bullish OB
if bosBull
int bosIdx2 = bosIdxBull
int fromIdx2 = fromIdxBull
int toIdx2 = toIdxBull
if not na(pocH) and touchesH > 0 and not na(fromIdx2) and not na(toIdx2)
int spanH = toIdx2 - fromIdx2
int bestIdx2 = na
float runMinLow = na
if spanH >= 0
for step = 0 to spanH
int idx2 = toIdx2 - step
int rel2 = bar_index - idx2
if rel2 >= 0
float lo2 = low
float hi2 = high
if not na(lo2) and not na(hi2)
runMinLow := na(runMinLow) ? lo2 : math.min(runMinLow, lo2)
bool touches = lo2 <= pocH and hi2 >= pocH
if touches and lo2 == runMinLow
bestIdx2 := idx2
bool gapLeg2 = not na(bestIdx2) ? hasGapBetween(bestIdx2, bosIdx2, true) : false
if not na(bestIdx2) and not gapLeg2
int relBest2 = bar_index - bestIdx2
float top2 = high
float bottom2 = low
if not obOverlapsActive(top2, bottom2)
addObFromPoc(bestIdx2, top2, bottom2, true, totVolH, bullVolH, bearVolH, bosIdx2)
evNewBullOB := true
shPrice := na
shIdx := na
// Invalidation and retest detection for existing OBs.
if obs.size() > 0
for i = 0 to obs.size() - 1
ObRec ob = obs.get(i)
if ob.active
bool invalid = false
int invIdx = na
int invTime = na
if ob.isBull
if invMethod == "Wick"
invalid := low < ob.bottom
invIdx := bar_index
invTime := time
else
if bar_index > 0
invalid := close < ob.bottom
invIdx := bar_index - 1
invTime := time
else
if invMethod == "Wick"
invalid := high > ob.top
invIdx := bar_index
invTime := time
else
if bar_index > 0
invalid := close > ob.top
invIdx := bar_index - 1
invTime := time
if invalid
ob.active := false
ob.invalidIndex := invIdx
ob.invalidTime := invTime
bool retestPrev = false
int retestBar = na
int retestTm = na
if bar_index > 0
if ob.isBull
bool opensAbovePrev = open > ob.top
bool closesAbovePrev = close > ob.top
bool wickTouchesPrev = low <= ob.top and low >= ob.bottom
retestPrev := opensAbovePrev and closesAbovePrev and wickTouchesPrev
else
bool opensBelowPrev = open < ob.bottom
bool closesBelowPrev = close < ob.bottom
bool wickTouchesPrev = high >= ob.bottom and high <= ob.top
retestPrev := opensBelowPrev and closesBelowPrev and wickTouchesPrev
if retestPrev
retestBar := bar_index - 1
retestTm := time
if retestPrev and not na(retestBar) and retestBar > ob.createdIndex
ob.retested := true
ob.retestIndex := retestBar
ob.retestTime := retestTm
int lastSideBar = ob.isBull ? lastBullRetestBar : lastBearRetestBar
bool canLog = na(lastSideBar) or retestBar - lastSideBar >= 4
if canLog
obRetests.unshift(RetestRec.new(retestBar, ob.isBull, ob.leftIndex, ob.createdIndex))
if ob.isBull
evBullRetest := true
lastBullRetestBar := retestBar
else
evBearRetest := true
lastBearRetestBar := retestBar
obs.set(i, ob)
//#endregion
//#region DRAW ENGINE (ZONES + VOLUME + 3D)
// Handles all boxes, polylines and labels for OBs and 3D faces.
bool showVD = vdEnable
bool isVert = displayStyle == "Vertical"
bool isHorz = not isVert
float dayAtr = ta.atr(14)
var array allBoxes = array.new()
var array allPolys = array.new()
var array allLabels = array.new()
drawPoly(PolyParams pp) =>
if not na(pp) and not na(pp.points) and pp.points.size() > 0
allPolys.unshift(polyline.new(points = pp.points, line_color = pp.lineColor, fill_color = pp.fillColor))
method pushBox(array store, box b) =>
store.unshift(b)
method pushLabel(array store, label l) =>
store.unshift(l)
// Chooses base colors for OB zones depending on vdEnable and bull/bear type.
obColors(ObRec ob) =>
color bullCol = vdEnable ? vdBullColor : bullObColor
color bearCol = vdEnable ? vdBearColor : bearObColor
color baseCol = ob.isBull ? bullCol : bearCol
color faded = ob.active ? baseCol : color.new(baseCol, 85)
// Computes right-most bar index for drawing an OB, considering extension and invalidation.
obRightIndex(ObRec ob) =>
int activeRight = bar_index + extendZones
if ob.active
activeRight
else
na(ob.invalidIndex) ? activeRight : ob.invalidIndex
// Draws the main OB zone box on the chart.
drawObZoneBox(ObRec ob, color faded) =>
int xR = obRightIndex(ob)
int xL = ob.leftIndex
int minBar = bar_index - 4999
if xL < minBar
xL := minBar
xR := math.max(xR, xL)
box bx = box.new(left = xL, right = xR, top = ob.top, bottom = ob.bottom, xloc = xloc.bar_index, bgcolor = faded, border_color = na, border_width = 0)
allBoxes.pushBox(bx)
// Draws a retest marker (triangle) when price revisits an OB.
drawRetestLabels(array bullAct, array bearAct, array bullInv, array bearInv) =>
int ret = 0
if showRetestLbl and obRetests.size() > 0
int minBar = bar_index - 4999
int lastBullLbl = na
int lastBearLbl = na
for i = obRetests.size() - 1 to 0
RetestRec r = obRetests.get(i)
if r.barIndex < minBar or r.barIndex > bar_index
RetestRec _trash = obRetests.remove(i)
else
bool hasDisplayedParent = false
if r.isBull
if bullAct.size() > 0
for j = 0 to bullAct.size() - 1
ObRec ob = obs.get(bullAct.get(j))
if ob.leftIndex == r.obLeftIndex and ob.createdIndex == r.obCreatedIndex
hasDisplayedParent := true
break
if not hasDisplayedParent and not hideInvalid and bullInv.size() > 0
for j = 0 to bullInv.size() - 1
ObRec ob = obs.get(bullInv.get(j))
if ob.leftIndex == r.obLeftIndex and ob.createdIndex == r.obCreatedIndex
hasDisplayedParent := true
break
else
if bearAct.size() > 0
for j = 0 to bearAct.size() - 1
ObRec ob = obs.get(bearAct.get(j))
if ob.leftIndex == r.obLeftIndex and ob.createdIndex == r.obCreatedIndex
hasDisplayedParent := true
break
if not hasDisplayedParent and not hideInvalid and bearInv.size() > 0
for j = 0 to bearInv.size() - 1
ObRec ob = obs.get(bearInv.get(j))
if ob.leftIndex == r.obLeftIndex and ob.createdIndex == r.obCreatedIndex
hasDisplayedParent := true
break
if not hasDisplayedParent
continue
int age = bar_index - r.barIndex
if age >= 0 and age <= 4999
if r.isBull
if not na(lastBullLbl) and r.barIndex - lastBullLbl < 3
continue
lastBullLbl := r.barIndex
else
if not na(lastBearLbl) and r.barIndex - lastBearLbl < 3
continue
lastBearLbl := r.barIndex
float yPrice = close
color baseCol = r.isBull ? bullObColor : bearObColor
st = r.isBull ? label.style_triangleup : label.style_triangledown
yl = r.isBull ? yloc.belowbar : yloc.abovebar
label newLbl = label.new(r.barIndex, yPrice, "", xloc = xloc.bar_index, yloc = yl, style = st,
color = color.new(baseCol, 0), textcolor = color.new(baseCol, 0), size = retestSize, force_overlay = true)
allLabels.pushLabel(newLbl)
ret
// Returns geometry used for volume overlay and 3D top view.
obGeom(ObRec ob) =>
int rawL = ob.leftIndex
int rawR = obRightIndex(ob)
int minBar = bar_index - 4999
int xL = math.max(rawL, minBar)
int xR = math.max(rawR, xL)
int widthX = vd3DDepth
int xR2 = xR + widthX
float yT = ob.top
float yB = ob.bottom
float h = yT - yB
// Converts bull/bear percentages into display strings (if enabled).
deltaTexts(float bullPct, float bearPct) =>
string bullTxt = showDeltaPct ? str.tostring(bullPct) + "%" : ""
string bearTxt = showDeltaPct ? str.tostring(bearPct) + "%" : ""
// Draws a text label with total volume on the right-bottom corner of the OB.
drawTotalVolLabel(int xL, int xR, float yT, float yB, float h, float total) =>
if showTotalVol
int cx = xR - 1
if cx < xL
cx := xL
float cy = yB + h * 0.25
string txt = formatVol(total)
label lb = label.new(cx, cy, txt, xloc = xloc.bar_index, style = label.style_label_right,
textcolor = vdTextColor, color = #ffffff00, size = size.small, force_overlay = true)
allLabels.pushLabel(lb)
// Fills the OB with bull/bear split either vertically or horizontally.
drawDeltaFills(int xL, int xR, float yT, float yB, float h, float bullPct, string bullTxt, string bearTxt) =>
color bullCol = vdEnable ? vdBullColor : bullObColor
color bearCol = vdEnable ? vdBearColor : bearObColor
if isVert
int splitX = xL + int((xR - xL) * (bullPct / 100.0))
splitX := xR - xL >= 2 ? math.max(xL + 1, math.min(xR - 1, splitX)) : xL
box bBull = box.new(xL, yT, splitX, yB, xloc = xloc.bar_index, bgcolor = bullCol, border_width = 0, text = bullTxt, text_color = vdTextColor, text_size = size.small)
box bBear = box.new(splitX, yT, xR, yB, xloc = xloc.bar_index, bgcolor = bearCol, border_width = 0, text = bearTxt, text_color = vdTextColor, text_size = size.small)
allBoxes.pushBox(bBull)
allBoxes.pushBox(bBear)
else
float midY = yB + h * (bullPct / 100.0)
box bBull = box.new(xL, midY, xR, yB, xloc = xloc.bar_index, bgcolor = bullCol, border_width = 0, text = bullTxt, text_color = vdTextColor, text_size = size.small)
box bBear = box.new(xL, yT, xR, midY, xloc = xloc.bar_index, bgcolor = bearCol, border_width = 0, text = bearTxt, text_color = vdTextColor, text_size = size.small)
allBoxes.pushBox(bBull)
allBoxes.pushBox(bBear)
// Track first visible bar index for 3D top face clipping.
var int leftVisIdx = na
if na(leftVisIdx) and time >= chart.left_visible_bar_time
leftVisIdx := bar_index
// Draws the 3D front faces and top faces based on bull/bear split and style.
drawDelta3D(int xL, int xR, int widthX, int xR2, float yT, float yB, float h, float bullPct) =>
color bullCol = vdEnable ? vdBullColor : bullObColor
color bearCol = vdEnable ? vdBearColor : bearObColor
float depthY = dayAtr * (0.1 * vd3DDepth)
int visibleLeft = na(leftVisIdx) ? xL : math.max(xL, leftVisIdx)
int visibleRight = xR
if isHorz
float midY = yB + h * (bullPct / 100.0)
if bullPct > 0
array ptsFrontBull = array.new()
ptsFrontBull.sideBox(xR, yB, midY, depthY, widthX)
drawPoly(PolyParams.new(ptsFrontBull, color.new(chart.fg_color, 90), color.new(bullCol, 70), 1))
if bullPct < 100
array ptsFrontBear = array.new()
ptsFrontBear.sideBox(xR, midY, yT, depthY, widthX)
drawPoly(PolyParams.new(ptsFrontBear, color.new(chart.fg_color, 90), color.new(bearCol, 70), 1))
if visibleRight > visibleLeft
array ptsTop = array.new()
ptsTop.unshift(chart.point.from_index(visibleRight + widthX, yT + depthY))
ptsTop.unshift(chart.point.from_index(visibleLeft + widthX, yT + depthY))
ptsTop.unshift(chart.point.from_index(visibleLeft, yT))
ptsTop.unshift(chart.point.from_index(visibleRight, yT))
ptsTop.unshift(chart.point.from_index(visibleRight + widthX, yT + depthY))
drawPoly(PolyParams.new(ptsTop, color.new(chart.fg_color, 90), color.new(bearCol, 70), 1))
else
array ptsFront = array.new()
ptsFront.sideBox(xR, yB, yT, depthY, widthX)
drawPoly(PolyParams.new(ptsFront, color.new(chart.fg_color, 90), color.new(bearCol, 70), 1))
if visibleRight > visibleLeft
float frac = bullPct / 100.0
int bullRight = visibleLeft + int((visibleRight - visibleLeft) * frac)
bullRight := math.max(visibleLeft, math.min(visibleRight, bullRight))
if bullPct > 0 and bullRight > visibleLeft
array ptsTopBull = array.new()
ptsTopBull.unshift(chart.point.from_index(bullRight + widthX, yT + depthY))
ptsTopBull.unshift(chart.point.from_index(visibleLeft + widthX, yT + depthY))
ptsTopBull.unshift(chart.point.from_index(visibleLeft, yT))
ptsTopBull.unshift(chart.point.from_index(bullRight, yT))
ptsTopBull.unshift(chart.point.from_index(bullRight + widthX, yT + depthY))
drawPoly(PolyParams.new(ptsTopBull, color.new(chart.fg_color, 90), color.new(bullCol, 70), 1))
if bullPct < 100 and visibleRight > bullRight
array ptsTopBear = array.new()
ptsTopBear.unshift(chart.point.from_index(visibleRight + widthX, yT + depthY))
ptsTopBear.unshift(chart.point.from_index(bullRight + widthX, yT + depthY))
ptsTopBear.unshift(chart.point.from_index(bullRight, yT))
ptsTopBear.unshift(chart.point.from_index(visibleRight, yT))
ptsTopBear.unshift(chart.point.from_index(visibleRight + widthX, yT + depthY))
drawPoly(PolyParams.new(ptsTopBear, color.new(chart.fg_color, 90), color.new(bearCol, 70), 1))
// Draws a full OB: zone, retest label, volume fill and 3D faces.
drawZoneAndVolume(ObRec ob) =>
= obColors(ob)
drawObZoneBox(ob, faded)
if showVD and ob.hasDelta
= obGeom(ob)
= deltaTexts(ob.bullPct, ob.bearPct)
drawTotalVolLabel(xL, xR, yT, yB, h, ob.totalVol)
drawDeltaFills(xL, xR, yT, yB, h, ob.bullPct, bullTxt, bearTxt)
if vd3D
drawDelta3D(xL, xR, widthX, xR2, yT, yB, h, ob.bullPct)
true
// Clear all previous drawings each bar before re-rendering current selection.
allBoxes.clearAll(allPolys, allLabels)
// Pick active and invalid OBs based on hideInvalid + showNearestX.
array bullActive = array.new_int()
array bearActive = array.new_int()
array bullInvalid = array.new_int()
array bearInvalid = array.new_int()
if hideInvalid
bullActive := pickNearest(obs, true, showNearestX, false)
bearActive := pickNearest(obs, false, showNearestX, false)
else
bullActive := pickNearest(obs, true, showNearestX, false)
bearActive := pickNearest(obs, false, showNearestX, false)
if obs.size() > 0
for i = 0 to obs.size() - 1
ObRec o = obs.get(i)
if not o.active
if o.isBull
bullInvalid.push(i)
else
bearInvalid.push(i)
if bearInvalid.size() > 0 and not hideInvalid
for i = 0 to bearInvalid.size() - 1
ObRec ob = obs.get(bearInvalid.get(i))
drawZoneAndVolume(ob)
if bearActive.size() > 0
for i = 0 to bearActive.size() - 1
ObRec ob = obs.get(bearActive.get(i))
drawZoneAndVolume(ob)
if bullInvalid.size() > 0 and not hideInvalid
for i = 0 to bullInvalid.size() - 1
ObRec ob = obs.get(bullInvalid.get(i))
drawZoneAndVolume(ob)
if bullActive.size() > 0
for i = 0 to bullActive.size() - 1
ObRec ob = obs.get(bullActive.get(i))
drawZoneAndVolume(ob)
// Draw all stored retest events on top of zones
drawRetestLabels(bullActive, bearActive, bullInvalid, bearInvalid)
//#endregion
//#region ALERTS
alertcondition(alBullOB and evNewBullOB, "Bullish Order Block", "New Bullish Order Block detected.")
alertcondition(alBearOB and evNewBearOB, "Bearish Order Block", "Bearish Order Block detected.")
alertcondition(alBullRetest and evBullRetest, "Bullish OB Retest", "Bullish Order Block retest.")
alertcondition(alBearRetest and evBearRetest, "Bearish OB Retest", "Bearish Order Block retest.")
if alBullOB and evNewBullOB
alert("Bullish Order Block detected.", alert.freq_once_per_bar)
if alBearOB and evNewBearOB
alert("Bearish Order Block detected.", alert.freq_once_per_bar)
if alBullRetest and evBullRetest
alert("Bullish Order Block retest.", alert.freq_once_per_bar)
if alBearRetest and evBearRetest
alert("Bearish Order Block retest.", alert.freq_once_per_bar)
// ==========================================================================================
// === Dashboard with Telegram Link ===
var table myTable = table.new(position.top_center, 1, 1, border_width=1, frame_color=color.black, bgcolor=color.white)
// Add Telegram Message to Dashboard
table.cell(myTable, 0, 0, "Join Telegram @STRATEGY INDIBOT", bgcolor=color.blue, text_color=color.white, text_size=size.normal)
Advanced Market Structure [Rogman]Rogman's Advanced Market Structure Indicator
The Ultimate All-in-One Market Structure Analysis Tool for TradingView
Take your technical analysis to the next level with a comprehensive, professional-grade tool designed for traders who demand precision and clarity in their charts.
🎯 Who Is This For?
ICT/SMC Traders seeking liquidity zones and market structure analysis
Day Traders monitoring session-based price action and kill zones
Swing Traders identifying key higher timeframe levels
Price Action Traders analyzing structure breaks and trend changes
Any Serious Trader wanting a clean, comprehensive market structure overlay
✨ Key Features
📊 Market Sessions Visualization
Track the three major trading sessions with our unique bracket-style display:
Asia, London, and New York sessions are clearly marked
Sessions display as SESSION ════════════ below price action
Smart vertical stacking prevents overlapping when sessions have similar lows
Fully customizable session times for any timezone
Perfect for identifying session highs/lows and optimal kill zone timing
📈 Higher Timeframe (HTF) Levels
Never miss a key level again:
Display Daily and Weekly Open, High, and Low levels
Instant visual reference for HTF support and resistance
Separate color controls for lines and labels
Choose from Solid, Dashed, or Dotted line styles
Essential for determining HTF bias and key decision points
🔄 Automatic Swing Detection
Let the indicator do the heavy lifting:
Auto-detection of swing highs (▼) and swing lows (▲)
Configurable lookback period for sensitivity adjustment
Optional horizontal level lines extending from swing points
Customizable colors, widths, and line styles
Identify potential reversal points and structure levels instantly
💧 Liquidity Zone Mapping
See where the money is hiding:
Automatic identification of buy-side liquidity (above swing highs)
Automatic identification of sell-side liquidity (below swing lows)
Visual zones show where stop losses are clustered
Real-time tracking when liquidity gets swept
Swept zones change color — know when liquidity has been taken
📉 Multi-Method Trend Detection
Three powerful methods to confirm trend direction:
Swing Structure — Based on higher highs/lows or lower highs/lows
EMA — Trend based on price position relative to EMA
Supertrend — Uses the popular Supertrend indicator
Features include:
Optional background coloring for at-a-glance trend identification
Real-time trend status label (UPTREND/DOWNTREND/NEUTRAL)
Customizable colors and transparency
🏷️ HH/HL/LH/LL Labels
Automatic market structure labeling:
HH (Higher High) — Bullish continuation signal
HL (Higher Low) — Bullish continuation signal
LH (Lower High) — Bearish continuation signal
LL (Lower Low) — Bearish continuation signal
Color-coded for instant visual recognition
📋 Information Dashboard
All critical data at a glance:
Current ticker symbol
Trend direction and status
Daily and Weekly bias
Last swing high and low prices
Active liquidity zone count
Positionable in any corner of your chart
🔔 Built-in Alerts
Never miss a key event:
Trend change alerts (Bullish/Bearish)
Swing high/low formation alerts
Set up notifications for critical market structure changes
🎨 Fully Customizable
Every feature can be:
Toggled on/off individually via the Feature Toggles menu
Color customized to match your chart theme
Size adjusted for optimal visibility
Fine-tuned with sensitivity parameters
Organized settings groups make configuration intuitive and fast.
🚀 Why Choose This Indicator?
Feature: Benefit: All-in-One Solution. Replace multiple indicators with one comprehensive tool. Clean Design and Thoughtful visual hierarchy keep charts readable. Smart Overlap Prevention. Session bars automatically stack to avoid visual clutter. Real-Time Updates: All elements update dynamically as the price moves. Professional Quality-Built with best practices in Pine Script v6. Extensive Documentation, clear code comments, and an organized structure
📖 How to Use
Add the indicator to your TradingView chart
Enable/disable features using the Feature Toggles menu
Customize colors and settings to match your preferences
Adjust session times for your timezone
Set up alerts for trend changes and swing formations
Pro Tips:
Use session times to identify optimal entry windows during kill zones
Watch for price sweeping liquidity zones before looking for reversals
Combine HTF bias with lower timeframe entries for higher probability trades
Use swing levels as potential support/resistance for entries and targets
Monitor the dashboard for a quick market assessment before trading
⚠️ Disclaimer
This indicator is provided for educational and informational purposes only. It does not constitute financial advice. Trading involves substantial risk and is not suitable for all investors. Past performance is not indicative of future results. Always conduct your own analysis and consider your financial situation before making trading decisions.
Session Highs & LowsCustom Highs & Lows
This indicator displays Previous Day High & Low along with session Highs & Lows for the Asian, London, and New York sessions.
Each session can be configured individually, allowing you to show or hide Highs, Lows, or both.
Basic customization options are included, such as:
level colors
line thickness
line extension length
transparency
line style
The main feature of this indicator is sweep detection.
For example, when the London session sweeps the Asian High or Low, the level automatically changes:
from a solid line to a dotted or dashed line
with reduced opacity
This makes it easy to see that the level has already been swept, while keeping the chart clean and uncluttered when looking for further confluences.
The indicator also supports alerts for all session Highs and Lows when they are swept, so you can receive notifications without constantly watching the chart.
Use it, test it, and if you have a solid idea for improvement, feel free to reach out. A lot of time went into building this indicator, and meaningful enhancements can always be discussed.
High Volume S/R + VPA Entries + Broken Level Cleanup High Volume S/R + VPA Entries + Broken Level Cleanup
[codapro] Elite Momentum & Smart Money Detector
Elite Momentum & Smart Money Detector
Overview
The Elite Detector is a non-repainting indicator that merges Smart Money Concepts, Adaptive Volatility-Based Momentum, and Multi-Timeframe Trend Confluence to identify high-probability trade setups. This tool helps confirm institutional intent and market pressure before triggering actionable signals.
Core Systems
Smart Money Concepts (SMC)
• Highlights institutional order blocks
• Detects equal highs/lows as liquidity zones
• Automatically cleans up outdated zones for clarity
Adaptive Momentum Engine
• Momentum calculated with volatility-adjusted smoothing
• Normalized scale from -100 to +100
• Candle coloring reflects trend strength dynamically
Squeeze Detection System
• Flags volatility contraction zones using Bollinger and Keltner channels
• Background shading highlights compression zones
• Histogram shows directional breakout pressure
Multi-Timeframe Trend Validation
• Aligns signals with higher timeframe momentum
• Built-in logic auto-selects appropriate HTF per chart
• Reduces false signals and improves timing
Signal Logic
Buy Signal appears when:
Momentum crosses from negative to positive
Squeeze condition is active
Higher timeframe confirms bullish trend
Sell Signal appears when:
Momentum crosses from positive to negative
Squeeze condition is active
Higher timeframe confirms bearish trend
All signals are non-repainting and appear only once all conditions are met.
Visual Dashboard (Top-Right Corner)
Displays real-time confirmation across five categories:
Momentum: Current trend direction and strength
Squeeze: Indicates if volatility is compressed
HTF Trend: Confirms higher-timeframe alignment
Volatility: Current volatility phase (low, normal, or high)
Signal Status: Buy, Sell, or Neutral (Wait)
Chart Visuals
Candle Colors:
• Bright green/red = Strong momentum
• Faded green/red = Weak momentum
Background Colors:
• Orange = Squeeze is active
• Clear = Normal market activity
Boxes:
• Green = Bullish order blocks
• Red = Bearish order blocks
Dashed Lines:
• Red = Equal highs (liquidity zones above)
• Green = Equal lows (liquidity zones below)
Alert Conditions
Includes three prebuilt alerts for automation and webhook systems:
Elite Buy Signal
Elite Sell Signal
Squeeze Activation
These alerts allow users to respond to market shifts in real time or integrate with automated trading workflows.
Best Practices
Wait for Confluence: Confirm all three systems (momentum, squeeze, HTF trend) before entering
Watch Order Blocks: Institutional zones often act as support/resistance
Monitor Liquidity Zones: Be cautious of stop hunts near equal highs/lows
Use Dashboard Cues: Let the HUD validate your setup
Always Use Risk Management: This tool increases probability, not certainty
Example Setup:
1. Squeeze background appears
2. Buy signal triangle confirms
3. Dashboard shows: Momentum strong up, Squeeze on, HTF trend up
4. Price bounces off green order block
→ High-probability long entry
Why It Works
This tool leverages multiple uncorrelated concepts to filter low-quality trades and highlight setups with real institutional backing:
Order Blocks and Liquidity Zones track smart money footprints
Volatility-adjusted Momentum captures real energy shifts
Multi-Timeframe Confluence confirms trades in the broader context
Non-repainting signals ensure reliability
Final Note
The Elite Detector is designed to show you:
Where smart money is positioned,
When the market is coiling for a move,
and Which direction is supported by momentum and trend.
Use it as your high-probability entry engine — across any market or timeframe.
Disclaimer
This tool was created using the CodaPro Pine Script architecture engine — designed to produce robust trading overlays, educational visuals, and automation-ready alerts. It is provided strictly for educational purposes and does not constitute financial advice. Always backtest and demo before applying to real capital.
SuperTrend - With Exits & Trade ZonesSuperTrend - With Exits & Trade Zones
Overview
An advanced trend-following indicator that combines pivot points with the SuperTrend methodology to create a complete trading system with entry signals, exit signals, and visual trade zones. This indicator adapts to market structure rather than just price action, providing more reliable trend identification.
What Makes This Unique
Unlike standard SuperTrend indicators that use moving averages, this version:
Uses actual pivot points to calculate a dynamic center line
Provides multiple entry mode options for different trading styles
Shows clear exit signals (both trailing stop and take profit)
Color-codes the entire chart into trade zones (Long, Short, No Trade)
Eliminates guesswork about when to enter, exit, and stay out
Features
📊 Core Indicator Components
Pivot Point Detection: Identifies local highs and lows in price structure
Dynamic Center Line: Weighted calculation using detected pivot points
ATR-Based Bands: Volatility-adjusted upper and lower bands
Trailing Stop Line: Adaptive stop-loss that follows the trend
🎯 Entry Signals
Four entry modes to match your trading style:
Immediate Mode ⚡
Signals right when the trailing stop breaks
Fastest entries for aggressive traders
Best for strong trending markets
Aggressive Mode 🔥 (Recommended)
Signals when price closes beyond break candle OR opens beyond it
Balanced speed and confirmation
Good for most market conditions
Balanced Mode ⚖️
Requires entire candle to close beyond break level
Moderate confirmation
Reduces false breakouts
Conservative Mode 🛡️
Waits for candle to open AND stay completely beyond break level
Highest confirmation, slowest entries
Best for choppy markets
🚪 Exit Signals
Three exit strategies:
Trailing Stop
Exits when price crosses back through the trailing stop line
Lets profits run in trending markets
Protects gains when trend weakens
Take Profit %
Exits at predetermined profit target
Locks in gains at specific percentage
Good for range-bound markets
Both
Uses whichever exit comes first
Combines profit protection with trend following
Recommended for most traders
🎨 Visual Trade Zones
Color-coded backgrounds eliminate confusion:
🟢 Light Green: Active LONG position
🔴 Light Red: Active SHORT position
⚫ Gray: NO TRADE ZONE (between exit and next signal)
📍 Additional Visual Elements
Diamond markers: Show when trailing stop is first broken
BUY/SELL labels: Clear entry signals in green/red
EXIT markers: Gray X for stop loss, Orange X (TP) for take profit
Pivot points: Optional display of detected highs/lows (H/L markers)
Support/Resistance: Optional circles at pivot levels
Settings & Parameters
Basic Settings
Pivot Point Period (default: 2)
Controls sensitivity of pivot detection
Lower = more pivots detected (more responsive)
Higher = fewer pivots (more stable)
ATR Factor (default: 3)
Distance multiplier for trailing stop bands
Lower = tighter stops (more signals, earlier exits)
Higher = wider stops (fewer signals, longer trades)
ATR Period (default: 10)
Lookback period for volatility calculation
Affects how quickly bands adapt to volatility changes
Entry Configuration
Entry Mode: Select from Immediate/Aggressive/Balanced/Conservative
Determines how quickly the indicator generates signals after a trend break
Exit Configuration
Exit Method: Choose Trailing Stop, Take Profit %, or Both
Take Profit % (default: 2%)
Set your profit target as percentage of entry price
Adjust based on volatility and timeframe
Display Options
Show Buy/Sell Labels: Toggle entry signal labels
Show Exit Signals: Toggle exit markers
Show Break Candles: Toggle diamond markers on trend breaks
Show Pivot Points: Display H/L markers at pivot points
Show PP Center Line: Display the dynamic center line
Show Support/Resistance: Display circles at S/R levels
How to Use
For Swing Traders
Set Entry Mode to "Balanced" or "Conservative"
Use "Both" exit method with 3-5% take profit
Enable all visual elements for complete market picture
Trade only in direction of colored zones
For Day Traders
Set Entry Mode to "Aggressive" or "Immediate"
Use "Trailing Stop" exit method to catch intraday trends
Lower ATR Factor to 2-2.5 for tighter stops
Watch for quick signals in the first 2 hours of trading
For Position Traders
Use higher timeframes (Daily/Weekly)
Set Entry Mode to "Conservative"
Increase Take Profit % to 5-10%
Use larger ATR Factor (4-5) for wider stops
General Trading Rules
✅ DO: Enter on BUY/SELL signals (green/red backgrounds)
✅ DO: Exit on EXIT/TP markers
❌ DON'T: Enter during gray NO TRADE ZONE
❌ DON'T: Counter-trend trade against the colored zone
Alerts
Set up the following alerts for automated trading notifications:
Buy Signal: Triggers when long entry conditions are met
Sell Signal: Triggers when short entry conditions are met
Exit Long: Triggers when long position should be closed
Exit Short: Triggers when short position should be closed
Trailing Stop Broken: Triggers on initial trend change
Best Practices
Timeframe Selection
1-5 min: Scalping (use Immediate/Aggressive mode)
15-60 min: Day trading (use Aggressive/Balanced mode)
4H-Daily: Swing trading (use Balanced/Conservative mode)
Weekly: Position trading (use Conservative mode)
Risk Management
Always use the EXIT signals - don't hold through gray zones
Position size based on distance to trailing stop
Never risk more than 1-2% per trade
Consider wider stops on higher timeframes
Market Conditions
Trending markets: Use Aggressive mode, Trailing Stop exits
Ranging markets: Use Conservative mode, Take Profit exits
High volatility: Increase ATR Factor, use Both exits
Low volatility: Decrease ATR Factor for tighter stops
Technical Details
Calculation Method
Detect pivot highs and lows using specified period
Calculate weighted center line: (previous_center × 2 + new_pivot) / 3
Calculate bands: Upper = Center - (ATR Factor × ATR), Lower = Center + (ATR Factor × ATR)
Determine trend based on price position relative to bands
Trail stop line follows the active trend direction
Signal Logic
Entry signals generated based on selected confirmation mode
Position tracking maintains state from entry to exit
Exit signals calculated from both trailing stop and take profit levels
Trade zones update in real-time based on position state
Limitations & Considerations
Works best in trending markets; may generate false signals in tight ranges
Not a holy grail - should be used with proper risk management
Past performance does not guarantee future results
Recommended to backtest on your specific instrument and timeframe
Consider combining with volume analysis or other indicators for confirmation
Version History
v1.0: Initial release with entry signals and confirmation modes
v1.1: Added exit signals (trailing stop and take profit)
v1.2: Added color-coded trade zones (Long/Short/No Trade)
Credits
Original Pivot Point SuperTrend concept by LonesomeTheBlue
Modified with exit signals and trade zone visualization
License
Mozilla Public License 2.0
Example Setups
Conservative Swing Trading
Pivot Point Period: 2
ATR Factor: 3
ATR Period: 10
Entry Mode: Conservative
Exit Method: Both
Take Profit %: 4%
Aggressive Day Trading
Pivot Point Period: 2
ATR Factor: 2.5
ATR Period: 10
Entry Mode: Aggressive
Exit Method: Trailing Stop
Position Trading
Pivot Point Period: 3
ATR Factor: 4
ATR Period: 14
Entry Mode: Balanced
Exit Method: Both
Take Profit %: 8%
Disclaimer: This indicator is for educational purposes only. Trading involves substantial risk. Always do your own research and never trade with money you cannot afford to lose.
Smart Fear & Greed Index [MarkitTick]💡 This comprehensive technical tool is designed to quantify market sentiment on an asset-specific basis, translating complex price action into a singular, normalized gauge of "Fear" and "Greed." While traditional Fear & Greed indices rely on macro-economic data (like put/call ratios or junk bond demand) generally applied to the broad S&P 500, this script calculates a localized index for the specific chart you are viewing. It synthesizes Momentum, Volatility, Volume, and Price Positioning into a bounded 0-100 oscillator, aiming to identify psychological extremes where market reversals are statistically more likely to occur.
✨ Originality and Utility
● Asset-Specific Sentiment Analysis
Most sentiment tools are external to the chart (e.g., news sentiment or broad market indices). The Smart Fear & Greed Index is unique because it internalizes this logic, creating a bespoke psychological profile for any ticker—whether it is Crypto, Forex, or Stocks. It allows traders to see if *this specific asset* is overheated (Greed) or oversold (Fear) relative to its own recent history.
● The "Buy the Fear, Sell the Greed" Logic
The script employs a contrarian color-coding philosophy aligned with the famous investment adage: "Be fearful when others are greedy, and greedy when others are fearful."
When the indicator shows Fear (Low values), it colors the zone Green, signaling a potential buying opportunity (discount).
When the indicator shows Greed (High values), it colors the zone Red, signaling potential downside risk (premium).
● Integrated Divergence Detection
Unlike standard oscillators that leave interpretation entirely to the user, this tool includes an automated divergence engine. It detects discrepancies between the sentiment index and price action, plotting lines and labels to highlight potential exhaustion points before they become obvious on the price chart.
🔬 Methodology and Concepts
The calculation is driven by a custom User-Defined Type (UDT) called QuantEngine , which aggregates four distinct technical "pillars" to form the final Composite Index.
• Pillar 1: Momentum (RSI)
The engine utilizes the Relative Strength Index to measure the velocity and magnitude of directional price movements. High momentum contributes to the "Greed" score, while collapsing momentum contributes to "Fear."
• Pillar 2: Volatility (Inverted Normalized ATR)
This component interprets volatility through a psychological lens.
Low Volatility is interpreted as complacency or "Greed" (steady uptrends often have low vol).
High Volatility is interpreted as "Fear" (panic selling and erratic ranges often spike volatility).
The script normalizes the Average True Range (ATR) and inverts it so that stability adds to the score, and instability subtracts from it.
• Pillar 3: Volume Strength
Volume is analyzed relative to its moving average. However, raw volume isn't enough; the engine applies directional logic.
High relative volume on an Up-Close adds to the Greed score.
High relative volume on a Down-Close subtracts, adding to the Fear score.
• Pillar 4: Price Position (Stochastic)
This calculates where the current close sits relative to the recent High-Low range. Closing near the highs indicates confidence (Greed), while closing near the lows indicates pessimism (Fear).
• The Composite & Smoothing
These four metrics are averaged to create a raw composite, which is then smoothed via an Exponential Moving Average (EMA) to filter out noise and produce the final, readable "Smart Fear & Greed" line.
🎨 Visual Guide
● The Oscillator Line
This is the primary fluctuating line that moves between 0 and 100.
Values > 50 suggest positive sentiment.
Values < 50 suggest negative sentiment.
● Color-Coded Zones
The plot changes color dynamically to reflect the psychological state:
Red (70-100): Extreme Greed. The market may be irrationally exuberant.
Orange (60-70): Greed. Strong bullish conviction.
Yellow (40-60): Neutral. Indecisive or transitionary market.
Light Green (30-40): Fear. Sentiment is turning bearish.
Bright Green (0-30): Extreme Fear. Panic selling, often a precursor to a value bounce.
● Background Highlights
A semi-transparent Red Background appears when the index breaches 75, warning of a potential "Top."
A semi-transparent Green Background appears when the index drops below 25, highlighting a potential "Bottom."
● Divergence Elements
Red Lines/Labels ("Bear"): Bearish Divergence. Price makes a Higher High, but the Index makes a Lower High. This suggests momentum is waning despite rising prices.
Green Lines/Labels ("Bull"): Bullish Divergence. Price makes a Lower Low, but the Index makes a Higher Low. This suggests selling pressure is drying up.
📖 How to Use
• Identifying Reversals
Wait for the oscillator to enter "Extreme" zones. Do not trade immediately upon entry; wait for the line to exit the extreme zone to confirm the reversal. For example, if the line hits 80 (Red) and then crosses back down below 70, it signals that Greed is fading.
• Trend Continuation
In a strong trend, the indicator may hover in the Greed (Orange) or Fear (Light Green) zones for extended periods. In these cases, use the Neutral (Yellow) zone crosses as re-entry signals in the direction of the trend.
• Divergence Confirmation
Use the automated divergence lines as high-conviction triggers. If the background turns Green (Extreme Fear) AND a Bullish Divergence label appears, it provides a stronger technical case for a long position than the zone alone.
⚙️ Inputs and Settings
● Calculation Settings
Global Lookback Period (Default: 21): The core lookback window for RSI, ATR, Volume, and Stochastic calculations. Increasing this makes the index slower and less reactive; decreasing it makes it faster.
Smoothing Length (Default: 5): Determines how smooth the final line is. Higher numbers reduce "whipsaws" but add lag.
Color Main Chart Candles : Colors the chart bars based on Fear/Greed sentiment.
● Divergence Settings
Divergence Lookback (Default: 5): Determines the pivot strength required to register a high or low for divergence checks.
Show Divergence Lines/Labels: Toggles to hide visual clutter if you only want to see the oscillator.
🔍 Deconstruction of the Underlying Scientific and Academic Framework
● Normalization Theory
The core scientific principle here is Min-Max Normalization. The script takes heterogeneous data types—Price (Dollars/Cents), Volume (Shares/Contracts), and Volatility (Points)—and standardizes them into a unit-less distribution between 0 and 100. This allows for the summation of disparate market forces into a single vector.
● Mean Reversion and Oscillator Bounds
The indicator relies on the statistical concept of Mean Reversion. Markets, like elastic bands, can only stretch so far from their average valuation (represented by the 50 line) before snapping back. The "Extreme" zones (Upper and Lower deciles) represent areas of statistical improbability where the likelihood of a continuation decreases and the likelihood of a reversion increases.
● Divergence and Momentum Theory
The divergence logic is grounded in the principle that momentum precedes price. Mathematically, price is the integral of velocity. When the derivative (momentum/sentiment) approaches zero or reverses while the function (price) continues, it signals a non-sustainable anomaly in the data series, often resolved by a price correction.
⚠️ Disclaimer
All provided scripts and indicators are strictly for educational exploration and must not be interpreted as financial advice or a recommendation to execute trades. I expressly disclaim all liability for any financial losses or damages that may result, directly or indirectly, from the reliance on or application of these tools. Market participation carries inherent risk where past performance never guarantees future returns, leaving all investment decisions and due diligence solely at your own discretion.
Anchored LRL using ZigZag AnchorAnchored Linear Regression Channel - ZigZag Pivot
The Anchored Linear Regression Channel (LRL) dynamically anchors to the most recent ZigZag pivot point, providing traders with a regression-based channel that resets with each significant price swing.
HOW IT WORKS:
This indicator combines ZigZag pivot detection with linear regression analysis. When price reverses by a specified ATR multiple, a new pivot is identified. After a minimum number of bars, the linear regression channel anchors to this pivot and projects forward to the current bar, recalculating with each new bar.
KEY FEATURES:
- Dynamic anchoring to ZigZag highs and lows
- Customizable ATR-based reversal detection
- Two standard deviation channel bands (inner and outer)
- Adjustable minimum bars before anchor reset (ideal for scalping on lower timeframes)
- Separate controls for ZigZag smoothing vs. anchor reset timing
- Color-coded regression line (up/down trend)
- Optional line extension to the right
- Fully customizable colors and line widths
- Visual label marking the anchor pivot point
INPUTS:
- ATR Reversal: Multiplier for ATR-based pivot detection (default: 2.0)
- MA Length: EMA smoothing for ZigZag calculation (default: 5)
- ATR Length: Period for ATR calculation (default: 5)
- Min Bars After Pivot: Bars required before anchor resets (default: 3, reduce to 1-2 for faster scalping)
- Channel Widths: Inner (0.70) and Outer (1.00) standard deviation multiples
- Line Colors: Customizable colors for uptrend/downtrend and channel lines
- Label Colors: Customizable background and text colors
HOW TO USE:
1. Apply the indicator to your chart
2. Adjust "Min Bars After Pivot" based on your timeframe:
- 1-minute charts: Use 1-2 bars for quick scalping entries
- 5-minute+ charts: Use 3-5 bars for more confirmation
3. Watch for the regression line color to indicate trend direction
4. Use channel bands as potential support/resistance zones
5. The label shows which pivot (high/low) the channel is anchored to
BEST PRACTICES:
- Lower timeframes (1-5 min): Use lower "Min Bars After Pivot" (1-3) for faster reaction
- Higher timeframes: Use higher values (5+) for more confirmed pivots
- Combine with price action and volume for confirmation
- Adjust ATR Reversal based on instrument volatility
NOTES:
- This indicator repaints as it recalculates with each new bar
- Channel resets when a new ZigZag pivot is confirmed
- Not suitable for backtesting strategies due to dynamic nature
- Works best on liquid instruments with clear price swings
DISCLAIMER:
This indicator is for educational and informational purposes only. It does not provide trading signals or guarantees of profitability. Past performance is not indicative of future results. Always perform your own analysis and risk management.






















