Previous D/W/M HLOCHey traders,
Here's a simple Multi-Timeframe indicator that essentially turns time and price into a box. It'll take the previous high, low, opening price, or closing price from one of the three timeframes of your choice (day, week, or month). For whatever reason I can't get the opening price to function consistently so if you find improvements feel free to let me know, this will help traders who prefer to use opening price over closing price.
Naturally this form of charting is classical and nature and some key figures you could use to study its usage are
- Richard W. Schabacker (1930s)
- Edwards & Magee (1948)
- Peter Brandt
- Stacey Burke (more on the intraday side - typically our preference)
It's usage put plainly:
- Quantifying Accumulation or Distribution
- Revealing Energy Build-Up (Compression)
- Framing Breakouts and False Breakouts
- Structuring Time
- Identifying opportunities to trade a daily, weekly, or monthly range. 
Cerca negli script per "accumulation"
Power RSI Segment Runner [CHE]  Power RSI Segment Runner   — Tracks RSI momentum across higher timeframe segments to detect directional switches for trend confirmation.
  Summary 
This indicator calculates a running Relative Strength Index adapted to segments defined by changes in a higher timeframe, such as daily closes, providing a smoothed view of momentum within each period. It distinguishes between completed segments, which fix the final RSI value, and ongoing ones, which update in real time with an exponential moving average filter. Directional switches between bullish and bearish momentum trigger visual alerts, including overlay lines and emojis, while a compact table displays current trend strength as a progress bar. This segmented approach reduces noise from intra-period fluctuations, offering clearer signals for trend persistence compared to standard RSI on lower timeframes.
  Motivation: Why this design? 
Standard RSI often generates erratic signals in choppy markets due to constant recalculation over fixed lookback periods, leading to false reversals that mislead traders during range-bound or volatile phases. By resetting the RSI accumulation at higher timeframe boundaries, this indicator aligns momentum assessment with broader market cycles, capturing sustained directional bias more reliably. It addresses the gap between short-term noise and long-term trends, helping users filter entries without over-relying on absolute overbought or oversold thresholds.
  What’s different vs. standard approaches? 
- Baseline Reference: Diverges from the classic Wilder RSI, which uses a fixed-length exponential moving average of gains and losses across all bars.
- Architecture Differences:
  - Segments momentum resets at higher timeframe changes, isolating calculations per period instead of continuous history.
  - Employs persistent sums for ups and downs within segments, with on-the-fly RSI derivation and EMA smoothing.
  - Integrates switch detection logic that clears prior visuals on reversal, preventing clutter from outdated alerts.
  - Adds overlay projections like horizontal price lines and dynamic percent change trackers for immediate trade context.
- Practical Effect: Charts show discrete RSI endpoints for past segments alongside a curved running trace, making momentum evolution visually intuitive. Switches appear as clean, extendable overlays, reducing alert fatigue and highlighting only confirmed directional shifts, which aids in avoiding whipsaws during minor pullbacks.
  How it works (technical) 
The indicator begins by detecting changes in the specified higher timeframe, such as a new daily bar, to define segment boundaries. At each boundary, it finalizes the prior segment's RSI by summing positive and negative price changes over that period and derives the value from the ratio of those sums, then applies an exponential moving average for smoothing. Within the active segment, it accumulates ongoing ups and downs from price changes relative to the source, recalculating the running RSI similarly and smoothing it with the same EMA length.
Points for the running RSI are collected into an array starting from the segment's onset, forming a curved polyline once sufficient bars accumulate. Comparisons between the running RSI and the last completed segment's value determine the current direction as long, short, or neutral, with switches triggering deletions of old visuals and creation of new ones: a label at the RSI pane, a vertical dashed line across the RSI range, an emoji positioned via ATR offset on the price chart, a solid horizontal line at the switch price, a dashed line tracking current close, and a midpoint label for percent change from the switch.
Initialization occurs on the first bar by resetting accumulators, and visualization gates behind a minimum bar count since the segment start to avoid early instability. The trend strength table builds vertically with filled cells proportional to the rounded RSI value, colored by direction. All drawing objects update or extend on subsequent bars to reflect live progress.
  Parameter Guide 
EMA Length — Controls the smoothing applied to the running RSI; higher values increase lag but reduce noise. Default: 10. Trade-offs: Shorter settings heighten sensitivity for fast markets but risk more false switches; longer ones suit trending conditions for stability.
Source — Selects the price data for change calculations, typically close for standard momentum. Default: close. Trade-offs: Open or high/low may emphasize gaps, altering segment intensity.
Segment Timeframe — Defines the higher timeframe for segment resets, like daily for intraday charts. Default: D. Trade-offs: Shorter frames create more frequent but shorter segments; longer ones align with major cycles but delay resets.
Overbought Level — Sets the upper threshold for potential overbought conditions (currently unused in visuals). Default: 70. Trade-offs: Adjust for asset volatility; higher values delay bearish warnings.
Oversold Level — Sets the lower threshold for potential oversold conditions (currently unused in visuals). Default: 30. Trade-offs: Lower values permit deeper dips before signaling bullish potential.
Show Completed Label — Toggles labels at segment ends displaying final RSI. Default: true. Trade-offs: Enables historical review but can crowd charts on dense timeframes.
Plot Running Segment — Enables the curved polyline for live RSI trace. Default: true. Trade-offs: Visualizes intra-segment flow; disable for cleaner panes.
Running RSI as Label — Displays current running RSI as a forward-projected label on the last bar. Default: false. Trade-offs: Useful for quick reads; may overlap in tight scales.
Show Switch Label — Activates RSI pane labels on directional switches. Default: true. Trade-offs: Provides context; omit to minimize pane clutter.
Show Switch Line (RSI) — Draws vertical dashed lines across the RSI range at switches. Default: true. Trade-offs: Marks reversal bars clearly; extends both ways for reference.
Show Solid Overlay Line — Projects a horizontal line from switch price forward. Default: true. Trade-offs: Acts as dynamic support/resistance; wider lines enhance visibility.
Show Dashed Overlay Line — Tracks a dashed line from switch to current close. Default: true. Trade-offs: Shows price deviation; thinner for subtlety.
Show Percent Change Label — Midpoint label tracking percent move from switch. Default: true. Trade-offs: Quantifies progress; centers dynamically.
Show Trend Strength Table — Displays right-side table with direction header and RSI bar. Default: true. Trade-offs: Instant strength gauge; fixed position avoids overlap.
Activate Visualization After N Bars — Delays signals until this many bars into a segment. Default: 3. Trade-offs: Filters immature readings; higher values miss early momentum.
Segment End Label — Color for completed RSI labels. Default: 7E57C2. Trade-offs: Purple tones for finality.
Running RSI — Color for polyline and running elements. Default: yellow. Trade-offs: Bright for live tracking.
Long — Color for bullish switch visuals. Default: green. Trade-offs: Standard for uptrends.
Short — Color for bearish switch visuals. Default: red. Trade-offs: Standard for downtrends.
Solid Line Width — Thickness of horizontal overlay line. Default: 2. Trade-offs: Bolder for emphasis on key levels.
Dashed Line Width — Thickness of tracking and vertical lines. Default: 1. Trade-offs: Finer to avoid dominance.
  Reading & Interpretation 
Completed segment RSIs appear as static points or labels in purple, indicating the fixed momentum at period close—values drifting toward the upper half suggest building strength, while lower half implies weakness. The yellow curved polyline traces the live smoothed RSI within the current segment, rising for accumulating gains and falling for losses. Directional labels and lines in green or red flag switches: green for running momentum exceeding the prior segment's, signaling potential uptrend continuation; red for the opposite.
The right table's header colors green for long, red for short, or gray for neutral/wait, with filled purple bars scaling from bottom (low RSI) to top (high), topped by the numeric value. Overlay elements project from switch bars: the solid green/red line as a price anchor, dashed tracker showing pullback extent, and percent label quantifying deviation—positive for alignment with direction, negative for counter-moves. Emojis (up arrow for long, down for short) float above/below price via ATR spacing for quick chart scans.
  Practical Workflows & Combinations 
- Trend Following: Enter long on green switch confirmation after a higher high in structure; filter with table strength above midpoint for conviction. Pair with volume surge for added weight.
- Exits/Stops: Trail stops to the solid overlay line on pullbacks; exit if percent change reverses beyond 2 percent against direction. Use wait bars to confirm without chasing.
- Multi-Asset/Multi-TF: Defaults suit forex/stocks on 1H-4H with daily segments; for crypto, shorten EMA to 5 for volatility. Scale segment TF to weekly for daily charts across indices.
- Combinations: Overlay on EMA clouds for confluence—switch aligning with cloud break strengthens signal. Add volatility filters like ATR bands to debounce in low-volume regimes.
  Behavior, Constraints & Performance 
Signals confirm on bar close within segments, with running polyline updating live but gated by minimum bars to prevent flicker. Higher timeframe changes may introduce minor repaints on timeframe switches, mitigated by relying on confirmed HTF closes rather than intrabar peeks. Resource limits cap at 500 labels/lines and 50 polylines, pruning old objects on switches to stay efficient; no explicit loops, but array growth ties to segment length—suitable for up to 500-bar histories without lag.
Known limits include delayed visualization in short segments and insensitivity to overbought/oversold levels, as thresholds are inputted but not actively visualized. Gaps in source data reset accumulators prematurely, potentially skewing early RSI.
  Sensible Defaults & Quick Tuning 
Start with EMA length 10, daily segments, and 3-bar wait for balanced responsiveness on hourly charts. For excessive switches in ranging markets, increase wait bars to 5 or EMA to 14 to dampen noise. If signals lag in trends, drop EMA to 5 and use 1H segments. For stable assets like indices, widen to weekly segments; tune colors for dark/light themes without altering logic.
  What this indicator is—and isn’t 
This tool serves as a momentum visualization and switch detector layered over price action, aiding trend identification and confirmation in segmented contexts. It is not a standalone trading system, predictive model, or risk calculator—always integrate with broader analysis, position sizing, and stop-loss discipline. View it as an enhancement for discretionary setups, not automated alerts without validation.
  Disclaimer 
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.  
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.  
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.  
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.  
 Best regards and happy trading  
Chervolino
VolumeAnlaysis### Volume Analysis (VA) Indicator
**Overview**  
The Volume Analysis (VA) indicator is a dynamic overlay tool designed for traders seeking to identify high-volume breakouts, retests, and multi-timeframe volume-driven price cycles. By combining volume spikes with price action and support/resistance boxes, it highlights potential trend continuations, reversals, and cycle shifts. Ideal for intraday and swing trading on stocks, forex, or crypto, it uses a Fibonacci-inspired 1.618 multiplier to detect significant volume surges, then maps them to visual boxes and key levels for actionable insights.  
This indicator draws from volume profile concepts but focuses on **breakout confirmation** and **cycle momentum**, helping you spot when "smart money" volume aligns with price extremes. It's particularly useful in volatile markets where volume precedes price moves.
**How It Works**  
1. **Volume Break Detection**:  
   - Identifies a "Volume Break" when the current bar's volume exceeds 1.618x the highest volume from the prior 5 bars. This signals unusual activity, often preceding breakouts.  
   - A "Volume Retest" triggers exactly 3 bars after a break if volume has been falling steadily over those 3 bars—indicating a pullback for re-accumulation/distribution.
2. **Visual Annotations**:  
   - **Labels**: Green/red/yellow labels mark Volume Breaks and Retests, positioned above/below the bar based on candle direction for clarity.  
   - **Demand/Supply Boxes**:  
     - Blue semi-transparent boxes form around Retest bars, extending rightward to act as dynamic support/resistance.  
     - Green (bullish) or red (bearish) boxes draw from Volume Breaks, based on the original candle's open/close, highlighting potential zones for continuation.  
     - Limited to 5 boxes max to avoid chart clutter; older boxes fade as new ones form.
3. **Box Interaction Signals**:  
   - When price enters a box:  
     - **Reversal Hints**: Maroon (bearish rejection) or lime (bullish rejection) labels on closes against the trend with opening price momentum.  
     - **Breakout Arrows**: Up/down arrows on crossovers/crossunders of box tops/bottoms from Retest boxes.  
   - Scans all active boxes for interactions, prioritizing recent volume events.
4. **Multi-Timeframe Volume Cycles**:  
   - Aggregates the "Volume Break Max" level (a proxy for key price extremes tied to volume spikes) across timeframes: 1min, 5min, 10min, 30min, and 65min (using `request.security`).  
   - Computes **MaxVolBreak** (highest extreme) and **MinVolBreak** (lowest extreme) for trend-following levels.  
   - Tracks **Percent Volume Greater/Less Than Close**: Sums volumes from TFs where price is below/above these levels, creating a momentum ratio.  
   - **CrossClose**: Plots the prior close where this ratio crosses (gray line), signaling cycle shifts—bullish below MinVolBreak, bearish above MaxVolBreak.  
   - **Fills**: Red fill above CrossClose/MaxVolBreak (bearish cycle); green below CrossClose/MinVolBreak (bullish cycle).
5. **Plots**:  
   - Black lines for MaxVolBreak (⏫) and MinVolBreak (⏬).  
   - Gray 🔄 for CrossClose.  
   - Colors dynamically adjust (green/red) based on close relative to levels.
