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.
Indicadores y estrategias
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
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.
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.
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.
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.
ApEn Zones with Delta Confirmation MTF [PhenLabs]📊 ApEn Zones with Delta Confirmation MTF
Version: PineScript™ v6
📌 Description
The ApEn Zones with Delta Confirmation MTF indicator combines Approximate Entropy analysis with cumulative volume delta to identify high-probability support and resistance zones. Approximate Entropy (ApEn) measures the complexity and unpredictability in price data—when ApEn drops significantly, it signals a transition from chaotic to ordered market behavior, often preceding reversals or continuations.
This indicator goes beyond simple ApEn detection by integrating Delta confirmation, which validates zones using volume-based order flow analysis. When a zone forms with Delta confirmation, it indicates institutional participation aligning with the price structure. The multi-timeframe capability allows traders to detect zones forming on higher timeframes while executing on their preferred chart.
🚀 Points of Innovation
First indicator to combine ApEn complexity analysis with cumulative Delta confirmation for zone validation
Pre-built calculation presets eliminate guesswork—optimized parameters for scalping, day trading, and swing trading
Smart zone management automatically removes invalidated zones after two price rejections
Multi-timeframe architecture detects zones on configurable timeframes independent of chart timeframe
Visual style presets provide instant customization from high contrast to subtle overlays
Delta threshold system distinguishes between regular zones and institutionally-confirmed zones
🔧 Core Components
ApEn Calculator: Measures pattern regularity using embedding dimension (m=2) and tolerance factor (r) against price standard deviation to quantify market complexity
Delta Engine: Computes cumulative delta from volume and price movement, comparing against statistical thresholds to identify significant order flow divergence
Zone Generator: Creates visual box zones at signal points with dynamic sizing based on bar range and confirmation status
MTF Request Handler: Fetches ApEn calculations from user-specified timeframe using security() calls for higher timeframe alignment
Zone Manager: Tracks zone interactions, counts rejections, and automatically purges zones that have been tested twice
🔥 Key Features
Calculation Presets: Choose from Aggressive, Conservative, Scalping 1m, Strong Scalping, Swing Trading, or Default—each preset optimizes all parameters for specific trading styles
Visual Style Presets: Select Default, High Contrast, Subtle, Classic, Neutral, or Neutral Reverse to match your chart theme and preference
Delta Confirmation: Zones display with enhanced opacity when cumulative delta confirms institutional participation in the direction of the zone
Automatic Zone Cleanup: Zones self-destruct after two rejections, keeping your chart clean and focused on active levels
Alert System: Four alert conditions for buy zones, sell zones, strong buy signals, and strong sell signals
Maximum Zone Control: Limits display to 5 zones per direction to prevent chart clutter
🎨 Visualization
Buy Zones: Displayed as horizontal boxes at low points when ApEn crosses under threshold—lighter transparency indicates regular zone, darker indicates Delta confirmation
Sell Zones: Displayed as horizontal boxes at high points when ApEn crosses over threshold—visual confirmation follows same transparency logic
Zone Boundaries: Each zone extends 10% of bar range above and below the signal level, providing clear entry and stop areas
Dynamic Extension: All zones automatically extend rightward with each new bar until invalidated
📖 Usage Guidelines
Calculation Preset Selection
Scalping 1m / Strong Scalping: Use for 1-5 minute charts with faster signal generation and tighter thresholds (Length: 15, Zone Length: 5)
Aggressive: Shorter lookback (Length: 10) generates more zones with lower confirmation requirements—higher frequency, more noise
Default: Balanced parameters suitable for 5-15 minute charts (Length: 15, Zone Threshold: 0.5, Delta Length: 4)
Conservative: Extended lookback (Length: 30) with stricter thresholds—fewer but higher probability zones
Swing Trading: Longest parameters (Length: 40, Zone Length: 20) for 1H-4H charts capturing major structural zones
Visual Style Selection
High Contrast: Bright green/red for maximum visibility on any background
Subtle: Muted green/red with transparency for minimal chart distraction
Classic: Traditional lime green and crimson color scheme
Neutral / Neutral Reverse: Grayscale tones for non-directional bias visualization
Timeframe Configuration
Default timeframe is set to 1 minute—adjust based on your execution timeframe
For scalping: Set zone timeframe 1-3x your chart timeframe
For swing trading: Set zone timeframe to 4H or Daily while viewing 1H charts
✅ Best Use Cases
Identifying reversal zones during high-volatility market conditions
Confirming support/resistance levels with volume-based order flow validation
Scalping entries on lower timeframes with higher timeframe zone confluence
Filtering trade setups by requiring Delta confirmation before entry
Setting stop losses beyond zone boundaries after rejection tests
Swing trade positioning at zones detected on 4H/Daily timeframes
⚠️ Limitations
ApEn calculations are computationally intensive—may experience slower loading on very long chart histories
Delta estimation uses (close - open) * volume approximation, not actual order flow data
Zones require sufficient price history—indicator needs max_bars_back of 2000 bars for proper calculation
Low volume instruments may produce unreliable Delta confirmation signals
Zone rejections are counted based on price interaction, not candle close confirmation
Maximum of 5 zones per direction limits visibility during highly active markets
💡 What Makes This Unique
Entropy-Based Detection: Uses mathematical complexity analysis rather than simple price patterns to identify zones
Dual Confirmation System: Combines ApEn signals with Delta divergence for higher probability setups
Adaptive Presets: Six calculation presets and six visual styles create 36 possible configurations without manual parameter adjustment
Self-Managing Zones: Automatic invalidation after two rejections mimics how professional traders track level degradation
🔬 How It Works
Step 1 - ApEn Calculation: The indicator computes Approximate Entropy by measuring how often similar patterns of length m repeat within tolerance r multiplied by standard deviation—lower values indicate more predictable (ordered) price behavior
Step 2 - Signal Generation: Buy signals trigger when higher timeframe ApEn crosses under the average ApEn divided by threshold; sell signals trigger when ApEn crosses over average multiplied by threshold
Step 3 - Delta Confirmation: Cumulative delta is compared against its moving average plus/minus standard deviation times threshold—extreme readings confirm institutional order flow alignment
Step 4 - Zone Creation: Visual boxes are drawn at signal bars with dimensions based on bar range; confirmed zones receive enhanced opacity while unconfirmed zones appear more transparent
Step 5 - Zone Lifecycle: Active zones extend with each bar and track price interactions; after two rejections (price touches zone but reverses), the zone is automatically deleted
💡 Note:
This indicator works best when combined with trend analysis and market structure. Use calculation presets as starting points and adjust the Zone Timeframe setting to align with your trading methodology. Delta confirmation significantly improves zone reliability but requires volume data—instruments with low or unreported volume should rely primarily on ApEn signals alone. Always validate signals with price action context before executing trades.
High Volume S/R + VPA Entries + Broken Level Cleanup High Volume S/R + VPA Entries + Broken Level Cleanup
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
[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.
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.*
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.
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.
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)
SWING ATR BasedWhat does this indicator do?
1. It identifies Market Swings The script monitors price action to detect when a trend changes direction.
It uses ATR (Average True Range) to measure volatility, ensuring it doesn't get tricked by small, insignificant price movements.
To validate a change in direction (from bullish to bearish, or vice versa), it waits for the price to cover a specific distance (defined by the kRange parameter) and requires at least two significant candles.
2. It plots Support and Resistance zones As soon as a new high or low point is confirmed:
In Green (Bull): It draws a support line at the level of the last low.
In Red (Bear): It draws a resistance line at the level of the last high.
Auto-Cleaning: If the price breaks through a support line, the line turns gray and stops. The script only keeps active (unbroken) levels on the screen.
3. It calculates an "SGE Score" (Market State) This is the "brain" of the script. It assigns a rating to the current trend:
+2 (Bullish): The price has broken a resistance.
-2 (Bearish): The price has broken a support.
0 (Neutral): The market is indecisive (for example, after a break that contradicts the previous one).
Key Feature: This score has a "one-candle delay." It waits for the next candle to close before confirming a score change, which helps avoid reacting too quickly to false alerts.
4. It simplifies visual reading To keep your chart clean and readable:
It only highlights the 3 levels closest to the current price (those most likely to be hit soon).
It colors the chart candles directly: Green if the score is +2, Red if the score is -2, and Gray if it is neutral.
5. Dashboard In the top-right corner of your screen, it displays a permanent summary:
The current score (-2, 0, or 2).
The number of active supports and resistances.
Summary: This is a "smart" trend detector. Instead of just looking at whether the price is going up or down, it waits for the price to break important structural levels (confirmed by volatility) to tell you: "Caution, the structure has just shifted from bullish to bearish."
Recommended Settings:
kRange: 1.3 / 1.4
ATR Mult: 0.3 to 0.5
Script created with Claude AI.
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. 注意事項
本ツールは移動平均線に基づく「遅行指標」の性質を持ちます。そのため、急激なスパイク(一瞬の突発的な動き)には反応しない場合があります。
常に「上位足のトレンドがどちらを向いているか」をダッシュボードで確認し、逆張りでの使用は避けることを推奨します。
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.
Institutional Confluence Nexus [Pro]The Problem: Noise vs. Signal
In the world of Smart Money Concepts (SMC), traders are often overwhelmed by "chart clutter." Standard indicators blindly highlight every Fair Value Gap (FVG) and Order Block (OB), regardless of whether the market is trending, ranging, or dead. This leads to analysis paralysis and low-probability entries.
The Institutional Confluence Nexus was built to solve this. It is not just a structure detector; it is a filtering engine. It uses a multi-factor model to hide low-probability zones and only highlight setups where Structure, Volume, and Momentum align.
The "Quantum" Integration
This script includes a built-in Quantum Regression Oscillator (QRO) engine running in the background. Unlike standard RSI or MACD which are reactive (lagging), the QRO uses Linear Regression mathematics to project momentum trajectory.
By combining institutional structure (Price Action) with quantum momentum (Math), this tool generates specific high-probability signals that only appear when price action and momentum are in perfect agreement.
How It Works & Visual Guide
This indicator is a complete trading suite. Here is what every symbol and color on your chart represents:
1. The "Nexus" Reversal Signals (Triangles)
Symbol : Green Triangle (Up) / Red Triangle (Down) labeled NEXUS.
Logic : These appear when price taps a valid Order Block that aligns with the macro trend (200 EMA).
Meaning : These are your primary "Trend Join" setups. They indicate that the institutional trend is resuming after a retracement.
2. High-Volume Breakouts (Bar Colors)
Symbol : Yellow Candles (Bullish) / Orange Candles (Bearish).
Logic : The script detects when a Break of Structure (BOS) occurs with Above-Average Volume.
Meaning : A breakout without volume is often a fakeout. These colored bars confirm that institutions are fueling the move. If you see a Yellow bar, it means "Smart Money" is buying the breakout.
3. QRO Confluence Signals (Labels)
These are the most advanced signals in the suite, combining Price Action with the internal Oscillator:
SNIPER (Blue/Purple) : The strongest reversal signal.
Condition : Price taps a Fair Value Gap + The internal QRO is at extreme volatility bands (Oversold/Overbought).
PB BUY / PB SELL (Aqua/Orange) : A trend continuation signal.
Condition : Price pulls back into a Fair Value Gap + The internal QRO confirms momentum is still healthy (above/below midline).
Note : These signals automatically draw a Red Line at the invalidation point (Stop Loss) to help you manage risk immediately.
4. The Confluence Dashboard
A non-intrusive Heads-Up Display (HUD) in the corner gives you a snapshot of the market state:
Trend : Is price above/below the 200 EMA?
Volume : Is current volume anomalous (High) or normal?
Structure : Are we breaking up, down, or ranging?
Settings & Customization
Smart Money Structure: Toggle FVGs and Order Blocks on/off.
FVG Extend: Control how far the gap "zones" extend to the right to see them as support/resistance zones.
Volume Filter: Enable/Disable the volume requirement (Keep enabled for higher strike rate).
Risk Management: Adjust the "Lookback" period for the automatic Stop Loss lines.
For Developers (Open Source)
I have kept the code open-source to foster learning in the Pine Script community. You can study how:
ta.linreg is used to smooth RSI data for the internal QRO engine.
box.new and line.new are used for dynamic drawing and extending zones.
var variables are used to store historical FVG levels to detect precise crossovers.
Disclaimer:
This tool is designed to assist with technical analysis and educational purposes. It does not guarantee profits. Always manage your risk and use this in conjunction with your own analysis.
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.
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.
Order Blocks & Breaker Blocks Destek DirencOrder Blocks & Breaker Blocks Destek Direnc Al Sat Bölgeleri
Short-Term Weekly Refuges (Shelters)## // Introduction // (Spanish Texts Below)
═══════════════════════════
Short-Term Weekly Refuges (Shelters) (WR or RS) is a structural analysis indicator designed to track price action during the current week. It combines a configurable ZigZag with Fibonacci retracements anchored to recent phases, using the Weekly Opening Price (W.O.P.) as a key reference level.
This indicator is optimized for 4H timeframe but also works on 1H and 15min charts.
## // Theoretical Foundation of the Indicator //
═════════════════════════════════════════════════
The WR (RS) indicator provides a structural framework for following price action during the current trading week.
The core concept: Recent ZigZag phases, combined with the Weekly Opening Price, create dynamic support and resistance levels that institutional traders often monitor and use for intraweek positioning. The indicator allows you to select which recent phase (1-10) serves as the Fibonacci anchor.
## // Indicator Objectives //
═════════════════════════════
1) Display a configurable ZigZag showing recent price structure with numbered phases (1 = most recent). Users should configure the ZigZag parameters based on whether they are analyzing a Major Degree Pattern (larger swings, less noise) or a Minor Degree Pattern (smaller swings, more detail), following standard Elliott Wave terminology. Configure the ZigZag to match the degree of your analysis: use higher Depth values for Major Degree Patterns, or lower values for Minor Degree Patterns.
2) Draw Fibonacci retracements on a user-selected phase, with two modes:
• "On ZigZag": Traditional Fibonacci on the selected phase.
• "Relative to W.O.P.": Fibonacci from phase anchor (i0) to Weekly Opening Price.
3) Show Weekly Opening Price lines as horizontal references, with the current week's line extended into the future.
4) Provide Pivot Up/Down markers for additional confirmation of local highs and lows.
5) Support multiple simultaneous indicator loads with visual identifier labels to distinguish between different analysis degrees (e.g., "Major Degree Pattern" vs "Minor Degree Pattern").
6) Optional Embedded Indicator: Enable Intraday Shelters (RID) - percentage-based support/resistance levels calculated from the Daily Opening Price, useful for 1H and 15min trading.
## // Key Features //
═════════════════════
• **Flexible ZigZag**: Adjustable Depth, Deviation, and Backstep parameters to adapt to any asset's volatility and degree pattern.
• **Phase Selection**: Choose from the 10 most recent phases for Fibonacci anchoring.
• **Dual Fibonacci Modes**: Trace on the ZigZag phase itself, or relative to the Weekly Opening Price.
• **New Age Color Palette**: Professional Fibonacci color scheme used by old school experienced traders.
• **Weekly Opening Price (W.O.P.)**: Historical weekly opens plus current week projection.
• **"Show Only W.O.P." Mode**: Isolate just the Weekly Opening Price line for cleaner charts on non-4H timeframes.
• **Optional Intraday Shelters (RID)**: 11 percentage levels (±0.382%, ±1%, ±1.5%, ±2%, ±2.5%) based on Daily Opening Price.
• **Multi-Load Support**: Visual identifier tags and Large Label for running multiple indicator instances simultaneously.
## // Recommended Workflow //
═════════════════════════════
1) Load the indicator on a 4H chart.
2) Adjust ZigZag parameters (Depth, Deviation) until the phases match your visual analysis of recent price structure.
3) Select the phase you want to use as Fibonacci anchor (typically Phase 2, 3 or higher).
4) Choose Fibonacci mode: "On ZigZag" for phase analysis, or "Relative to W.O.P." for analysis based on weekly opening price context.
5) Monitor how price interacts with the Fibonacci levels and Weekly Opening Price throughout the week.
6) Optionally enable RID for intraday high precision order placements on 1H or 15min charts.
## // Integration with Other Refuge Indicators //
═════════════════════════════════════════════════
This indicator WR (RS) is part of our complete refuge-based analysis ecosystem:
• LTR (RLP) (Long-Term Refuges): For automatic determination of the predominant phase of a ZigZag, which institutional investors choose as the basis for a Fibo whose levels calculate the projection for order placement over the following months and years.
• LTRS (RLPS) (Simple Long-Term Refuges): Simplified version of LTR in which the known coordinates of the predominant phases (obtained with the LTR indicator) of up to five assets are easily captured for permanent long-term operation.
• WR (RS) (Short-Term Weekly Refuges): For short-term tactical analysis (4H, 1H) based on chosen phases of a ZigZag that define Fibo levels effective during the near past week(s).
• IDR (RID) (Intra-Day Refuges): For daily operations relying on intraday levels on timeframes of 1H or less. Ideal for scalping traders.
By combining LTR, LTRS, WR and IDR, you obtain a multi-level framework that allows you to operate with clarity at any time horizon, from intraday positions to investments spanning months and years.
## // Additional Notes //
═════════════════════════
1) Default parameters are optimized for volatile assets (crypto, tech stocks). For forex or less volatile instruments, consider reducing Deviation to 3-8%.
2) The "Phase in Development" (dashed line) shows the tentative current ZigZag segment that may still change as new bars form.
3) Due to TradingView's English-only publication rules, the complete Spanish version of this indicator with all tooltips and documentation will be available soon in our GitHub repository: aj-poolom-maasewal.
4) Bug reports, improvement proposals for the ZigZag generator, pattern determination, or Fibo composition, etc., will be greatly appreciated and taken into account for a future version. Best regards and happy hunting.
════════════════════════════════════════════════════
════════════════════════════════════════════════════
TEXTO EN ESPANIOL (Sin acentos ni enies para compatibilidad con TradingView)
════════════════════════════════════════════════════
## // Introduccion //
═════════════════════
Refugios Semanales (RS o WR) es un indicador de analisis estructural diseniado para seguir la accion del precio durante la semana en curso. Combina un ZigZag configurable con retrocesos de Fibonacci anclados a fases recientes, utilizando el Precio de Apertura Semanal (P.A.S.) como nivel de referencia clave.
Este indicador esta optimizado para temporalidad de 4H pero tambien funciona en graficos de 1H y 15min.
## // Fundamento Teorico del Indicador //
═════════════════════════════════════════
El indicador RS (WR) proporciona un marco estructural para seguir la accion del precio durante la semana de operacion actual.
El concepto central: Las fases recientes del ZigZag, combinadas con el Precio de Apertura Semanal, crean niveles dinamicos de soporte y resistencia que los operadores institucionales frecuentemente monitorean para su posicionamiento intrasemanal. El indicador permite seleccionar cual fase reciente (1-10) sirve como ancla del Fibonacci.
## // Objetivos del Indicador //
════════════════════════════════
1) Mostrar un ZigZag configurable con la estructura de precios reciente y fases numeradas (1 = mas reciente). Los usuarios deben configurar los parametros del ZigZag segun esten analizando una Pauta de Grado Mayor (oscilaciones mas amplias, menos ruido) o una Pauta de Grado Menor (oscilaciones mas pequenias, mas detalle), siguiendo la terminologia estandar de Ondas de Elliott. Configure el ZigZag para que coincida con el grado de su analisis: use valores de Profundidad mas altos para Pautas de Grado Mayor, o valores mas bajos para Pautas de Grado Menor.
2) Dibujar retrocesos de Fibonacci en una fase seleccionada por el usuario, con dos modos:
• "En el ZigZag": Fibonacci tradicional sobre la fase seleccionada.
• "Respecto al P.A.S.": Fibonacci desde el ancla de la fase (i0) hasta el Precio de Apertura Semanal.
3) Mostrar lineas del Precio de Apertura Semanal como referencias horizontales, con la linea de la semana actual extendida hacia el futuro.
4) Proporcionar marcadores de Pivote Arriba/Abajo para confirmacion adicional de maximos y minimos locales.
5) Soportar multiples cargas simultaneas del indicador con etiquetas identificadoras visuales para distinguir entre diferentes grados de analisis (ej: "Pauta de Grado Mayor" vs "Pauta de Grado Menor").
6) Indicador Integrado Opcional: Habilitar Refugios Intra-Diarios (RID) - niveles de soporte/resistencia basados en porcentajes calculados desde el Precio de Apertura Diaria, util para operacion en 1H y 15min.
## // Caracteristicas Principales //
════════════════════════════════════
• **ZigZag Flexible**: Parametros ajustables de Profundidad, Desviacion y Retroceso para adaptarse a la volatilidad y grado de pauta de cualquier activo.
• **Seleccion de Fase**: Elija entre las 10 fases mas recientes para el anclaje del Fibonacci.
• **Modos Duales de Fibonacci**: Trace sobre la fase del ZigZag, o relativo al Precio de Apertura Semanal.
• **Paleta de Colores New Age**: Esquema de colores profesional de Fibonacci usado por operadores institucionales de la vieja escuela.
• **Precio de Apertura Semanal (P.A.S.)**: Aperturas semanales historicas mas proyeccion de la semana actual.
• **Modo "Solo P.A.S."**: Aisla unicamente la linea del Precio de Apertura Semanal para graficos mas limpios en temporalidades distintas a 4H.
• **Refugios Intra-Diarios Opcionales (RID)**: 11 niveles porcentuales (±0.382%, ±1%, ±1.5%, ±2%, ±2.5%) basados en el Precio de Apertura Diaria.
• **Soporte Multi-Carga**: Etiquetas identificadoras visuales y Rotulo Grande para ejecutar multiples instancias del indicador simultaneamente.
## // Flujo de Trabajo Recomendado //
═════════════════════════════════════
1) Cargue el indicador en un grafico de 4H.
2) Ajuste los parametros del ZigZag (Profundidad, Desviacion) hasta que las fases coincidan con su analisis visual de la estructura de precios reciente.
3) Seleccione la fase que desea usar como ancla del Fibonacci (tipicamente Fase 2, 3 o superior).
4) Elija el modo de Fibonacci: "En el ZigZag" para analisis de fase, o "Respecto al P.A.S." para analisis basado en el contexto del precio de apertura semanal.
5) Monitoree como el precio interactua con los niveles de Fibonacci y el Precio de Apertura Semanal durante la semana.
6) Opcionalmente habilite RID para precision intradiaria en graficos de 1H o 15min.
## // Integracion con Otros Indicadores de Refugios //
══════════════════════════════════════════
RS (WR) es parte de nuestro ecosistema completo de analisis basado en refugios:
• RLP (LTR) (Refugios de Largo Plazo): Para determinacion automatica de la fase preponderante de un ZigZag, que los inversionistas institucionales eligen como base para un Fibo cuyos niveles calculan la proyeccion para colocacion de ordenes durante los meses y anios siguientes.
• RLPS (LTRS) (Refugios de Largo Plazo Simplificado): Version simplificada de RLP en la cual las coordenadas conocidas de las fases preponderantes (obtenidas con el indicador RLP) de uno o hasta cinco activos se capturan facilmente para operacion permanente de largo plazo.
• RS (WR) (Refugios Semanales de Corto Plazo): Para analisis tactico de corto plazo (4H, 1H) basado en fases elegidas de un ZigZag que definen niveles Fibo efectivos durante la(s) semana(s) pasada(s) reciente(s).
• RID (IDR) (Refugios Intra-Diarios): Para operaciones diarias basadas en niveles intradiarios en temporalidades de 1H o menos. Ideal para operadores de scalping.
Al combinar RLP, RLPS, RS y RID, obtiene un marco multinivel que le permite operar con claridad en cualquier horizonte temporal, desde posiciones intradiarias hasta inversiones que abarcan meses y anios.
## // Notas Adicionales //
══════════════════════════
1) Los parametros por defecto estan optimizados para activos volatiles (cripto, acciones tecnologicas). Para forex o instrumentos menos volatiles, considere reducir la Desviacion a 3-8%.
2) La "Fase en Desarrollo" (linea discontinua) muestra el segmento tentativo actual del ZigZag que aun puede cambiar conforme se formen nuevas barras.
3) Debido a las reglas de publicacion de TradingView (solo ingles), la version completa en espaniol de este indicador con todos los tooltips y documentacion estara disponible proximamente en nuestro repositorio de GitHub: aj-poolom-maasewal.
4) El reporte de cualquier error encontrado, propuestas de mejoras al generador de Zigzags, determinacion de pautas, o composicion del Fibo, etc., seran ampliamente agradecidas y tomadas en cuenta para una proxima version. Saludos y buena caceria.
══════════════════════════════════════════════════






