**Key Features**  
- **Trend vs. Reversal Modes**: Toggle alerts for trend-following breaks (crosses of Max/MinVolBreak) or reversal signals (crosses of CrossClose).  
- **Multi-TF Fusion**: Optionally include the chart's native timeframe in Max/Min calculations for finer tuning.  
- **Box Management**: Auto-prunes to 5 boxes; focuses on retest/break alignments for "inside bar" logic.  
- **Momentum Filters**: Uses rising/falling opens and crossovers for label precision, reducing noise.  
- **Customizable**: Simple inputs for alert visibility and timeframe inclusion.
**Settings**  
| Input | Default | Description |  
|-------|---------|-------------|  
| Show Volume Reversal Breaks | False | Enables alerts/labels for CrossClose crosses (cycle reversals). |  
| Show Trend Following Breaks | True | Enables alerts for Max/MinVolBreak crosses (trend signals). |  
| Use Current Time | False | Includes chart's native TF in multi-TF Max/Min calculations. |  
**Alerts**  
- **Reversal Alerts** (if enabled): "Volume Reverse Bullish/Bearish Break of  " on close crosses of CrossClose.  
- **Trend Alerts** (if enabled): "Trend Volume Bullish/Bearish Signal" on close crosses of Max/MinVolBreak; plus notes if prior low/high aligns with levels.  
- All alerts include ticker and level value for easy scanning. Use `alert.freq_once_per_bar` to avoid spam.
**Trading Ideas**  
- **Bullish Entry**: Green box formation + price holding MinVolBreak + upward arrow on retest box. Target next resistance.  
- **Bearish Entry**: Red box + close above MaxVolBreak + red fill activation. Stop below recent low.  
- **Cycle Trading**: Watch CrossClose crosses for regime shifts—fade extremes in overextended cycles.  
- **Best Timeframes**: 5-30min for intraday; combine with daily for swings. Works best on liquid assets with reliable volume data.  
**Limitations & Notes**  
- Relies on accurate volume data (e.g., stocks/forex); less effective on low-volume or synthetic instruments.  
- Boxes extend rightward but don't auto-delete—monitor for clutter on long histories (max_bars_back=500).  
- Some logic (e.g., exact 3-bar retest) is rigid; backtest for your market.  
- Open-source under MPL 2.0—fork and tweak as needed!  
For questions or enhancements, drop a comment below. Happy trading! 🚀
Ehlers Phasor Analysis (PHASOR)# PHASOR: Phasor Analysis (Ehlers)
## Overview and Purpose
The Phasor Analysis indicator, developed by John Ehlers, represents an advanced cycle analysis tool that identifies the phase of the dominant cycle component in a time series through complex signal processing techniques. This sophisticated indicator uses correlation-based methods to determine the real and imaginary components of the signal, converting them to a continuous phase angle that reveals market cycle progression. Unlike traditional oscillators, the Phasor provides unwrapped phase measurements that accumulate continuously, offering unique insights into market timing and cycle behavior.
## Core Concepts
*   **Complex Signal Analysis** — Uses real and imaginary components to determine cycle phase
*   **Correlation-Based Detection** — Employs Ehlers' correlation method for robust phase estimation
*   **Unwrapped Phase Tracking** — Provides continuous phase accumulation without discontinuities
*   **Anti-Regression Logic** — Prevents phase angle from moving backward under specific conditions
Market Applications:
*   **Cycle Timing** — Precise identification of cycle peaks and troughs
*   **Market Regime Analysis** — Distinguishes between trending and cycling market conditions
*   **Turning Point Detection** — Advanced warning system for potential market reversals
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|----------------|
| Period | 28 | Fixed cycle period for correlation analysis | Match to expected dominant cycle length |
| Source | Close | Price series for phase calculation | Use typical price or other smoothed series |
| Show Derived Period | false | Display calculated period from phase rate | Enable for adaptive period analysis |
| Show Trend State | false | Display trend/cycle state variable | Enable for regime identification |
## Calculation and Mathematical Foundation
**Technical Formula:**
**Stage 1: Correlation Analysis**
For period $n$ and source $x_t$:
Real component correlation with cosine wave:
$$R = \frac{n \sum x_t \cos\left(\frac{2\pi t}{n}\right) - \sum x_t \sum \cos\left(\frac{2\pi t}{n}\right)}{\sqrt{D_{cos}}}$$
Imaginary component correlation with negative sine wave:
$$I = \frac{n \sum x_t \left(-\sin\left(\frac{2\pi t}{n}\right)\right) - \sum x_t \sum \left(-\sin\left(\frac{2\pi t}{n}\right)\right)}{\sqrt{D_{sin}}}$$
where $D_{cos}$ and $D_{sin}$ are normalization denominators.
**Stage 2: Phase Angle Conversion**
$$\theta_{raw} = \begin{cases}
90° - \arctan\left(\frac{I}{R}\right) \cdot \frac{180°}{\pi} & \text{if } R \neq 0 \\
0° & \text{if } R = 0, I > 0 \\
180° & \text{if } R = 0, I \leq 0
\end{cases}$$
**Stage 3: Phase Unwrapping**
$$\theta_{unwrapped}(t) = \theta_{unwrapped}(t-1) + \Delta\theta$$
where $\Delta\theta$ is the normalized phase difference.
**Stage 4: Ehlers' Anti-Regression Condition**
$$\theta_{final}(t) = \begin{cases}
\theta_{final}(t-1) & \text{if regression conditions met} \\
\theta_{unwrapped}(t) & \text{otherwise}
\end{cases}$$
**Derived Calculations:**
Derived Period: $P_{derived} = \frac{360°}{\Delta\theta_{final}}$ (clamped to  )
Trend State: 
$$S_{trend} = \begin{cases}
1 & \text{if } \Delta\theta \leq 6° \text{ and } |\theta| \geq 90° \\
-1 & \text{if } \Delta\theta \leq 6° \text{ and } |\theta| < 90° \\
0 & \text{if } \Delta\theta > 6°
\end{cases}$$
> 🔍 **Technical Note:** The correlation-based approach provides robust phase estimation even in noisy market conditions, while the unwrapping mechanism ensures continuous phase tracking across cycle boundaries.
## Interpretation Details
*   **Phasor Angle (Primary Output):**
    - **+90°**: Potential cycle peak region
    - **0°**: Mid-cycle ascending phase
    - **-90°**: Potential cycle trough region
    - **±180°**: Mid-cycle descending phase
*   **Phase Progression:**
    - Continuous upward movement → Normal cycle progression
    - Phase stalling → Potential cycle extension or trend development
    - Rapid phase changes → Cycle compression or volatility spike
*   **Derived Period Analysis:**
    - Period < 10 → High-frequency cycle dominance
    - Period 15-40 → Typical swing trading cycles
    - Period > 50 → Trending market conditions
*   **Trend State Variable:**
    - **+1**: Long trend conditions (slow phase change in extreme zones)
    - **-1**: Short trend or consolidation (slow phase change in neutral zones)
    - **0**: Active cycling (normal phase change rate)
## Applications
*   **Cycle-Based Trading:**
    - Enter long positions near -90° crossings (cycle troughs)
    - Enter short positions near +90° crossings (cycle peaks)
    - Exit positions during mid-cycle phases (0°, ±180°)
*   **Market Timing:**
    - Use phase acceleration for early trend detection
    - Monitor derived period for cycle length changes
    - Combine with trend state for regime-appropriate strategies
*   **Risk Management:**
    - Adjust position sizes based on cycle clarity (derived period stability)
    - Implement different risk parameters for trending vs. cycling regimes
    - Use phase velocity for stop-loss placement timing
## Limitations and Considerations
*   **Parameter Sensitivity:**
    - Fixed period assumption may not match actual market cycles
    - Requires cycle period optimization for different markets and timeframes
    - Performance degrades when multiple cycles interfere
*   **Computational Complexity:**
    - Correlation calculations over full period windows
    - Multiple mathematical transformations increase processing requirements
    - Real-time implementation requires efficient algorithms
*   **Market Conditions:**
    - Most effective in markets with clear cyclical behavior
    - May provide false signals during strong trending periods
    - Requires sufficient historical data for correlation analysis
Complementary Indicators:
* MESA Adaptive Moving Average (cycle-based smoothing)
* Dominant Cycle Period indicators
* Detrended Price Oscillator (cycle identification)
## References
1. Ehlers, J.F. "Cycle Analytics for Traders." Wiley, 2013.
2. Ehlers, J.F. "Cybernetic Analysis for Stocks and Futures." Wiley, 2004.
Fib OscillatorWhat is Fib Oscillator and How to Use it?
🔶 1. Conceptual Overview
The Fib Oscillator is a Fibonacci-based relative position oscillator.
Instead of measuring momentum (like RSI or MACD), it measures where price currently sits between the recent swing high and swing low, expressed as a percentage within the Fibonacci range.
In other words:
It answers: “Where is price right now within its most recent dynamic range?”
It visualizes retracement and extension zones numerically, providing continuous feedback between 0% and 100% (and beyond if extended).
🔶 2. What the Script Does
The indicator:
Automatically detects recent high and low levels using an adaptive lookback window, which depends on ATR volatility.
Calculates the current price’s position between those levels as a percentage (0–100).
Plots that percentage as an oscillator — showing visually whether price is near the top, middle, or bottom of its recent range.
Overlays Fibonacci retracement levels (23.6%, 38.2%, 50%, 61.8%, 78.6%) as reference zones.
Generates alerts when the oscillator crosses key Fib thresholds — which can signal retracement completion, breakout potential, or pullback exhaustion.
🔶 3. Technical Flow Breakdown
(a) Inputs
Input	Description	Default	Notes
atrLength	ATR period used for volatility estimation	14	Used to dynamically tune lookback sensitivity
minLookback	Minimum lookback window (candles)	20	Ensures stability even in low volatility
maxLookback	Maximum lookback window	100	Limits over-expansion during high volatility
isInverse	Inverts chart orientation	false	Useful for inverse markets (e.g. shorts or inverse BTC view)
(b) Volatility-Adaptive Lookback
Instead of using a fixed lookback, it calculates:
lookback
=
SMA(ATR,10)
/
SMA(Close,10)
×
500
lookback=SMA(ATR,10)/SMA(Close,10)×500
Then it clamps this between minLookback and maxLookback.
This makes the oscillator:
More reactive during high volatility (shorter lookback)
More stable during calm markets (longer lookback)
Essentially, it self-adjusts to market rhythm — you don’t have to constantly tweak lookback manually.
(c) High-Low Reference Points
It takes the highest and lowest points within the dynamic lookback window.
If isInverse = true, it flips the candle logic (useful if viewing inverse instruments like stablecoin pairs or when analyzing bearish setups invertedly).
(d) Oscillator Core
The main oscillator line:
osc
=
(
close
−
low
)
(
high
−
low
)
×
100
osc=
(high−low)
(close−low)
	
×100
0% = Price is at the lookback low.
100% = Price is at the lookback high.
50% = Midpoint (balanced).
Between Fibonacci percentages (23.6%, 38.2%, 61.8%, etc.), the oscillator indicates retracement stages.
(e) Fibonacci Levels as Reference
It overlays horizontal reference lines at:
0%, 23.6%, 38.2%, 50%, 61.8%, 78.6%, 100%
These act as support/resistance bands in oscillator space.
You can read it similar to how traders use Fibonacci retracements on charts, but compressed into a single line oscillator.
(f) Alerts
The script includes built-in alert conditions for crossovers at each major Fibonacci level.
You can set TradingView alerts such as:
“Oscillator crossed above 61.8%” → possible bullish continuation or breakout.
“Oscillator crossed below 38.2%” → possible pullback or correction starting.
This allows automated monitoring of fib retracement completions without manually drawing fib levels.
🔶 4. How to Use It
🔸 Visual Interpretation
Oscillator Value	Zone	Market Context
0–23.6%	Deep Retracement	Potential exhaustion of a down-move / early reversal
23.6–38.2%	Shallow retracement zone	Possible continuation phase
38.2–50%	Mid retracement	Neutral or indecisive structure
50–61.8%	Key pivot region	Common trend resumption zone
61.8–78.6%	Late retracement	Often “last pullback” area
78.6–100%	Near high range	Possible overextension / profit-taking
>100%	Range breakout	New leg formation / expansion
🔸 Practical Application Steps
Load the indicator on your chart (set overlay = false, so it’s below the main price chart).
Observe oscillator position relative to fib bands:
Use it to determine retracement depth.
Combine with structure tools:
Trend lines, swing points, or HTF market structure.
Use crossovers for timing:
Crossing above 61.8% in an uptrend often confirms breakout continuation.
Crossing below 38.2% in a downtrend signals renewed downside momentum.
For range markets, oscillator swings between 23.6% and 78.6% can define accumulation/distribution boundaries.
🔶 5. When to Use It
During Retracements: To gauge how deep the pullback has gone.
During Range Markets: To identify relative overbought/oversold positions.
Before Breakouts: Crossovers of 61.8% or 78.6% often precede impulsive moves.
In Multi-Timeframe Contexts:
LTF (15M–1H): Detect intraday retracement exhaustion.
HTF (4H–1D): Confirm major range expansions or key reversal zones.
🔶 6. Ideal Companion Indicators
The Fib Oscillator works best when contextualized with structure, volatility, and trend bias indicators.
Below are optimal pairings:
Companion Indicator	Purpose	Integration Insight
Market Structure MTF Tool	Identify active trend direction	Use Fib Oscillator only in trend direction for cleaner signals
EMA Ribbon / Supertrend	Trend confirmation	Align oscillator crossovers with EMA bias
ATR Bands / Volatility Envelope	Validate breakout strength	If oscillator >78.6% & ATR rising → valid breakout
Volume Oscillator	Confirm retracement strength	Volume contraction + oscillator under 38.2% → potential reversal
HTF Fib Retracement Tool	Combine LTF oscillator with HTF fib confluence	Powerful multi-timeframe setups
RSI or Stochastic	Measure momentum relative to position	RSI divergence while oscillator near 78.6% → exhaustion clue
🔶 7. Understanding the Settings
Setting	Function	Practical Impact
ATR Period (14)	Controls volatility sampling	Higher = smoother lookback adaptation
Min Lookback (20)	Smallest window allowed	Lower = more reactive but noisier
Max Lookback (100)	Largest window allowed	Higher = smoother but slower to react
Inverse Candle Chart	Flips oscillator vertically	Useful when analyzing bearish or inverse scenarios (e.g. short-side fib mapping)
Recommended Configs:
For scalping/intraday: ATR 10–14, lookback 20–50
For swing/position trading: ATR 14–21, lookback 50–100
🔶 8. Example Trade Logic (Practical Use)
Scenario: Uptrend on 4H chart
Oscillator drops to below 38.2% → retracement zone
Price consolidates → oscillator stabilizes
Oscillator crosses above 50% → pullback ending
Entry: Long when oscillator crosses above 61.8%
Exit: Near 78.6–100% zone or upon divergence with RSI
For Short Bias (Inverse Setup):
Enable isInverse = true to visually flip the oscillator (so lows become highs).
Use the same thresholds inversely.
🔶 9. Strengths & Limitations
✅ Strengths
Dynamic, self-adapting to volatility
Quantifies Fib retracement as a continuous function
Compact oscillator view (no clutter on chart)
Works well across all timeframes
Compatible with both trending and ranging markets
⚠️ Limitations
Doesn’t define trend direction — must be used with structure filters
Can whipsaw during choppy consolidations
The “lookback auto-adjust” may lag in sudden volatility shifts
Shouldn’t be used standalone for entries without structural confluence
🔶 10. Summary
The “Fib Oscillator” is a dynamic Fibonacci-relative positioning tool that merges retracement theory with adaptive volatility logic.
It gives traders an intuitive, quantified view of where price sits within its recent fib range, allowing anticipation of pullbacks, reversals, or breakout momentum.
Think of it as a "Fibonacci RSI", but instead of momentum strength, it shows positional depth — the vibrational location of price within its natural swing cycle.
Dual Table Dashboard - Correct V3add RSI Data## 📈 Trading Applications
### 1. Trend Following Strategy
```
1. Check TABLE 1 for trend direction (AnEMA29 + PDMDR)
2. If both green → Look for longs
3. If both red → Look for shorts
4. Use TABLE 2 for entry levels
```
### 2. Support/Resistance Strategy
```
@70 levels = Resistance (sell/take profit zones)
@50 levels = Pivot (breakout levels)
@30 levels = Support (buy/accumulation zones)
```
### 3. Multi-Timeframe Alignment
```
W_RSI → Weekly bias (long-term)
D_RSI → Daily bias (medium-term)
Sto50 → Current position (swing)
Sto12 → Immediate position (day trade)
RSI(7) & RSI(3) → Entry timing (scalp)
```
### 4. Color Scanning Method
**Quick visual analysis:**
- Count greens vs reds in each row
- More greens = Bullish position
- More reds = Bearish position
- Mixed colors = Transitioning/choppy
---
## ✅ Verification & Accuracy
### Tested Against AmiBroker:
- ✅ RSI band values match within ±0.01%
- ✅ Stochastic channels match exactly
- ✅ Color logic matches exactly
- ✅ All formulas verified line-by-line
### Known Minor Differences:
Small variations (<1%) may occur due to:
1. **Platform calculation precision** - Different floating-point engines
2. **Historical data feeds** - Slight variations in past prices
3. **Weekly bar boundaries** - TradingView vs AmiBroker week definitions
4. **Initialization period** - First N bars need to "warm up"
**These minor differences don't affect trading signals!**
---
## ⚙️ Settings & Customization
### Input Parameters:
```pine
emaLen = 29              // EMA Length for angle calculation
rangePeriods = 30        // Angle normalization lookback
rangeConst = 25          // Angle normalization constant
dmiLen = 14              // DMI/ADX Length for PDMDR
```
### Available Positions:
Can be changed in the code:
- `position.top_left`
- `position.top_center`
- `position.top_right`
- `position.middle_left` (Table 2 default)
- `position.middle_center`
- `position.middle_right`
- `position.bottom_left` (Table 1 default)
- `position.bottom_center`
- `position.bottom_right`
### Text Sizes:
- `size.tiny`
- `size.small` (current default)
- `size.normal`
- `size.large`
- `size.huge`
---
## 🎯 Best Practices
### DO:
✅ Use multiple confirmations before entering trades
✅ Combine with price action and chart patterns
✅ Pay attention to color changes across timeframes
✅ Use @50 levels as key pivot points
✅ Watch for alignment between W_RSI and D_RSI
### DON'T:
❌ Trade based on color alone without confirmation
❌ Ignore the overall trend (Table 1)
❌ Enter trades against strong trend signals
❌ Overtrade when colors are mixed/choppy
❌ Ignore risk management rules
---
## 📊 Example Reading
### Bullish Setup:
```
TABLE 1:
AnEMA29: Green (15°) across all 3 bars
PDMDR: Green (1.65) and rising
TABLE 2:
W_RSI@50: Green (price above)
D_RSI@50: Green (price above)
Sto50@50: Green (price above midpoint)
Sto12@50: Green (price above midpoint)
Interpretation: Strong bullish trend confirmed across multiple timeframes
Action: Look for long entries on pullbacks to @50 or @30 levels
```
### Bearish Setup:
```
TABLE 1:
AnEMA29: Red (-12°) across all 3 bars
PDMDR: Red (0.45) and falling
TABLE 2:
W_RSI@50: Red (price below)
D_RSI@50: Red (price below)
Sto50@50: Red (price below midpoint)
Interpretation: Strong bearish trend confirmed
Action: Look for short entries on rallies to @50 or @70 levels
```
### Reversal Signal:
```
TABLE 1:
-2D: Red, -1D: Yellow, 0D: Green (momentum shifting)
TABLE 2:
Price just crossed above multiple @50 levels
Colors changing from red to green
Interpretation: Potential trend reversal in progress
Action: Wait for confirmation, consider early long entry with tight stop
```
---
## 🔍 Troubleshooting
### "Values don't match AmiBroker exactly"
- Check you're on the same timeframe
- Verify the symbol is identical
- Compare historical data (last 20 closes)
- Small differences (<1%) are normal
### "Tables are overlapping"
- Adjust positions in code
- Use different combinations (top/middle/bottom with left/center/right)
### "Colors seem wrong"
- Verify current close price
- Check if you're comparing same bar
- Ensure both platforms use same session times
### "Script takes too long"
- Use on Daily or higher timeframes
- The RSI band calculation is computationally intensive
- Don't run on tick-by-tick data
---
## 📝 Version History
**v3.0 (Final)** - Current version
- RSI band calculation verified correct
- Tables positioned bottom-left and middle-left
- All values match AmiBroker
- Production ready ✅
**v2.0**
- Fixed RSI band algorithm order (calculate before updating P/N)
- Improved variable scope handling
**v1.0**
- Initial implementation
- Had incorrect RSI band calculation
---
## 📄 Files in Package
PheeTrades - Value Area Levels (VAH / VAL / POC Visualizer)This script helps traders quickly visualize key Volume Profile–style levels such as Value Area High (VAH), Value Area Low (VAL), and Point of Control (POC) using recent price and volume data.
While TradingView’s built-in Volume Profile tool is great for manual analysis, this indicator automatically calculates and plots approximate value zones directly on your chart — ideal for traders who want to identify high-probability support and resistance areas without drawing a fixed range every time.
Features:
Calculates short-term VAH, VAL, and POC based on a user-defined lookback period.
Plots color-coded levels for quick visual reference.
Helps identify “fair value” zones where most trading activity occurred.
Useful for detecting breakout or mean-reversion opportunities around value extremes.
How to use:
Apply the script to any chart and set your preferred lookback period.
VAH (red line): potential upper resistance or overbought zone.
VAL (green line): potential lower support or accumulation zone.
POC (orange line): price level with the highest traded activity — often a magnet for price.
Note:
This is a simplified Value Area model meant for educational and analytical use. It does not replace TradingView’s official Volume Profile or broker-level volume distribution data.
saodisengxiaoyu-lianghua-2.1- This indicator is a modular, signal-building framework designed to generate long and short signals by combining a chosen leading indicator with selectable confirmation filters. It runs on Pine Script version 5, overlays directly on price, and is built to be highly configurable so traders can tailor the signal logic to their market, timeframe, and trading style. It includes a dashboard to visualize which conditions are active and whether they validate a signal, and it outputs clear buy/sell labels and alert conditions so you can automate or monitor trades with confidence.
Core Design
- Leading Indicator: You choose one primary signal generator from a broad list (for example, Range Filter, Supertrend, MACD, RSI, Ichimoku, and many others). This serves as the anchor of the system and determines when a preliminary long or short setup exists.
- Confirmation Filters: You can enable additional filters that validate the leading signal before it becomes actionable. Each “respect…” input toggles a filter on or off. These filters include popular tools like EMA, 2/3 EMA crosses, RQK (Nadaraya Watson), ADX/DMI, Bollinger-based oscillators, MACD variations, QQE, Hull, VWAP, Choppiness Index, Damiani Volatility, and more.
- Signal Expiry: To avoid waiting indefinitely for confirmations, the indicator counts how many consecutive bars the leading condition holds. If confirmations do not align within a defined number of bars, the setup expires. This controls latency and helps reduce late or stale entries.
- Alternating Signals: An optional mode enforces alternation (long must follow short and vice versa), helping avoid repeated entries in the same direction without a meaningful reset.
- Aggregation Logic: The final long/short conditions are formed by combining the leading condition with all selected confirmation filters through logical conjunction. Only if all enabled filters validate the signal (within expiry constraints) does the indicator consider it a confirmed long or short.
- Visualization and Alerts: The script plots buy/sell labels at signal points, provides alert conditions for automation, and displays a compact dashboard summarizing the leading indicator’s status and each confirmation’s pass/fail result using checkmarks.
Leading Indicator Options
- The indicator includes a very large menu of leading tools, each with its own logic to determine uptrend or downtrend impulses. Highlights include:
  - Range Filter: Uses a dynamic centerline and bands computed via conditional EMA/SMA and range sizing to define directional movement. It can operate in a default mode or an alternative “DW” mode.
  - Rational Quadratic Kernel (RQK): Applies a kernel smoothing model (Nadaraya Watson) to detect uptrends and downtrends with a focus on noise reduction.
  - Supertrend, Half Trend, SSL Channel: Classic trend-following tools that derive direction from ATR-based bands or moving average channels.
  - Ichimoku Cloud and SuperIchi: Multi-component systems validating trend via cloud position, conversion/base line relationships, projected cloud, and lagging span.
  - TSI (True Strength Index), DPO (Detrended Price Oscillator), AO (Awesome Oscillator), MACD, STC (Schaff Trend Cycle), QQE Mod: Momentum and cycle tools that parse direction from crossovers, zero-line behavior, and momentum shifts.
  - Donchian Trend Ribbon, Chandelier Exit: Trend and exit tools that can validate breakouts or sustained trend strength.
  - ADX/DMI: Measures trend strength and directional movement via +DI/-DI relationships and minimum ADX thresholds.
  - RSI and Stochastic: Use crossovers, level exits, or threshold filters to gate entries based on overbought/oversold dynamics or relative strength trends.
  - Vortex, Chaikin Money Flow, VWAP, Bull Bear Power, ROC, Wolfpack Id, Hull Suite: A diverse set of directional, momentum, and volume-based indicators to suit different markets and styles.
  - Trendline Breakout and Range Detector: Price-behavior filters that confirm signals during breakouts or within defined ranges.
Confirmation Filters
- Each filter is optional. When enabled, it must validate the leading condition for a signal to pass. Examples:
  - EMA Filter: Requires price to be above a specified EMA for longs and below for shorts, filtering signals that contradict broader trend or baseline levels.
  - 2 EMA Cross and 3 EMA Cross: Enforce moving average cross conditions (fast above slow for long, the reverse for short) or a three-line stacking logic for more stringent trend alignment.
  - RQK, Supertrend, Half Trend, Donchian, QQE, Hull, MACD (crossover vs. zero-line), AO (zero line or AC momentum variants), SSL: Each adds its characteristic validation pattern.
  - RSI family (MA cross, exits OB/OS zones, threshold levels) plus RSI MA direction and RSI/RSI MA limits: Multiple ways to constrain signals via relative strength behavior and trajectories.
  - Choppiness Index and Damiani Volatility: Prevent entries during ranging conditions or insufficient volatility; choppiness thresholds and volatility states gate the trade.
  - VWAP, Volume modes (above MA, simple up/down, delta), Chaikin Money Flow: Volume and flow conditions that ensure signals happen in supportive liquidity or accumulation/distribution contexts.
  - ADX/DMI thresholds: Demand a minimum trend strength and directional DI alignment to reduce whipsaw trades.
  - Trendline Breakout and Range Detector: Confirm that the price is breaking structure or remains within active range consistent with the leading setup.
- By combining several filters you can create strict, conservative entries or looser setups depending on your goals.
Range Filter Engine
- A core building block, the Range Filter uses conditional EMA and SMA functions to compute adaptive bands around a dynamic centerline. It supports two types:
  - Type 1: The centerline updates when price exceeds the band thresholds; bands define acceptable drift ranges.
  - Type 2: Uses quantized steps (via floor operations) relative to the previous centerline to handle larger moves in discrete increments.
- The engine offers smoothing for range values using a secondary EMA and can switch between raw and averaged outputs. Its hi/lo bands and centerline compose a corridor that defines directional movement and potential breakout confirmation.
Signal Construction
- The script computes:
  - leadinglongcond and leadingshortcond : The primary directional signals from the chosen leading indicator.
  - longCond and shortCond : Final signals formed by combining the leading conditions with all enabled confirmations. Each confirmation contributes a boolean gate. If a filter is disabled, it contributes a neutral pass-through, keeping the logic intact without enforcing that condition.
  - Expiry Logic: The code counts consecutive bars where the leading condition remains true. If confirmations do not line up within the user-defined “Signal Expiry Candle Count,” the setup is abandoned and the signal does not trigger.
  - Alternation: An optional state ensures that long and short signals alternate. This can reduce repeated entries in the same direction without a clear reset.
- Finally, longCondition and shortCondition represent the actionable signals after expiry and alternation logic. These drive the label plotting and alert conditions.
Visualization
- Buy and Sell Labels: When longCondition or shortCondition confirm, the script plots annotated labels directly on the chart, making entries easy to see at a glance. The labels use color coding and clear text tags (“long” vs. “short”).
- Dashboard: A table summarizes the status of the leading indicator and all confirmations. Each row shows the indicator label and whether it passed (✔️) or failed (❌) on the current bar. This intensely practical UI helps you diagnose why a signal did or did not trigger, empowering faster strategy iteration and parameter tuning.
- Failed Confirmation Markers: If a setup expires (count exceeds the limit) and confirmations failed to align, the script can mark the chart with a small label and provide a tooltip listing which confirmations did not pass. It’s a helpful audit trail to understand missed trades or prevent “chasing” invalid signals.
- Data Window Values: The script outputs signal states to the data window, which can be useful for debugging or building composite conditions in multi-indicator templates.
Inputs and Parameters
- You control the indicator from a comprehensive input panel:
  - Setup: Signal expiry count, whether to enforce alternating signals, and whether to display labels and the dashboard (including position and size).
  - Leading Indicator: Choose the primary signal generator from the large list.
  - Per-Filter Toggles: For each confirmation, a respect... toggle enables or disables it. Many include sub-options (like MACD type, Stochastic mode, RSI mode, ADX variants, thresholds for choppiness/volatility, etc.) to fine-tune behavior.
  - Range Filter Settings: Choose type and behavior; select default vs. DW mode and smoothing. The underlying functions adjust band sizes using ATR, average change, standard deviation, or user-defined scales.
- Because everything is customizable, you can adapt the indicator to different assets, volatility regimes, and timeframes.
Alerts and Automation
- The script defines alert conditions tied to longCondition and shortCondition . You can set these alerts in your chart to trigger notifications or webhook calls for automated execution in external bots. The alert text is simple, and you can configure your own message template when creating alerts in the chart, including JSON payloads for algorithmic integration.
Typical Workflow
- Select a Leading Indicator aligned with your style. For trend following, Supertrend or SSL may be appropriate; for momentum, MACD or TSI; for range/trend-change detection, Range Filter, RQK, or Donchian.
- Add a few key Confirmation Filters that complement the leading signal. For example:
  - Pair Supertrend with EMA Filter and RSI MA Direction to ensure trend alignment and positive momentum.
  - Combine MACD Crossover with ADX/DMI and Volume Above MA to avoid signals in low-trend or low-liquidity conditions.
  - Use RQK with Choppiness Index and Damiani Volatility to only act when the market is trending and volatile enough.
- Set a sensible Signal Expiry Candle Count. Shorter expiry keeps entries timely and reduces lag; longer expiry captures setups that mature slowly.
- Observe the Dashboard during live markets to see which filters pass or fail, then iterate. Tighten or loosen thresholds and filter combinations as needed.
- For automation, turn on alerts for the final conditions and use webhook payloads to notify your trading robot.
Strengths and Practical Notes
- Flexibility: The indicator is a toolkit rather than a single rigid model. It lets you test different combinations rapidly and visualize outcomes immediately.
- Clarity: Labels, dashboard, and failed-confirmation markers make it easy to audit behavior and refine settings without digging into code.
- Robustness: The expiry and alternation options add discipline, avoiding the temptation to enter late or repeatedly in one direction without a reset.
- Modular Design: The logical gates (“respect…”) make the behavior transparent: if a filter is on, it must pass; if it’s off, the signal ignores it. This keeps reasoning clean.
- Avoiding Overfitting: Because you can stack many filters, it’s tempting to over-constrain signals. Start simple (one leading indicator and one or two confirmations). Add complexity only if it demonstrably improves your edge across varied market regimes.
Limitations and Recommendations
- No single configuration is universally optimal. Markets change; tune filters for the instrument and timeframe you trade and revisit settings periodically.
- Trend filters can underperform in choppy markets; likewise, momentum filters can false-trigger in quiet periods. Consider using Choppiness Index or Damiani to gate signals by regime.
- Use expiry wisely. Too short may miss good setups that need a few bars to confirm; too long may cause late entries. Balance responsiveness and accuracy.
- Always consider risk management externally (position sizing, stops, profit targets). The indicator focuses on signal quality; combining it with robust trade management methods will improve results.
Example Configurations
- Trend-Following Setup:
  - Leading: Supertrend uptrend for longs and downtrend for shorts.
  - Confirmations: EMA Filter (price above 200 EMA for long, below for short), ADX/DMI (trend strength above threshold with +DI/-DI alignment), Volume Above MA.
  - Expiry: 3–4 bars to keep entries timely.
  - Result: Strong bias toward sustained moves while avoiding weak trends and thin liquidity.
- Mean-Reversion to Momentum Crossover:
  - Leading: RSI exits from OB/OS zones (e.g., RSI leaves oversold for long and leaves overbought for short).
  - Confirmations: 2 EMA Cross (fast crossing slow in the same direction), MACD zero-line behavior for added momentum validation.
  - Expiry: 2–3 bars for responsive re-entry.
  - Result: Captures momentum transitions after short-term extremes, with extra confirmation to reduce head-fakes.
- Range Breakout Focus:
  - Leading: Range Filter Type 2 or Donchian Trend Ribbon to detect breakouts.
  - Confirmations: Damiani Volatility (avoid low-volatility false breaks), Choppiness Index (prefer trend-ready states), ROC positive/negative threshold.
  - Expiry: 1–3 bars to act on breakout windows.
  - Result: Better alignment to breakout dynamics, gating trades by volatility and regime.
Conclusion
- This indicator is a comprehensive, configurable framework that merges a chosen leading signal with an array of corroborating filters, disciplined expiry handling, and intuitive visualization. It’s designed to help you build high-quality entry signals tailored to your approach, whether that’s trend-following, breakout trading, momentum capturing, or a hybrid. By surfacing pass/fail states in a dashboard and allowing alert-based automation, it bridges the gap between discretionary analysis and systematic execution. With sensible parameter tuning and thoughtful filter selection, it can serve as a robust backbone for signal generation across diverse instruments and timeframes.
Pivot Regime Anchored VWAP [CHE]  Pivot Regime Anchored VWAP   — Detects body-based pivot regimes to classify swing highs and lows, anchoring volume-weighted average price lines directly at higher highs and lower lows for adaptive reference levels.
  Summary 
This indicator identifies shifts between top and bottom regimes through breakouts in candle body highs and lows, labeling swing points as higher highs, lower highs, lower lows, or higher lows. It then draws anchored volume-weighted average price lines starting from the most recent higher high and lower low, providing dynamic support and resistance that evolve with volume flow. These anchored lines differ from standard volume-weighted averages by resetting only at confirmed swing extremes, reducing noise in ranging markets while highlighting momentum shifts in trends.
  Motivation: Why this design? 
Traders often struggle with static reference lines that fail to adapt to changing market structures, leading to false breaks in volatile conditions or missed continuations in trends. By anchoring volume-weighted average price calculations to body pivot regimes—specifically at higher highs for resistance and lower lows for support—this design creates reference levels tied directly to price structure extremes. This approach addresses the problem of generic moving averages lagging behind swing confirmations, offering a more context-aware tool for intraday or swing trading.
  What’s different vs. standard approaches? 
- Baseline reference: Traditional volume-weighted average price indicators compute a running total from session start or fixed periods, often ignoring price structure.
- Architecture differences:
  - Regime detection via body breakout logic switches between high and low focus dynamically.
  - Anchoring limited to confirmed higher highs and lower lows, with historical recalculation for accurate line drawing.
  - Polyline rendering rebuilds only on the last bar to manage performance.
- Practical effect: Charts show fewer, more meaningful lines that start at swing points, making it easier to spot confluences with structure breaks rather than cluttered overlays from continuous calculations.
  How it works (technical) 
The indicator first calculates the maximum and minimum of each candle's open and close to define body highs and lows. It then scans a lookback window for the highest body high and lowest body low. A top regime triggers when the body high from the lookback period exceeds the window's highest, and a bottom regime when the body low falls below the window's lowest. These regime shifts confirm pivots only when crossing from one state to the other.
For top pivots, it compares the new body high against the previous swing high: if greater, it marks a higher high and anchors a new line; otherwise, a lower high. The same logic applies inversely for bottom pivots. Anchored lines use cumulative price-volume products and volumes from the anchor bar onward, subtracting prior cumulatives to isolate the segment. On pivot confirmation, it loops backward from the current bar to the anchor, computing and storing points for the line. New points append as bars advance, ensuring the line reflects ongoing volume weighting.
Initialization uses persistent variables to track the last swing values and anchor bars, starting with neutral states. Data flows from regime detection to pivot classification, then to anchoring and point accumulation, with lines rendered globally on the final bar.
  Parameter Guide 
Pivot Length — Controls the lookback window for detecting body breakouts, influencing pivot frequency and sensitivity to recent action. Shorter values catch more pivots in choppy conditions; longer smooths for major swings. Default: 30 (bars). Trade-offs/Tips: Min 1; for intraday, try 10–20 to reduce lag but watch for noise; on daily, 50+ for stability.
Show Pivot Labels — Toggles display of text markers at swing points, aiding quick identification of higher highs, lower highs, lower lows, or higher lows. Default: true. Trade-offs/Tips: Disable in multi-indicator setups to declutter; useful for backtesting structure.
HH Color — Sets the line and label color for higher high anchored lines, distinguishing resistance levels. Default: Red (solid). Trade-offs/Tips: Choose contrasting hues for dark/light themes; pair with opacity for fills if added later.
LL Color — Sets the line and label color for lower low anchored lines, distinguishing support levels. Default: Lime (solid). Trade-offs/Tips: As above; green shades work well for bullish contexts without overpowering candles.
  Reading & Interpretation 
Higher high labels and red lines indicate potential resistance zones where volume weighting begins at a new swing top, suggesting sellers may defend prior highs. Lower low labels and lime lines mark support from a fresh swing bottom, with the line's slope reflecting buyer commitment via volume. Lower highs or higher lows appear as labels without new anchors, signaling possible range-bound action. Line proximity to price shows overextension; crosses may hint at regime shifts, but confirm with volume spikes.
  Practical Workflows & Combinations 
- Trend following: Enter longs above a rising lower low anchored line after higher low confirmation; filter with rising higher highs for uptrends. Use line breaks as trailing stops.
- Exits/Stops: In downtrends, exit shorts below a higher high line; set aggressive stops above it for scalps, conservative below for swings. Pair with momentum oscillators for divergence.
- Multi-asset/Multi-TF: Defaults suit forex/stocks on 1H–4H; on crypto 15M, shorten length to 15. Scale colors for dark themes; combine with higher timeframe anchors for confluence.
  Behavior, Constraints & Performance 
Closed-bar logic ensures pivots confirm after the lookback period, with no repainting on historical bars—live bars may adjust until regime shift. No higher timeframe calls, so minimal repaint risk beyond standard delays. Resources include a 2000-bar history limit, label/polyline caps at 200/50, and loops for historical point filling (up to current bar count from anchor, typically under 500 iterations). Known limits: In extreme gaps or low-volume periods, anchors may skew; lines absent until first pivots.
  Sensible Defaults & Quick Tuning 
Start with the 30-bar length for balanced pivot detection across most assets. For too-frequent pivots in ranges, increase to 50 for fewer signals. If lines lag in trends, reduce to 20 and enable labels for visual cues. In low-volatility assets, widen color contrasts; test on 100-bar history to verify stability.
  What this indicator is—and isn’t 
This is a structure-aware visualization layer for anchoring volume-weighted references at swing extremes, enhancing manual analysis of regimes and levels. It is not a standalone signal generator or predictive model—always integrate with broader context like order flow or news. Use alongside risk management and position sizing, not as isolated buy/sell triggers.
Many thanks to LuxAlgo for the original script "McDonald's Pattern  ". The implementation for body pivots instead of wicks uses a = max(open, close), b = min(open, close) and then highest(a, length) / lowest(b, length). This filters noise from the wicks and detects breakouts over/under bodies. Unusual and targeted, super innovative.
  Disclaimer 
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
 Best regards and happy trading
Chervolino
AUTOMATIC ANALYSIS MODULE🧭 Overview
“Automatic Analysis Module” is a professional, multi-indicator system that interprets market conditions in real time using TSI, RSI, and ATR metrics.
It automatically detects trend reversals, volatility compressions, and momentum exhaustion, helping traders identify high-probability setups without manual analysis.
⚙️ Core Logic
The script continuously evaluates:
TSI (True Strength Index) → trend direction, strength, and early reversal zones.
RSI (Relative Strength Index) → momentum extremes and technical divergences.
ATR (Average True Range) → volatility expansion or compression phases.
Multi-timeframe ATR comparison → detects whether the weekly structure supports or contradicts the local move.
The system combines these signals to produce an automatic interpretation displayed directly on the chart.
📊 Interpretation Table
At every new bar close, the indicator updates a compact dashboard (bottom right corner) showing:
🔵 Main interpretation → trend, reversal, exhaustion, or trap scenario.
🟢 Micro ATR context → volatility check and flow analysis (stable / expanding / contracting).
Each condition is expressed in plain English for quick decision-making — ideal for professional traders who manage multiple charts.
📈 How to Use
1️⃣ Load the indicator on your preferred asset and timeframe (recommended: Daily or 4H).
2️⃣ Watch the blue line message for the main trend interpretation.
3️⃣ Use the green line message as a volatility gauge before entering.
4️⃣ Confirm entries with your own strategy or price structure.
Typical examples:
“Possible bullish reversal” → early accumulation signal.
“Compression phase → wait for breakout” → avoid premature trades.
“Confirmed uptrend” → trend continuation zone.
⚡ Key Features
Real-time auto-interpretation of TSI/RSI/ATR signals.
Detects both bull/bear traps and trend exhaustion zones.
Highlights volatility transitions before breakouts occur.
Works across all assets and timeframes.
No repainting — stable on historical data.
✅ Ideal For
Swing traders, position traders, and institutional analysts who want automated context recognition instead of manual indicator reading.
Historical Matrix Analyzer [PhenLabs]📊Historical Matrix Analyzer  
 Version:  PineScriptv6
 📌Description 
The Historical Matrix Analyzer is an advanced probabilistic trading tool that transforms technical analysis into a data-driven decision support system. By creating a comprehensive 56-cell matrix that tracks every combination of RSI states and multi-indicator conditions, this indicator reveals which market patterns have historically led to profitable outcomes and which have not.
At its core, the indicator continuously monitors seven distinct RSI states (ranging from Extreme Oversold to Extreme Overbought) and eight unique indicator combinations (MACD direction, volume levels, and price momentum). For each of these 56 possible market states, the system calculates average forward returns, win rates, and occurrence counts based on your configurable lookback period. The result is a color-coded probability matrix that shows you exactly where you stand in the historical performance landscape.
The standout feature is the Current State Panel, which provides instant clarity on your active market conditions. This panel displays signal strength classifications (from Strong Bullish to Strong Bearish), the average return percentage for similar past occurrences, an estimated win rate using Bayesian smoothing to prevent small-sample distortions, and a confidence level indicator that warns you when insufficient data exists for reliable conclusions.
 🚀Points of Innovation 
 
 Multi-dimensional state classification combining 7 RSI levels with 8 indicator combinations for 56 unique trackable market conditions
 Bayesian win rate estimation with adjustable smoothing strength to provide stable probability estimates even with limited historical samples
 Real-time active cell highlighting with “NOW” marker that visually connects current market conditions to their historical performance data
 Configurable color intensity sensitivity allowing traders to adjust heat-map responsiveness from conservative to aggressive visual feedback
 Dual-panel display system separating the comprehensive statistics matrix from an easy-to-read current state summary panel
 Intelligent confidence scoring that automatically warns traders when occurrence counts fall below reliable thresholds
 
 🔧Core Components 
 
 RSI State Classification:  Segments RSI readings into 7 distinct zones (Extreme Oversold <20, Oversold 20-30, Weak 30-40, Neutral 40-60, Strong 60-70, Overbought 70-80, Extreme Overbought >80) to capture momentum extremes and transitions
 Multi-Indicator Condition Tracking:  Simultaneously monitors MACD crossover status (bullish/bearish), volume relative to moving average (high/low), and price direction (rising/falling) creating 8 binary-encoded combinations
 Historical Data Storage Arrays:  Maintains rolling lookback windows storing RSI states, indicator states, prices, and bar indices for precise forward-return calculations
 Forward Performance Calculator:  Measures price changes over configurable forward bar periods (1-20 bars) from each historical state, accumulating total returns and win counts per matrix cell
 Bayesian Smoothing Engine:  Applies statistical prior assumptions (default 50% win rate) weighted by user-defined strength parameter to stabilize estimated win rates when sample sizes are small
 Dynamic Color Mapping System:  Converts average returns into color-coded heat map with intensity adjusted by sensitivity parameter and transparency modified by confidence levels
 
 🔥Key Features 
 
 56-Cell Probability Matrix:  Comprehensive grid displaying every possible combination of RSI state and indicator condition, with each cell showing average return percentage, estimated win rate, and occurrence count for complete statistical visibility
 Current State Info Panel:  Dedicated display showing your exact position in the matrix with signal strength emoji indicators, numerical statistics, and color-coded confidence warnings for immediate situational awareness
 Customizable Lookback Period:  Adjustable historical window from 50 to 500 bars allowing traders to focus on recent market behavior or capture longer-term pattern stability across different market cycles
 Configurable Forward Performance Window:  Select target holding periods from 1 to 20 bars ahead to align probability calculations with your trading timeframe, whether day trading or swing trading
 Visual Heat Mapping:  Color-coded cells transition from red (bearish historical performance) through gray (neutral) to green (bullish performance) with intensity reflecting statistical significance and occurrence frequency
 Intelligent Data Filtering:  Minimum occurrence threshold (1-10) removes unreliable patterns with insufficient historical samples, displaying gray warning colors for low-confidence cells
 Flexible Layout Options:  Independent positioning of statistics matrix and info panel to any screen corner, accommodating different chart layouts and personal preferences
 Tooltip Details:  Hover over any matrix cell to see full RSI label, complete indicator status description, precise average return, estimated win rate, and total occurrence count
 
 🎨Visualization 
 
 Statistics Matrix Table:  A 9-column by 8-row grid with RSI states labeling vertical axis and indicator combinations on horizontal axis, using compact abbreviations (XOverS, OverB, MACD↑, Vol↓, P↑) for space efficiency
 Active Cell Indicator:  The current market state cell displays “⦿ NOW ⦿” in yellow text with enhanced color saturation to immediately draw attention to relevant historical performance
 Signal Strength Visualization:  Info panel uses emoji indicators (🔥 Strong Bullish, ✅ Bullish, ↗️ Weak Bullish, ➖ Neutral, ↘️ Weak Bearish, ⛔ Bearish, ❄️ Strong Bearish, ⚠️ Insufficient Data) for rapid interpretation
 Histogram Plot:  Below the price chart, a green/red histogram displays the current cell’s average return percentage, providing a time-series view of how historical performance changes as market conditions evolve
 Color Intensity Scaling:  Cell background transparency and saturation dynamically adjust based on both the magnitude of average returns and the occurrence count, ensuring visual emphasis on reliable patterns
 Confidence Level Display:  Info panel bottom row shows “High Confidence” (green), “Medium Confidence” (orange), or “Low Confidence” (red) based on occurrence counts relative to minimum threshold multipliers
 
 📖Usage Guidelines 
 RSI Period 
 
 Default: 14
 Range: 1 to unlimited
 Description: Controls the lookback period for RSI momentum calculation. Standard 14-period provides widely-recognized overbought/oversold levels. Decrease for faster, more sensitive RSI reactions suitable for scalping. Increase (21, 28) for smoother, longer-term momentum assessment in swing trading. Changes affect how quickly the indicator moves between the 7 RSI state classifications.
 
 MACD Fast Length 
 
 Default: 12
 Range: 1 to unlimited
 Description: Sets the faster exponential moving average for MACD calculation. Standard 12-period setting works well for daily charts and captures short-term momentum shifts. Decreasing creates more responsive MACD crossovers but increases false signals. Increasing smooths out noise but delays signal generation, affecting the bullish/bearish indicator state classification.
 
 MACD Slow Length 
 
 Default: 26
 Range: 1 to unlimited
 Description: Defines the slower exponential moving average for MACD calculation. Traditional 26-period setting balances trend identification with responsiveness. Must be greater than Fast Length. Wider spread between fast and slow increases MACD sensitivity to trend changes, impacting the frequency of indicator state transitions in the matrix.
 
 MACD Signal Length 
 
 Default: 9
 Range: 1 to unlimited
 Description: Smoothing period for the MACD signal line that triggers bullish/bearish state changes. Standard 9-period provides reliable crossover signals. Shorter values create more frequent state changes and earlier signals but with more whipsaws. Longer values produce more confirmed, stable signals but with increased lag in detecting momentum shifts.
 
 Volume MA Period 
 
 Default: 20
 Range: 1 to unlimited
 Description: Lookback period for volume moving average used to classify volume as “high” or “low” in indicator state combinations. 20-period default captures typical monthly trading patterns. Shorter periods (10-15) make volume classification more reactive to recent spikes. Longer periods (30-50) require more sustained volume changes to trigger state classification shifts.
 
 Statistics Lookback Period 
 
 Default: 200
 Range: 50 to 500
 Description: Number of historical bars used to calculate matrix statistics. 200 bars provides substantial data for reliable patterns while remaining responsive to regime changes. Lower values (50-100) emphasize recent market behavior and adapt quickly but may produce volatile statistics. Higher values (300-500) capture long-term patterns with stable statistics but slower adaptation to changing market dynamics.
 
 Forward Performance Bars 
 
 Default: 5
 Range: 1 to 20
 Description: Number of bars ahead used to calculate forward returns from each historical state occurrence. 5-bar default suits intraday to short-term swing trading (5 hours on hourly charts, 1 week on daily charts). Lower values (1-3) target short-term momentum trades. Higher values (10-20) align with position trading and longer-term pattern exploitation.
 
 Color Intensity Sensitivity 
 
 Default: 2.0
 Range: 0.5 to 5.0, step 0.5
 Description: Amplifies or dampens the color intensity response to average return magnitudes in the matrix heat map. 2.0 default provides balanced visual emphasis. Lower values (0.5-1.0) create subtle coloring requiring larger returns for full saturation, useful for volatile instruments. Higher values (3.0-5.0) produce vivid colors from smaller returns, highlighting subtle edges in range-bound markets.
 
 Minimum Occurrences for Coloring 
 
 Default: 3
 Range: 1 to 10
 Description: Required minimum sample size before applying color-coded performance to matrix cells. Cells with fewer occurrences display gray “insufficient data” warning. 3-occurrence default filters out rare patterns. Lower threshold (1-2) shows more data but includes unreliable single-event statistics. Higher thresholds (5-10) ensure only well-established patterns receive visual emphasis.
 
 Table Position 
 
 Default: top_right
 Options: top_left, top_right, bottom_left, bottom_right
 Description: Screen location for the 56-cell statistics matrix table. Position to avoid overlapping critical price action or other indicators on your chart. Consider chart orientation and candlestick density when selecting optimal placement.
 
 Show Current State Panel 
 
 Default: true
 Options: true, false
 Description: Toggle visibility of the dedicated current state information panel. When enabled, displays signal strength, RSI value, indicator status, average return, estimated win rate, and confidence level for active market conditions. Disable to declutter charts when only the matrix table is needed.
 
 Info Panel Position 
 
 Default: bottom_left
 Options: top_left, top_right, bottom_left, bottom_right
 Description: Screen location for the current state information panel (when enabled). Position independently from statistics matrix to optimize chart real estate. Typically placed opposite the matrix table for balanced visual layout.
 
 Win Rate Smoothing Strength 
 
 Default: 5
 Range: 1 to 20
 Description: Controls Bayesian prior weighting for estimated win rate calculations. Acts as virtual sample size assuming 50% win rate baseline. Default 5 provides moderate smoothing preventing extreme win rate estimates from small samples. Lower values (1-3) reduce smoothing effect, allowing win rates to reflect raw data more directly. Higher values (10-20) increase conservatism, pulling win rate estimates toward 50% until substantial evidence accumulates.
 
 ✅Best Use Cases 
 
 Pattern-based discretionary trading where you want historical confirmation before entering setups that “look good” based on current technical alignment
 Swing trading with holding periods matching your forward performance bar setting, using high-confidence bullish cells as entry filters
 Risk assessment and position sizing, allocating larger size to trades originating from cells with strong positive average returns and high estimated win rates
 Market regime identification by observing which RSI states and indicator combinations are currently producing the most reliable historical patterns
 Backtesting validation by comparing your manual strategy signals against the historical performance of the corresponding matrix cells
 Educational tool for developing intuition about which technical condition combinations have actually worked versus those that feel right but lack historical evidence
 
 ⚠️Limitations 
 
 Historical patterns do not guarantee future performance, especially during unprecedented market events or regime changes not represented in the lookback period
 Small sample sizes (low occurrence counts) produce unreliable statistics despite Bayesian smoothing, requiring caution when acting on low-confidence cells
 Matrix statistics lag behind rapidly changing market conditions, as the lookback period must accumulate new state occurrences before updating performance data
 Forward return calculations use fixed bar periods that may not align with actual trade exit timing, support/resistance levels, or volatility-adjusted profit targets
 
 💡What Makes This Unique 
 
 Multi-Dimensional State Space:  Unlike single-indicator tools, simultaneously tracks 56 distinct market condition combinations providing granular pattern resolution unavailable in traditional technical analysis
 Bayesian Statistical Rigor:  Implements proper probabilistic smoothing to prevent overconfidence from limited data, a critical feature missing from most pattern recognition tools
 Real-Time Contextual Feedback:  The “NOW” marker and dedicated info panel instantly connect current market conditions to their historical performance profile, eliminating guesswork
 Transparent Occurrence Counts:  Displays sample sizes directly in each cell, allowing traders to judge statistical reliability themselves rather than hiding data quality issues
 Fully Customizable Analysis Window:  Complete control over lookback depth and forward return horizons lets traders align the tool precisely with their trading timeframe and strategy requirements
 
 🔬How It Works 
 1. State Classification and Encoding 
 
 Each bar’s RSI value is evaluated and assigned to one of 7 discrete states based on threshold levels (0: <20, 1: 20-30, 2: 30-40, 3: 40-60, 4: 60-70, 5: 70-80, 6: >80)
 Simultaneously, three binary conditions are evaluated: MACD line position relative to signal line, current volume relative to its moving average, and current close relative to previous close
 These three binary conditions are combined into a single indicator state integer (0-7) using binary encoding, creating 8 possible indicator combinations
 The RSI state and indicator state are stored together, defining one of 56 possible market condition cells in the matrix
 
 2. Historical Data Accumulation 
 
 As each bar completes, the current state classification, closing price, and bar index are stored in rolling arrays maintained at the size specified by the lookback period
 When the arrays reach capacity, the oldest data point is removed and the newest added, creating a sliding historical window
 This continuous process builds a comprehensive database of past market conditions and their subsequent price movements
 
 3. Forward Return Calculation and Statistics Update 
 
 On each bar, the indicator looks back through the stored historical data to find bars where sufficient forward bars exist to measure outcomes
 For each historical occurrence, the price change from that bar to the bar N periods ahead (where N is the forward performance bars setting) is calculated as a percentage return
 This percentage return is added to the cumulative return total for the specific matrix cell corresponding to that historical bar’s state classification
 Occurrence counts are incremented, and wins are tallied for positive returns, building comprehensive statistics for each of the 56 cells
 The Bayesian smoothing formula combines these raw statistics with prior assumptions (neutral 50% win rate) weighted by the smoothing strength parameter to produce estimated win rates that remain stable even with small samples
 
 💡Note: 
The Historical Matrix Analyzer is designed as a decision support tool, not a standalone trading system. Best results come from using it to validate discretionary trade ideas or filter systematic strategy signals. Always combine matrix insights with proper risk management, position sizing rules, and awareness of broader market context. The estimated win rate feature uses Bayesian statistics specifically to prevent false confidence from limited data, but no amount of smoothing can create reliable predictions from fundamentally insufficient sample sizes. Focus on high-confidence cells (green-colored confidence indicators) with occurrence counts well above your minimum threshold for the most actionable insights.
Hyper Strength Index | QuantLapse🧠 Hyper Strength Index (HSI) | QuantLapse 
 Overview: 
The Hyper Strength Index (HSI) is a composite momentum oscillator designed to unify multiple strength measures into a single, adaptive framework. It combines the Relative Strength Index (RSI), Chande Momentum Oscillator (CMO), Money Flow Index (MFI), and Stochastic RSI to deliver a refined, multidimensional view of market momentum and overbought/oversold conditions.
Unlike traditional oscillators that rely on a single formula, the HSI averages four distinct momentum perspectives — price velocity, directional conviction, volume participation, and stochastic behavior — offering traders a more balanced and noise-resistant reading of market strength.
 ⚙️ Calculation Logic: 
The Hyper Strength Index is computed as the normalized average of:
 
 📈 RSI — classic measure of relative momentum.
 💪 CMO — captures directional bias and intensity of moves.
 💵 MFI — integrates volume and money flow pressure.
 🔄 Stochastic RSI (K-line) — identifies momentum extremes and short-term turning points.
 
This fusion creates a smoother, more comprehensive signal, mitigating the weaknesses of any single oscillator.
 🎯 Interpretation: 
Overbought Zone (Default: > 75):
Indicates potential exhaustion of bullish momentum — a cooling phase or reversal may follow.
Oversold Zone (Default: < 7):
Suggests bearish exhaustion — a rebound or accumulation phase may emerge.
Neutral Zone (Between 7 and 75):
Represents balanced market conditions or trend continuation phases.
Visual cues highlight key conditions:
🔺 Red Highlights — Overbought regions or downward inflection points.
🔻 Green Highlights — Oversold regions or upward inflection points.
Neutral zones are shaded with subtle gray backgrounds for clarity.
 💡 Key Features: 
🔹 Multi-factor strength analysis (RSI + CMO + MFI + StochRSI).
🔹 Adaptive overbought/oversold detection.
🔹 Visual alerts via colored backgrounds and bar markers.
🔹 Customizable smoothing and length parameters for fine-tuning sensitivity.
🔹 Intuitive visualization ideal for both short-term scalping and swing trading setups.
🧭 Usage Notes:
Works best as a momentum confirmation tool — pair with trend filters like EMA, SuperTrend, or ADX.
In trending markets, use crossovers from extreme zones as potential continuation or exhaustion signals.
In ranging markets, exploit overbought/oversold reversals for high-probability mean reversion trades.
📘 Summary:
The Hyper Strength Index | QuantLapse distills multiple dimensions of market strength into a single, cohesive oscillator. By merging price, volume, and directional momentum, it provides traders with a more robust, responsive, and context-aware perspective on market dynamics — a next-generation evolution beyond the limitations of RSI or CMO alone.
Smart Money Dynamics Blocks — Pearson MatrixSmart Money Dynamics Blocks — Pearson Matrix 
A structural fusion of Prime Number Theory, Pearson Correlation, and Cumulative Delta Geometry.
 1. Mathematical Foundation 
This indicator is built on the intersection of Prime Number Theory and the Pearson correlation coefficient, creating a structural framework that quantifies how price and time evolve together.
Prime numbers — unique, indivisible, and irregular — are used here as nonlinear time intervals. Each prime length (2, 3, 5, 7, 11…97) represents a regression horizon where correlation is measured between price and time. The result is a multi-scale correlation lattice — a geometric matrix that captures hidden directional strength and temporal bias beyond traditional moving averages.
 2. The Pearson Matrix Logic 
For every prime interval p, the indicator calculates the linear correlation:
 r_p = corr(price, bar_index, p) 
Each r_p reflects how closely price and time move together across a prime-defined window. All r_p values are then averaged to create avgR, a single adaptive coefficient summarizing overall structural coherence.
 - When avgR > 0.8 → strong positive correlation (labeled R+).
- When avgR < -0.8 → strong negative correlation (labeled R−). 
This approach gives a mathematically grounded definition of trend — one that isn’t based on pattern recognition, but on measurable correlation strength.
 3. Sequential Prime Slope and Median Pivot 
Using the ordered sequence of 25 prime intervals, the model computes sequential slopes between adjacent primes. These slopes represent the rate of change of structure between two prime scales. A robust median aggregator smooths the slopes, producing a clean, stable directional vector.
The system anchors this slope to the 41-bar pivot — the median of the first 25 primes — serving as the geometric midpoint of the prime lattice. The resulting yellow line on the chart is not an ordinary regression line; it’s a dynamic prime-slope function, adapting continuously with correlation feedback.
 4. Regression-Style Parallel Bands 
Around this prime-slope line, the indicator constructs parallel bands using standard deviation envelopes — conceptually similar to a regression channel but recalculated through the prime–Pearson matrix.
These bands adjust dynamically to:
 - Volatility, via standard deviation of residuals.
- Correlation strength, via avgR sign weighting. 
Together, they visualize statistical deviation geometry, making it easier to observe symmetry, expansion, and contraction phases of price structure.
 5. Volume and Cumulative Delta Peaks 
Below the geometric layer, the indicator incorporates a custom lower-timeframe volume feed — by default using 15-second data  (custom_tf_input_volume = “15S”).  This allows precise delta computation between up-volume and down-volume even on higher timeframe charts.
From this feed, the indicator accumulates delta over a configurable period (default: 100 bars). When cumulative delta reaches a local maximum or minimum, peak and trough markers appear, showing the precise bar where buying or selling pressure statistically peaked.
This combination of geometry and order flow reveals the intersection of market structure and energy — where liquidity pressure expresses itself through mathematical form.
 6. Chart Interpretation 
The primary chart view represents the live execution of the indicator. It displays the relationship between structural correlation and volume behavior in real time.
Orange “R+” and blue “R−” labels indicate regions of strong positive or negative Pearson correlation across the prime matrix. The yellow median prime-slope line serves as the structural backbone of the indicator, while green and red parallel bands act as dynamic regression boundaries derived from the underlying correlation strength. Peaks and troughs in cumulative delta — displayed as numerical annotations — mark statistically significant shifts in buying and selling pressure.
  
The secondary visualization (Prime Regression Concept) expands on this by illustrating how regression behavior evolves across prime intervals. Each colored regression fan corresponds to a prime number window (2, 3, 5, 7, …, 97), demonstrating how multiple regression lines would appear if drawn independently. The indicator integrates these into one unified geometric model — eliminating the need to plot tens of regression lines manually. It’s a conceptual tool to help visualize the internal logic: the synthesis of many small-scale regressions into a single coherent structure.
 7. Interpretive Insight 
This model is not a prediction tool; it’s an instrument of mathematical observation. By translating price dynamics into a prime-structured correlation space, it reveals how coherence unfolds through time — not as a forecast, but as a measurable evolution of structure.
It unifies three analytical domains:
 - Prime distribution — defines a nonlinear temporal architecture.
- Pearson correlation — quantifies statistical cohesion.
- Cumulative delta — expresses behavioral imbalance in order flow. 
The synthesis creates a geometric analysis of liquidity and time — where structure meets energy, and where the invisible rhythm of market flow becomes measurable.
 8. Contribution & Feedback 
Share your observations in the comments:
 - The time gap and alternation between R+ and R− clusters.
- How different timeframes change delta sensitivity or reveal compression/expansion.
- Prime intervals/clusters that tend to sit near turning points or liquidity shifts.
- How avgR behaves across assets or regimes (trending, ranging, high-vol).
- Notable interactions with the parallel bands (touches, breaks, mean-revert). 
Your field notes help others read the model more effectively and compare contexts.
 Summary
 - Primes define the structure.
- Pearson quantifies coherence.
- Slope median stabilizes geometry.
- Regression bands visualize deviation.
- Cumulative delta locates imbalance.
 Together, they construct a framework where mathematics meets market behavior. 
ICT HTF Volume Candles (Based on HTF Candles by Fadi)# ICT HTF Volume Candles - Multi-Timeframe Volume Analysis
## Overview
This indicator provides multi-timeframe volume visualization designed to complement price action analysis. It displays volume data from up to 6 higher timeframes simultaneously in a separate panel, allowing traders to identify volume spikes, divergences, and institutional activity without switching between timeframes.
**Original Concept Credits:** This indicator builds upon the HTF Candles framework by Fadi, adapting it specifically for volume analysis with enhanced features including gap-filling for extended hours, multiple scaling methods, and advanced synchronization.
## What Makes This Script Original
### Key Innovations:
1. **Three Volume Scaling Methods:**
   - **Per-HTF Auto Scale:** Each timeframe scales independently for detailed comparison
   - **Global Auto Scale:** All timeframes use unified scale for relative volume comparison
   - **Manual Scale:** User-defined maximum for consistent analysis across sessions
2. **Bullish/Bearish Volume Differentiation:**
   - Volume bars colored based on price movement (close vs open)
   - Separate styling for bullish (green) and bearish (red) volume periods
   - Helps identify whether volume supports price direction
3. **Advanced Time Synchronization:**
   - Custom daily candle open times (Midnight, 8:30 AM, 9:30 AM ET)
   - Timezone-aware calculations for New York trading hours
   - Real-time countdown timers for each timeframe
   - **Gap-filling technology** for continuous display during extended hours and weekends
4. **Flexible Display Options:**
   - Configurable spacing and positioning
   - Label placement (top, bottom, or both)
   - Day-of-week or time interval labels on candles
   - Works reliably in backtesting and live trading
## How It Works
### Volume Calculation
The indicator uses `request.security()` with optimized parameters to fetch volume data from higher timeframes:
- **Volume Open/High/Low/Close (OHLC):** Tracks volume changes within each HTF candle
- **Color Logic:** Compares HTF close vs open prices to determine bullish/bearish classification
- **Alignment:** All volume bars share a common baseline for easy visual comparison
- **Gap Handling:** Uses `gaps=barmerge.gaps_off` to maintain continuity during non-trading hours
### Technical Implementation
```
1. Monitors HTF timeframe changes using request.security() with lookahead
2. Creates new VolumeCandle object when HTF bar opens
3. Updates current candle's volume H/L/C on each chart bar
4. Applies selected scaling method to normalize display height
5. Repositions all candles and labels on each bar update
6. Fills gaps automatically during extended hours for consistent display
```
### Scaling Methods Explained
**Method 1 - Auto Scale per HTF:**
Each timeframe displays volume relative to its own maximum. Best for identifying patterns within each individual timeframe.
**Method 2 - Global Auto Scale:**
All timeframes share the same scale based on the highest volume across all HTFs. Best for comparing relative volume strength between timeframes.
**Method 3 - Manual Scale:**
User sets maximum volume value. Best for maintaining consistent scale across different trading sessions or instruments.
## How to Use This Indicator
### Setup
1. Add indicator to your chart (it appears in a separate panel below price)
2. Configure up to 6 higher timeframes (default: 5m, 15m, 1H, 4H, 1D, 1W)
3. Set number of candles to display for each timeframe
4. Choose volume scaling method based on your analysis needs
5. Enable "Fix gaps in non-trading hours" for extended hours trading (enabled by default)
### Interpretation
**Volume Spikes:**
- Sudden increase in volume height indicates institutional activity or strong conviction
- Compare volume between timeframes to identify where the real money is moving
- Look for volume spikes that appear across multiple timeframes simultaneously
**Bullish vs Bearish Volume:**
- **Green volume bars:** Price closed higher (buying pressure)
- **Red volume bars:** Price closed lower (selling pressure)
- High green volume during uptrend = confirmation of strength
- High red volume during downtrend = confirmation of weakness
- High volume opposite to trend = potential reversal warning
**Multi-Timeframe Context:**
- **5m/15m:** Scalping and day trading activity
- **1H/4H:** Swing trading and intraday institutional flows
- **Daily/Weekly:** Major position building and long-term trends
**Divergences:**
- Price making new highs but volume declining = weakening trend
- Volume increasing while price consolidates = potential breakout brewing
- Price breaks level but volume doesn't confirm = likely false breakout
### Practical Examples
**Example 1 - Institutional Confirmation:**
Price breaks above resistance. Check volume across timeframes:
- 5m shows spike = retail interest
- 15m + 1H + 4H all show spikes = institutional confirmation
- **Trade confidence: HIGH**
**Example 2 - False Breakout Detection:**
Price breaks resistance with:
- High volume on 5m only
- Normal/low volume on 1H and 4H
- **Interpretation:** Likely retail trap, institutions not participating
- **Action:** Wait for pullback or avoid
**Example 3 - Accumulation Phase:**
Price ranges sideways but:
- Daily volume gradually increasing
- Weekly volume above average
- **Interpretation:** Smart money accumulating
- **Action:** Prepare for breakout in direction of volume
**Example 4 - Volume Divergence:**
Price makes new high:
- Current high has lower volume than previous high across all timeframes
- **Interpretation:** Weakening momentum
- **Action:** Consider profit-taking or reversal trade
## Configuration Parameters
### Timeframe Settings
- **HTF 1-6:** Select timeframes (must be higher than chart timeframe)
- **Max Display:** Number of candles to show per timeframe (1-50)
- **Limit to Next HTFs:** Display only first N enabled timeframes (1-6)
### Styling
- **Bull/Bear Colors:** Separate colors for body, border, and wick
- **Padding from current candles:** Distance offset from live price action
- **Space between candles:** Gap between individual volume bars
- **Space between Higher Timeframes:** Gap between different timeframe groups
- **Candle Width:** Thickness of volume bars (1-4, multiplied by 2)
### Volume Settings
- **Volume Scale Method:** Choose 1, 2, or 3
  - 1 = Auto Scale per HTF (each TF independent)
  - 2 = Global Auto Scale (all TF unified)
  - 3 = Manual Scale (user-defined max)
- **Auto Scale Volume:** Enable/disable automatic scaling
- **Manual Scale Max Volume:** Set maximum when using Method 3
### Label Settings
- **HTF Label:** Show/hide timeframe names with color and size options
- **Label Positions:** Display at Top, Bottom, or Both
- **Label Alignment:** Align centered or Follow Candles
- **Remaining Time:** Show countdown timer until next HTF candle
- **Interval Value:** Display day-of-week or time on each candle
### Custom Daily Candle
- **Enable Custom Daily:** Override default daily candle timing
- **Open Time Options:**
  - **Midnight:** Standard 00:00 ET daily open
  - **8:30 AM:** Align with economic data releases
  - **9:30 AM:** Align with NYSE market open
- Useful for specific trading strategies or market alignment
### Advanced Settings
- **Fix gaps in non-trading hours:** Maintains alignment during extended hours and weekends (recommended: ON)
  - Prevents visual gaps during forex weekend closures
  - Ensures consistent display during crypto 24/7 trading
  - Improves backtesting reliability
## Best Practices
1. **Pair with Price Action:** Use alongside HTF price candles indicator for complete picture
2. **Start Simple:** Enable 2-3 timeframes initially (e.g., 15m, 1H, 4H), add more as needed
3. **Match Settings:** Use same candle width/spacing as companion price indicator for visual alignment
4. **Scale Appropriately:** 
   - Use **Global scale** (Method 2) when comparing timeframes
   - Use **Per-HTF scale** (Method 1) for pattern analysis within each timeframe
   - Use **Manual scale** (Method 3) for consistent day-to-day comparison
5. **Watch for Volume Clusters:** High volume appearing simultaneously across multiple HTFs signals significant market events
6. **Confirm Breakouts:** Always check if volume supports the price movement across higher timeframes
7. **Extended Hours:** Keep "Fix gaps" enabled for 24/7 markets (Forex, Crypto) and weekend analysis
## Technical Notes
- **Timezone:** All calculations use America/New_York timezone for consistency
- **Real-time Updates:** Volume and timers update on each tick during market hours
- **Performance:** Optimized with max_bars_back=5000 for extensive historical analysis
- **Compatibility:** Works on all instruments with volume data (Stocks, Forex, Crypto, Futures)
- **Gap Handling:** Uses `barmerge.gaps_off` to fill data gaps during non-trading periods
- **Backtesting:** Uses `lookahead=barmerge.lookahead_on` for stable historical data without repainting
- **Data Continuity:** Automatically handles market closures, weekends, and extended hours
## Updates & Improvements
**Version 2.0 (Current):**
- ✅ Fixed alignment issues during extended hours and weekends
- ✅ Eliminated repainting in backtesting
- ✅ Added gap-filling technology for continuous display
- ✅ Improved data synchronization across all timeframes
- ✅ Enhanced NA value handling for data integrity
- ✅ Added advanced settings group for user control
## Support
For questions, suggestions, or feedback, please comment on the publication or message the author.
---
**Disclaimer:** This indicator is for educational and informational purposes only. It does not constitute financial advice. Past performance is not indicative of future results. Always perform your own analysis and implement proper risk management before making trading decisions.
  
Power Zone Trader (PZT)The PZT Indicator (Power Zone Trader ) is a multi-timeframe confluence system designed to identify and visualize natural support and resistance levels with exceptional clarity. By automatically mapping key structural highs and lows from higher timeframes, PZT allows traders to see where price is most likely to react, reverse, or accelerate, forming the foundation for high-probability trade setups. PZT highlights key reaction zones that influence order flow and trader behavior across all markets — including Forex, Crypto, Indices, and Commodities.
📍 Indicator Key
Each color represents a significant price level derived from its respective timeframe, helping traders instantly gauge market context and potential liquidity pools:
Color	Level Represented	Significance
🔴 Red Yearly High 	Strong resistance — potential selling pressure and major liquidity sweep zones.
🟢 Green	Yearly Low	Strong support — potential buying interest and accumulation points.
🟠 Orange Monthly High  Intermediate resistance — swing rejection or continuation decision zone.
🔵 Blue	Monthly Low	Intermediate support — potential retracement or base-building area.
🟣 Purple Weekly High	Short-term resistance — common rejection level or stop hunt zone.
🟤 Teal	Weekly Low	Short-term support — potential rebound or liquidity grab.
⚫ Gray	Daily High	Intraday resistance — active scalper and day trader interest.
⚪ White	Daily Low	Intraday support — short-term bounce or continuation pivot.
Timebender – 369 PivotsTimebender – 369 Pivots is a clean visual study that marks swing highs and lows with numeric “369-sequence” digits derived from time.
Each digit is automatically color-coded into Accumulation (1 – 3), Manipulation (4 – 6), and Distribution (7 – 9) phases, helping traders identify rhythm and symmetry in market structure.
Labels float above or below bars for clear visibility and never overlap price, allowing smooth zoom and multi-timeframe use.
This base model focuses on clarity, precision, and efficient plotting — no toggles, no clutter — a stable foundation for future Timebender builds.
Timebender - Sum of TimeTimebender – Sum of Time 
A minimalist numerological clock that decodes the vibration of the moment.
It calculates and displays the digital sum of the current date and time, assigning colors based on the 1–3 (Accumulation), 4–6 (Manipulation), and 7–9 (Distribution) cycle.
Clean, efficient, and fully synchronized with your chart’s timezone.
Daily Levels: PD / PM / OR (RTH/Pre)# Daily Levels: PD / PM / OR (RTH/Pre)
## Overview
This indicator displays key intraday support and resistance levels for US equity markets, specifically designed for traders who use Previous Day, Pre-Market, and Opening Range levels in their trading strategy.
## Key Features
**Seven Critical Levels Displayed:**
- **PDH (Previous Day High)** - Blue line: The highest price from yesterday's regular trading hours (9:30 AM - 4:00 PM ET)
- **PDL (Previous Day Low)** - Blue line: The lowest price from yesterday's regular trading hours
- **PDC (Previous Day Close)** - Orange line: The closing price from yesterday's regular trading hours
- **PMH (Pre-Market High)** - Yellow line: The highest price during today's pre-market session (4:00 AM - 9:30 AM ET)
- **PML (Pre-Market Low)** - Yellow line: The lowest price during today's pre-market session
- **ORH (Opening Range High)** - Red line: The highest price during the first 30 minutes of trading (9:30 AM - 10:00 AM ET)
- **ORL (Opening Range Low)** - Red line: The lowest price during the first 30 minutes of trading
## How It Works
**At 9:30 AM ET (Market Open):**
- PDH, PDL, PDC levels appear (from previous day's RTH)
- PMH, PML levels appear (from today's pre-market session)
- All lines begin at the 9:30 AM bar and extend right
**At 10:00 AM ET (Opening Range Close):**
- ORH, ORL levels appear (from today's first 30 minutes)
- Lines begin at the 9:30 AM bar and extend right
**Level Persistence:**
- All levels remain visible until the next trading day at 9:30 AM ET
- Levels reset daily for the new trading session
## Use Cases
**Day Trading:**
- Identify key support and resistance zones before placing trades
- Use PDH/PDL as potential profit targets or stop loss areas
- Monitor price reaction at pre-market levels for early trading signals
- Trade breakouts or rejections at opening range levels
**Swing Trading:**
- Assess daily momentum by observing breaks above/below previous day levels
- Use multiple timeframes while maintaining consistent reference points
**Market Structure:**
- Quickly identify if the market is trading above or below key levels
- Recognize accumulation/distribution patterns around these zones
## Technical Details
- **Timezone:** All times referenced are US Eastern Time (America/New_York)
- **Session Windows:**
  - Pre-Market: 4:00 AM - 9:30 AM ET
  - Regular Trading Hours: 9:30 AM - 4:00 PM ET
  - Opening Range: 9:30 AM - 10:00 AM ET
- **Timeframe Agnostic:** Works on any chart timeframe
- **Visual Clarity:** Color-coded lines and labels for easy identification
## Color Scheme
- **Blue:** Previous Day levels (PDH, PDL)
- **Orange:** Previous Day Close (PDC)
- **Yellow:** Pre-Market levels (PMH, PML)
- **Red:** Opening Range levels (ORH, ORL)
## Best Practices
1. Use on US equity indices (SPY, QQQ, ES, NQ) and liquid US stocks
2. Combine with volume analysis for confirmation
3. Pay attention to how price reacts at these levels (bounce vs. break)
4. Most effective during the first 2 hours of trading when volatility is highest
5. Consider the market context (trending vs. ranging) when interpreting these levels
## Note
This indicator is specifically designed for US market hours. Results may vary when applied to international markets or instruments with different trading sessions.
ICT Anchored Market Structures with Validation [LuxAlgo]The  ICT Anchored Market Structures with Validation  indicator is an advanced iteration of the original  Pure-Price-Action-Structures  tool, designed for price action traders. 
It systematically tracks and validates key price action structures, distinguishing between true structural shifts/breaks and short-term sweeps to enhance trend and reversal analysis. The indicator automatically highlights structural points, confirms breakouts, identifies sweeps, and provides clear visual cues for short-term, intermediate-term, and long-term market structures.
A distinctive feature of this indicator is its exclusive reliance on price patterns. It does not depend on any user-defined input, ensuring that its analysis remains robust, objective, and uninfluenced by user bias, making it an effective tool for understanding market dynamics.
🔶  USAGE 
  
Market structure is a cornerstone of price action analysis. This script automatically detects real-time market structures across short-term, intermediate-term, and long-term levels, simplifying trend analysis for traders. It assists in identifying both trend reversals and continuations with greater clarity.
  
Market structure shifts and breaks help traders identify changes in trend direction. A shift signals a potential reversal, often occurring when a swing high or low is breached, suggesting a transition in trend. A break, on the other hand, confirms the continuation of an established trend, reinforcing the current direction. Recognizing these shifts and breaks allows traders to anticipate price movement with greater accuracy.
  
It’s important to note that while a CHoCH may signal a potential trend reversal and a BoS suggests a continuation of the prevailing trend, neither guarantees a complete reversal or continuation. In some cases, CHoCH and BoS levels may act as liquidity zones or areas of consolidation rather than indicating a clear shift or continuation in market direction. The indicator’s validation component helps confirm whether the detected CHoCH and BoS are true breakouts or merely liquidity sweeps.
  
🔶  DETAILS 
🔹  Market Structures 
Market structures are derived from price action analysis, focusing on identifying key levels and patterns in the market. Swing point detection, a fundamental concept in ICT trading methodologies and teachings, plays a central role in this approach.
  
Swing points are automatically identified based exclusively on market movements, without requiring any user-defined input.
🔹  Utilizing Swing Points 
Swing points are not identified in real-time as they form. Short-term swing points may appear with a delay of up to one bar, while the identification of intermediate and long-term swing points is entirely dependent on subsequent market movements. Importantly, this detection process is not influenced by any user-defined input, relying solely on pure price action. As a result, swing points are generally not intended for real-time trading scenarios.
Instead, traders often analyze historical swing points to understand market trends and identify potential entry and exit opportunities. By examining swing highs and lows, traders can:
 
 Recognize Trends:  Swing highs and lows provide insight into trend direction. Higher swing highs and higher swing lows signify an uptrend, while lower swing highs and lower swing lows indicate a downtrend.
 Identify Support and Resistance Levels:  Swing highs often act as resistance levels, referred to as Buyside Liquidity Levels in ICT terminology, while swing lows function as support levels, also known as Sellside Liquidity Levels. Traders can leverage these levels to plan their trade entries and exits.
 Spot Reversal Patterns:  Swing points can form key reversal patterns, such as double tops or bottoms, head and shoulders, and triangles. Recognizing these patterns can indicate potential trend reversals, enabling traders to adjust their strategies effectively.
 Set Stop Loss and Take Profit Levels:  In ICT teachings, swing levels represent price points with expected clusters of buy or sell orders. Traders can target these liquidity levels/pools for position accumulation or distribution, using swing points to define stop loss and take profit levels in their trades.
 
Overall, swing points provide valuable information about market dynamics and can assist traders in making more informed trading decisions.
🔹  Logic of Validation 
The validation process in this script determines whether a detected market structure shift or break represents a confirmed breakout or a sweep.
The breakout is confirmed when the close price is significantly outside the deviation range of the last detected structural price. This deviation range is defined by the 17-period Average True Range (ATR), which creates a buffer around the detected market structure shift or break.
A sweep occurs when the price breaches the structural level within the deviation range but does not confirm a breakout. In this case, the label is updated to 'SWEEP.'
A visual box is created to represent the price range where the breakout or sweep occurs. If the validation process continues, the box is updated. This box visually highlights the price range involved in a sweep, helping traders identify liquidity events on the chart.
  
 🔶 SETTINGS 
The settings for Short-Term, Intermediate-Term, and Long-Term Structures are organized into groups, allowing users to customize swing points, market structures, and visual styles for each.
🔹  Structures 
 
 Swings and Size:  Enables or disables the display of swing highs and lows, assigns icons to represent the structures, and adjusts the size of the icons.
 Market Structures:  Toggles the visibility of market structure lines.
 Market Structure Validation:  Enable or disable validation to distinguish true breakouts from liquidity sweeps.
 Market Structure Labels:  Displays or hides labels indicating the type of market structure.
 Line Style and Width:  Allows customization of the style and width of the lines representing market structures.
 Swing and Line Colors:  Provides options to adjust the colors of swing icons, market structure lines, and labels for better visualization.
 
🔶  RELATED SCRIPTS 
 
 Pure-Price-Action-Structures. 
 Market-Structures-(Intrabar). 
Volume Rate of Change (VROC)# Volume Rate of Change (VROC)
**What it is:** VROC measures the rate of change in trading volume over a specified period, typically expressed as a percentage. Formula: `((Current Volume - Volume n periods ago) / Volume n periods ago) × 100`
## **Obvious Uses**
**1. Confirming Price Trends**
- Rising VROC with rising prices = strong bullish trend
- Rising VROC with falling prices = strong bearish trend
- Validates that price movements have conviction behind them
**2. Spotting Divergences**
- Price makes new highs but VROC doesn't = weakening momentum
- Price makes new lows but VROC doesn't = potential reversal
**3. Identifying Breakouts**
- Sudden VROC spikes often accompany legitimate breakouts from consolidation patterns
- Helps distinguish real breakouts from false ones
**4. Overbought/Oversold Conditions**
- Extreme VROC readings (very high or very low) suggest exhaustion
- Mean reversion opportunities when volume extremes occur
---
## **Non-Obvious Uses**
**1. Smart Money vs. Dumb Money Detection**
- Declining VROC during price rallies may indicate retail FOMO while institutions distribute
- Rising VROC during selloffs with price stability suggests institutional accumulation
**2. News Impact Measurement**
- Compare VROC before/after earnings or announcements
- Low VROC on "significant" news = market doesn't care (fade the move)
- High VROC = genuine market reaction (respect the move)
**3. Market Regime Changes**
- Persistent shifts in average VROC levels can signal transitions between bull/bear markets
- Declining baseline VROC over months = waning market participation/topping process
**4. Intraday Liquidity Profiling**
- VROC patterns across trading sessions identify best execution times
- Avoid trading when VROC is abnormally low (wider spreads, poor fills)
**5. Sector Rotation Analysis**
- Compare VROC across sector ETFs to identify where capital is flowing
- Rising VROC in defensive sectors + falling VROC in cyclicals = risk-off rotation
**6. Options Expiration Effects**
- VROC typically drops significantly post-options expiration
- Helps avoid false signals from mechanically-driven volume changes
**7. Algorithmic Activity Detection**
- Unusual VROC patterns (regular spikes at specific times) may indicate algo programs
- Can front-run or avoid periods of heavy algorithmic interference
**8. Liquidity Crisis Early Warning**
- Sharp, sustained VROC decline across multiple assets = liquidity withdrawal
- Can precede market stress events before price volatility emerges
**9. Cryptocurrency Wash Trading Detection**
- Comparing VROC across exchanges for same asset
- Discrepancies suggest artificial volume on certain platforms
**10. Pair Trading Optimization**
- Use relative VROC between correlated pairs
- Enter when VROC divergence is extreme, exit when it normalizes
The key to advanced VROC usage is context: combining it with price action, market structure, and other indicators rather than using it in isolation.
Order Flow RSI - Price / CVD / OIOrder Flow RSI  blends three powerful market perspectives —  Price ,  Cumulative Volume Delta (CVD) , and  Open Interest (OI)  — into one unified RSI-style oscillator.
It reveals momentum and imbalance across these data streams and highlights situations where participation, liquidity, and positioning disagree — moments that often precede reversals.
 What it does 
The indicator converts:
 
 Price → RSI  (classic momentum),
 CVD → RSI  (buy/sell pressure balance),
 OI → RSI  (position expansion/contraction)
 
…then plots all three RSIs together on the same 0–100 scale.
A fourth  Consensus RSI  (average of any two or all three) can optionally be shown to simplify the view.
 Core logic 
 
 CVD engine  – based on TradingView’s native volume-delta request.
 Modes: Continuous (default, smooth line), Anchored (resets each session), Rolling window.
 Open Interest  – pulled automatically from the symbol’s “_OI” feed; aligns to chart timeframe for real-time flow.
 RSI calculation  – standard RSI applied to each data stream, optionally smoothed (SMA / EMA / RMA / WMA / VWMA).
 Signals  – optional background highlights when:
 All three RSIs are overbought (red) or oversold (green), or
 Any pair show opposite extremes (e.g., price overbought + OI oversold).
 Consensus RSI  – arithmetic mean of the selected RSIs, summarizing overall market tone.
 
 Inputs overview 
 
 CVD settings:  anchor period, lower-TF delta, mode, rolling length
 RSI lengths:  separate for price, CVD, OI
 Smoothing:  type + period applied to all RSIs at once
 Consensus:  choose which RSIs to average
 Signals:  enable/disable each combination; optional alerts
 Levels:  adjustable OB/MID/OS (default 70 / 50 / 30)
 Visuals:  fill between active RSIs, background highlights, level lines, colors in Style tab
 
 How to read it 
 
 All 3 overbought (red):  broad exhaustion → possible correction
 All 3 oversold (green):  broad depletion → possible bounce
 Opposite pairs:  divergence between price and participation
 Price↑ but OI↓ (red) → weak rally, fading participation
 Price↓ but CVD↑ (green) → hidden accumulation
 
Combine with structure and volume profile for confirmation.
 Notes 
 
 Works best on assets with full CVD + OI data (futures, BTC, etc.).
 Use Continuous CVD for smooth RSI, Anchored for session analysis.
 Smoothing 2–5 EMA is a good starting point to reduce noise.
 All styling (colors, line types, thickness) is adjustable in the Style tab.
 
 Limitations & caveats 
 
 CVD requires accurate tick/volume/delta data from your data feed. Performance may differ across instruments.
 OI availability varies by exchange / symbol. Where OI is absent, pairwise OI signals are not evaluated.
 This indicator is a tool — it generates signals of interest, not guaranteed profitable trades. Backtest and combine with your risk rules.
 Smoothing introduces lag; longer smoothing reduces noise but delays signals.
 
 Order Flow RSI  bridges traditional momentum analysis and order-flow context — giving a multi-dimensional view of when markets are truly stretched or quietly reloading.
 Sometimes it works, sometimes it doesn't.
Free Stock ScreenerMissing great trade opportunities is annoying, and unless you have 12 screens or only trade one market, you are missing a lot of trades. To fix that, we created this free stock screener so you get notified instantly of potential great trading conditions in real time, right on your chart.
You get notified of trading benchmarks being met by the value being displayed on the scanner as well as a color change so that it grabs your attention and makes you aware that you should take a look at the other market and look for a potential trade. It also has built in alerts so you can have an alert notification go off when any of your trading conditions are met instead of needing to watch the scanner for color changes.
The screener will change the ticker symbol background color to red green when price is above or below the previous daily range and above or below both VWAPs. This signals that the ticker is trending, which typically means it is a great time to trade that market and follow the trend.
This free stock screener allows you to scan up to 10 different markets at the same time for various different conditions so you always know what is going on with your favorite trading symbols. If you want to scan more tickers, just add the indicator to your chart again and change the table position to the other side of the screen and update the tickers on the 2nd screener, allowing you to have 20 tickers at a time.
The scanner can be fully customized by changing the markets that it screens and turning on or off as many of them as you would like. You can also turn on or off any of the different data sets so that you only get information about trading conditions that matter to you.
The screener can provide data on any type of market, such as stocks, crypto, futures, forex and more. Each ticker can be adjusted to whatever market you would like it to scan for data in the settings panel, the only limitation is that it will not provide data for the VWAP and volume trend score if the ticker you are screening does not provide volume data.
 Screener Features 
The scanner will provide the following types of data for each ticker that is turned on:
 
 Volume  - Provides a volume score compared to the average volume and notifies you of higher than normal volume and volume spikes on individual bars by changing colors.
 Volatility  - Provides a volatility score compared to the average volatility and notifies you of higher than normal volatility by changing colors.
 Oscillator  - Choose between the RSI or CCI. The value of that oscillator will be displayed and will notify you when values are in extreme ranges such as overbought or oversold conditions according to the threshold values you enter in the settings panel. When those thresholds have been breached, you will be notified by it changing color.
 Big Candles  - Compares the current candle to average previous candle sizes, and changes color to notify you of big candles including a big top wick, big bottom wick, big candle body and big candle high to low range.
 Daily Level Touches & Trends  - Calculates and displays various daily candle and intraday open price levels that act as support and resistance. Notifies you when price is touching any of the daily levels that are turned on. The levels you can have on are as follows: previous day high, previous day low or previous day open. It also will notify you when price is touching the current day’s open, NY 930am open, Asia 8pm open, London 2am open and NY midnight 12am open. It will also say “Above” if price is above the previous day’s high or it will say “Below” if price is below the previous day’s low. The color of the cell will also change when a level touch is happening or price is above the previous day high or below the previous day low.
 VWAP  - Choose from 2 different VWAP lengths, default settings are daily and weekly VWAPs. You will get notified if price touches either of the VWAPs and they will also say “Above” or “Below” if price is currently above or below each VWAP.
 
 How To Use The Screener To Help You Trade 
The main purpose of the screener is to scan other markets and notify you of potential good trading opportunities such as price bouncing off of the daily levels or VWAPs. It can also be used to know when price is trending according to the VWAPs and daily levels. Lastly, you can use it to know how the volume and volatility trends are currently which gives you more confidence in taking a trade with this data when volume and volatility are present.
 Volume Score 
When volume is high, this represents a good time to trade because there are many market participants and price is likely to be volatile while there is high volume which can present a lot of good trade setups for you to take. 
The volume score shown on the screener measures the current volume trend compared to previous volume trends and calculates that into a score based on 100 being the same as the previous volume trend. So any value above 100 means it is high volume and any value less than 100 means it is lower volume than normal.
In the settings panel, you can adjust the volume threshold that needs to be met for a volume notification to show up. The default setting is at 120, so you will get notified when the current volume trend score is 120 or higher or you can adjust that threshold value to whatever value you prefer.
It also will notify you when there is a volume spike on the current bar. This is determined by calculating an average of the recent volume totals and then checking to see if the current bar is greater than or equal to that average multiplied by 3. So if a single bar has volume that is greater than 3 times what the average volume is, then you will get a notification that says “Spike” to make you aware of that volume spike.
The volume trend threshold, volume spike multiplier and lookback length for the average volume used in volume spike calculations can all be adjusted in the settings panel to fit your desired preferences.
 Volatility Score 
High volatility can mean it is a great time to trade because the market is moving quickly and providing large enough movements that you can get in and out in a short amount of time, while still accruing decent sized trade PnL. 
The volatility score will calculate the current volatility for each market compared to previous conditions and then divide the current volatility by the average volatility to give you a volatility score. Anything over 100 means the market is decently volatile and you should look at that market to find potential trade setups to execute on. Anything below 100 means the market is not very volatile and it is usually best to just wait until volatility returns before you start trading again.
The screener will notify you when the volatility score is above the threshold you set. The default value is set to 90, but can be adjusted to your preference. Pay attention to any market that shows an alert and take a look at that chart because the high volatility may present a good trade setup for you in the near future.
 Oscillator Score 
The oscillator data can be switched between Relative Strength Index(RSI) and Commodity Channel Index(CCI). 
The RSI provides a value between 0 and 100 that indicates the momentum and strength of the recent price action. Many traders use the extremes of the 0-100 range to signal overbought or oversold conditions and use that as a sign to look for price to reverse in the near future. The typical values used for this and the default settings to provide notifications are: 70 for overbought and 30 for oversold. The scanner will notify you when the RSI value is considered overbought or oversold so you know to take a look at the chart and analyze if it is ready for a trade to be taken.
The CCI provides a value that can be used to determine the trend strength of the underlying asset when the oscillator moves above 100 or below -100. These extreme values are outside of the normal accumulation range and signify that price is moving strongly in that direction so it may be a good time to take a trade in the direction of the trend. The scanner will show you the value of the CCI for each market and notify you if that value is above 100 or below -100.
Both RSI and CCI settings can be adjusted in the settings panel to your desired settings so you have the exact oscillator settings you prefer to use as well as the exact values that you want to use for being notified.
 Big Candles 
Big candles can mean that many traders are buying or selling at the same time and many times indicate a good signal to trade in that same direction. That is why we included this calculation in the screener, so you are always aware when a large candle prints. 
It calculates the average size of the recent candles and then uses that average as the benchmark to determine if the current candle is considered big and worthy of notifying you to take a look at that chart. 
You can adjust the multiplier used for the big candle threshold to whatever you desire, but the default setting is 3 which means the candle will be considered big and notify you if it is 3 times as large as an average candle.
The big candles data will track the following candle values and notify you with these labels:
 
 High to Low candle size = HL
 Candle Body from open to close candle size = OC
 Top Wick size = TW
 Bottom Wick size = BW
 
 Daily Level Touches & Trend 
Daily level touches are excellent levels to watch for price to bounce because they often act as support and resistance levels for intraday trading. The scanner will track each market and notify you when the current candle is touching any of the daily levels that you have turned on in the settings panel.
The main levels that are turned on by default and are useful for all markets and how they will be labeled on the scanner are as follows:
 
 Previous Day High = High
 Previous Day Low = Low
 Previous Day Open = < Open
 Previous Day Close = Close
 Current Day Open = Open
 
We also included some extra levels that are useful for futures traders. They are as follows:
 
 NY 930am Open = 930am
 NY 12am Midnight Open = 12am
 Asia Open at 8pm NY time = Asia
 London Open at 2am NY Time = London
 
Watch how price reacts to these levels and then trade the bounces off of these levels if the price action confirms that it is going to respect that level.
When price is currently above the previous day high, the scanner will say “Above” and show a green color, indicating a bullish trend and that price is above the previous daily candle’s high.
When price is currently below the previous day low, the scanner will say “Below” and show a red color, indicating a bearish trend and that price is below the previous daily candle’s low.
Pay attention to when price is trending above or below the previous daily candle as those trends can provide excellent trend trading opportunities.
The daily levels that you have turned on in the settings will also show as lines on the chart and include a label next to them, identifying each level so you know what each line represents. You can turn on or off all of the lines shown on the chart in the main settings or turn them off one by one in the style panel of the settings. Labels can also be turned on or off for all of the lines in the main settings panel. You can adjust the label positioning in the Label Offset section of the settings panel.
 VWAP Touches & Trend 
VWAP stands for volume weighted average price and is a very popular tool that traders use to determine trend direction based on volume as well as an excellent level to trade price bounces off of.
The typical VWAP time period used is Daily, which means the volume weighted average price will reset at the beginning of a new day. We set the first VWAP to be the daily VWAP by default and the second one to be the weekly VWAP. You can adjust both of the time periods to be any of the provided time lengths that you choose.
The screener will show “Above” with a green background color when price is above the VWAP, indicating a bullish trend. It will show “Below” with a red background color when price is below the VWAP, indicating a bearish trend. When both VWAPs are showing Above or Below, you can expect price to trend in that direction, so look for pullbacks you can trade in the direction of the trend. If the VWAPs are showing different directions, then you should expect to bounce back and forth between the VWAPs, but be careful and watch out for price to break beyond either one and start a trend.
When the current candle is touching the VWAP, the scanner will change colors and say VWAP to notify you that price is touching the VWAP and you should look at that chart and analyze the market for a potential bounce off of the VWAP to trade.
 Trending Market Signals 
Strong trends are excellent markets to trade and can many times provide excellent trading opportunities that don’t require expert price action reading skills to be able to take winning trades from. That is why we included a signal to notify you of a strong trending market. 
The strong trending market will show up as a green or red background color for the ticker name. If the color of the ticker name is green, it is notifying you that the price is above the previous daily high, above VWAP 1 and above VWAP 2 and is a good market to look for bullish trend trades. If the color of the ticker name is red, it is notifying you that the price is below the previous daily low, below VWAP 1 and below VWAP 2 and is a good market to look for bearish trend trades. 
 Changing The Tickers It Scans 
To change the tickers that the indicator scans, scroll near the bottom of the settings panel and select the ticker symbol you want to update and then search for the exact symbol you want to use. If you want to scan less tickers, then just turn some of the tickers off that you don’t need.
 Scanning More Than 10 Tickers 
If you want to scan more than 10 tickers, you can add the scanner to your chart again and then just change the table position to the other side of the screen. This will allow you to scan 10 more tickers that will show up separately. Then if you want even more, just add the indicator to your chart again and update the table position until you have as many markets as you want. The table position setting can be found at the bottom of the main settings panel.
 Alerts 
The screener has alerts that can be used to notify you when any of the data set thresholds have been met or if price is touching one of the levels. You can set alerts for the following events:
 
 Bullish Trend Alert  - Price is above the previous daily high and above both VWAPs.
 Bearish Trend Alert  - Price is below the previous daily low and below both VWAPs.
 High Volume Alert  - Volume is higher than the threshold or a volume spike is detected.
 High Volatility Alert  - Volatility is higher than the threshold.
 Oscillator Is Extended Alert  - Oscillator value has exceeded the upper or lower threshold.
 Big Candle Alert  - A big candle has been detected.
 Daily Level Touch Alert  - One of the daily levels that is turned on is being touched.
 VWAP Touch Alert  - One of the 2 VWAPs are being touched.
 
An alert will trigger when any one of tickers on your scanner meets the alert conditions, so when you see the alert, you will need to go to your chart and look at the scanner to see which ticker it was and then navigate to that chart to look for potential trade setups.
The alerts will use the exact same settings you have configured in the settings panel to send you alert notifications. With normal settings, this could give you a lot of alerts, so if you only want alerts to fire when abnormal conditions are being met, try setting up a second screener on your chart that has very high threshold values and only has the most important level touches on. Then turn the setting "Do Not Show The Screener On The Chart" to off so the calculations will still run and fire alerts, but won't clog up your charts. This way you can only get alert notifications when major events happen but still have your normal screener settings available on your chart.
 Markets This Can Be Used On 
This screener uses the price action and volume data so you can use it to scan any type of market you would like as long as the ticker you are scanning has price and volume data feeds. If a market does not have volume data, then it will just show NaN in the volume row and the VWAP rows will not show anything.
Volume v4 (Dollar Value) by Koenigsegg📊 Volume v3 (Dollar Value) by Koenigsegg
🎯 Purpose:
Volume v3 (Dollar Value) by Koenigsegg transforms traditional raw-unit volume into dollar-denominated volume, revealing how much money actually flows through each candle.
Instead of measuring how many coins or contracts were traded, this version calculates the total traded value = volume × average price (hlc3), allowing traders to visually assess capital intensity and market participation within each move.
⚙️ Core Features
- Converts raw volume into USD-based traded value for each candle.
- Color-coded bars show bullish (green/teal) vs. bearish (red) activity.
- Built-in SMA and SMMA overlays highlight sustained shifts in value flow.
- Designed for visual clarity to support momentum, exhaustion, and divergence studies.
📖 How to Read It
Rising Dollar Volume — indicates growing market participation and strong capital flow, often aligning with impulsive waves in trend direction.
Falling Dollar Volume — signals waning interest or reduced participation, potentially hinting at correction or exhaustion phases.
Comparing Legs — when price makes new highs/lows but dollar volume weakens, it can reveal divergences between price movement and actual capital commitment.
SMA / SMMA Lines — use them to identify longer-term accumulation or depletion of market activity, separating short bursts from sustained inflows or outflows.
The goal is to visualize the strength of market moves in terms of capital energy, not just tick activity. This distinction helps traders interpret whether a trend is being driven by genuine money flow or low-liquidity drift.
⚠️ Disclaimer
This script is provided for research and educational purposes only.
It does not constitute financial advice, investment recommendations, or trading signals.
Always conduct your own analysis and manage your own risk when trading live markets.
The author accepts no liability for financial losses incurred from use of this tool.
🧠 Credits
Developed and published by Koenigsegg.
Written in Pine Script® v6, fully compliant with TradingView’s House Rules for Pine Scripts.
Licensed under the Mozilla Public License 2.0.






















