C&B Auto MK5C&B Auto MK5.2ema BullBear
Overview
The C&B Auto MK5.2ema BullBear is a versatile Pine Script indicator designed to help traders identify bullish and bearish market conditions across various timeframes. It combines Exponential Moving Averages (EMAs), Relative Strength Index (RSI), Average True Range (ATR), and customizable time filters to generate actionable signals. The indicator overlays on the price chart, displaying EMAs, a dynamic cloud, scaled RSI levels, bull/bear signals, and market condition labels, making it suitable for swing trading, day trading, or scalping in trending or volatile markets.
What It Does
This indicator generates bull and bear signals based on the interaction of two EMAs, filtered by RSI thresholds, ATR-based volatility, a 50/200 EMA trend filter, and user-defined time windows. It adapts to market volatility by adjusting EMA lengths and RSI thresholds. A dynamic cloud highlights trend direction or neutral zones, with candlestick coloring in neutral conditions. Market condition labels (current and historical) provide real-time trend and volatility context, displayed above the chart.
How It Works
The indicator uses the following components:
EMAs: Two EMAs (short and long) are calculated on a user-selected timeframe (1, 5, 15, 30, or 60 minutes). Their crossover or crossunder triggers potential bull/bear signals. EMA lengths adjust based on volatility (e.g., 10/20 for volatile markets, 5/10 for non-volatile).
Dynamic Cloud: The area between the EMAs forms a cloud, colored green for bullish trends, red for bearish trends, or a user-defined color (default yellow) for neutral zones (when EMAs are close, determined by an ATR-based threshold). Users can widen the cloud for visibility.
RSI Filter: RSI is scaled to price levels and plotted on the chart (optional). Signals are filtered to ensure RSI is within volatility-adjusted bull/bear thresholds and not in overbought/oversold zones.
ATR Volatility Filter: An optional filter ensures signals occur during sufficient volatility (ATR(14) > SMA(ATR, 20)).
50/200 EMA Trend Filter: An optional filter restricts bull signals to bullish trends (50 EMA > 200 EMA) and bear signals to bearish trends (50 EMA < 200 EMA).
Time Filter: Signals are restricted to a user-defined UTC time window (default 9:00–15:00), aligning with active trading sessions.
Market Condition Labels: Labels above the chart display the current trend (Bullish, Bearish, Neutral) and optionally volatility (e.g., “Bullish Volatile”). Up to two historical labels persist for a user-defined number of bars (default 5) to show recent trend changes.
Visual Aids: Bull signals appear as green triangles/labels below the bar, bear signals as red triangles/labels above. Candlesticks in neutral zones are colored (default yellow).
The indicator ensures compatibility with standard chart types (e.g., candlestick or bar charts) to produce realistic signals, avoiding non-standard types like Heikin Ashi or Renko.
How to Use It
Add to Chart: Apply the indicator to a candlestick or bar chart on TradingView.
Configure Settings:
Timeframe: Choose a timeframe (1, 5, 15, 30, or 60 minutes) to match your trading style.
Filters:
Enable/disable the ATR volatility filter to focus on high-volatility periods.
Enable/disable the 50/200 EMA trend filter to align signals with the broader trend.
Enable the time filter and set custom UTC hours/minutes (default 9:00–15:00).
Cloud Settings: Adjust the cloud width, neutral zone threshold, color, and transparency.
EMA Colors: Use default trend-based colors or set custom colors for short/long EMAs.
RSI Display: Toggle the scaled RSI and its thresholds, with customizable colors.
Signal Settings: Toggle bull/bear labels and set signal colors.
Market Condition Labels: Toggle current/historical labels, include/exclude volatility, and adjust decay period.
Interpret Signals:
Bull Signal: A green triangle or “Bull” label below the bar indicates potential bullish momentum (EMA crossover, RSI above bull threshold, within time window, passing filters).
Bear Signal: A red triangle or “Bear” label above the bar indicates potential bearish momentum (EMA crossunder, RSI below bear threshold, within time window, passing filters).
Neutral Zone: Yellow candlesticks and cloud (if enabled) suggest a lack of clear trend; consider range-bound strategies or avoid trading.
Market Condition Labels: Check labels above the chart for real-time trend (Bullish, Bearish, Neutral) and volatility status to confirm market context.
Monitor Context: Use the cloud, RSI, and labels to assess trend strength and volatility before acting on signals.
Unique Features
Volatility-Adaptive EMAs: Automatically adjusts EMA lengths based on ATR to suit volatile or non-volatile markets, reducing manual configuration.
Neutral Zone Detection: Uses an ATR-based threshold to identify low-trend periods, helping traders avoid choppy markets.
Scaled RSI Visualization: Plots RSI and thresholds directly on the price chart, simplifying momentum analysis relative to price.
Flexible Time Filtering: Supports precise UTC-based trading windows, ideal for day traders targeting specific sessions.
Historical Market Labels: Displays recent trend changes (up to two) with a decay period, providing context for market shifts.
50/200 EMA Trend Filter: Aligns signals with the broader market trend, enhancing signal reliability.
Notes
Use on standard candlestick or bar charts to ensure accurate signals.
Test the indicator on a demo account to optimize settings for your market and timeframe.
Combine with other analysis (e.g., support/resistance, volume) for better decision-making.
The indicator is not a standalone system; use it as part of a broader trading strategy.
Limitations
Signals may lag in fast-moving markets due to EMA-based calculations.
Neutral zone detection may vary in extremely volatile or illiquid markets.
Time filters are UTC-based; ensure your platform’s timezone settings align.
This indicator is designed for traders seeking a customizable, trend-following tool that adapts to volatility and provides clear visual cues with robust filtering for bullish and bearish market conditions.
ค้นหาในสคริปต์สำหรับ "renko"
AlphaTrend++AlphaTrend++
Overview
The AlphaTrend++ is an advanced Pine Script indicator designed to help traders identify buy and sell opportunities in trending and volatile markets. Building on trend-following principles, it uses a modified Average True Range (ATR) calculation combined with volume or momentum data to plot a dynamic trend line. The indicator overlays on the price chart, displaying a colored trend line, a filled trend zone, buy/sell signals, and optional stop-loss tick labels, making it ideal for day trading or swing trading, particularly in markets like futures (e.g., MES).
What It Does
This indicator generates buy and sell signals based on the direction and momentum of a custom trend line, filtered by optional time restrictions and signal frequency logic. The trend line adapts to price action and volatility, with a filled zone highlighting trend strength. Buy/sell signals are plotted as labels, and stop-loss distances are displayed in ticks (customizable for instruments like MES). The indicator supports standard chart types for realistic signal generation.
How It Works
The indicator employs the following components:
Trend Line Calculation: A dynamic trend line is calculated using ATR adjusted by a user-defined multiplier, combined with either Money Flow Index (MFI) or Relative Strength Index (RSI) depending on volume availability. The line tracks price movements, adjusting upward or downward based on trend direction and volatility.
Trend Zone: The area between the current trend line and its value two bars prior is filled, colored green for bullish trends (upward movement) or red for bearish trends (downward movement), providing a visual cue of trend strength.
Signal Generation: Buy signals occur when the trend line crosses above its value two bars ago, and sell signals occur when it crosses below, with optional filtering to reduce signal noise (based on bar timing logic). Signals can be restricted to a 9:00–15:00 UTC trading window.
Stop-Loss Ticks: For each signal, the indicator calculates the distance to the trend line (acting as a stop-loss level) in ticks, using a user-defined tick size (default 0.25 for MES). These are displayed as labels below/above the signal.
Time Filter: An optional filter limits signals to 9:00–15:00 UTC, aligning with active trading sessions like the US market open.
The indicator ensures compatibility with standard chart types (e.g., candlestick or bar charts) to avoid unrealistic results associated with non-standard types like Heikin Ashi or Renko.
How to Use It
Add to Chart: Apply the indicator to a candlestick or bar chart on TradingView.
Configure Settings:
Multiplier: Adjust the ATR multiplier (default 1.0) to control trend line sensitivity. Higher values widen the stop-loss distance.
Common Period: Set the ATR and MFI/RSI period (default 14) for trend calculations.
No Volume Data: Enable if volume data is unavailable (e.g., for certain forex pairs), switching from MFI to RSI.
Tick Size: Set the tick size for stop-loss calculations (default 0.25 for MES futures).
Show Buy/Sell Signals: Toggle signal labels (default enabled).
Show Stop Loss Ticks: Toggle stop-loss tick labels (default enabled).
Use Time Filter: Restrict signals to 9:00–15:00 UTC (default disabled).
Use Filtered Signals: Enable to reduce signal frequency using bar timing logic (default enabled).
Interpret Signals:
Buy Signal: A blue “BUY” label below the bar indicates a potential long entry (trend line crossover, passing filters).
Sell Signal: A red “SELL” label above the bar indicates a potential short entry (trend line crossunder, passing filters).
Trend Zone: Green fill suggests bullish momentum; red fill suggests bearish momentum.
Stop-Loss Ticks: Gray labels show the stop-loss distance in ticks, helping with risk management.
Monitor Context: Use the trend line and filled zone to confirm the market’s direction before acting on signals.
Unique Features
Adaptive Trend Line: Combines ATR with MFI or RSI to create a responsive trend line that adjusts to volatility and market conditions.
Tick-Based Stop-Loss: Displays stop-loss distances in ticks, customizable for specific instruments, aiding precise risk management.
Signal Filtering: Optional bar timing logic reduces false signals, improving reliability in choppy markets.
Trend Zone Visualization: The filled zone between trend line values enhances trend clarity, making it easier to assess momentum.
Time-Restricted Trading: Optional 9:00–15:00 UTC filter aligns signals with high-liquidity sessions.
Notes
Use on standard candlestick or bar charts to ensure accurate signals.
Test the indicator on a demo account to optimize settings for your market and timeframe.
Combine with other analysis (e.g., support/resistance, volume spikes) for better decision-making.
The indicator is not a standalone system; use it as part of a broader trading strategy.
Limitations
Signals may lag in highly volatile or low-liquidity markets due to ATR-based calculations.
The 9:00–15:00 UTC time filter may not suit all markets; disable it for 24-hour assets like forex or crypto.
Stop-loss tick calculations assume consistent tick sizes; verify compatibility with your instrument.
This indicator is designed for traders seeking a robust, trend-following tool with customizable risk management and signal filtering, optimized for active trading sessions.
Adaptive Freedom Machine w/labelsAdaptive Freedom Machine w/ Labels
Overview
The Adaptive Freedom Machine w/ Labels is a versatile Pine Script indicator designed to assist traders in identifying buy and sell opportunities across various market conditions (trending, ranging, or volatile). It combines Exponential Moving Averages (EMAs), Relative Strength Index (RSI), Average True Range (ATR), and customizable time filters to generate actionable signals. The indicator overlays on the price chart, displaying EMAs, a dynamic cloud, scaled RSI levels, buy/sell signals, and market condition labels, making it suitable for swing trading, day trading, or scalping.
What It Does
This indicator generates buy and sell signals based on the interaction of two EMAs, filtered by RSI thresholds, ATR-based volatility, and user-defined time windows. It adapts to the selected market condition by adjusting EMA lengths, RSI thresholds, and trading hours. A dynamic cloud highlights trend direction or neutral zones, and candlestick bodies are colored in neutral conditions for clarity. A table displays real-time trend and volatility status.
How It Works
The indicator uses the following components:
EMAs: Two EMAs (short and long) are calculated on a user-selected timeframe (1, 5, 15, 30, or 60 minutes). Their crossover or crossunder generates potential buy/sell signals, with lengths adjusted based on the market condition (e.g., longer EMAs for trending markets, shorter for ranging).
Dynamic Cloud: The area between the EMAs forms a cloud, colored green for uptrends, red for downtrends, or a user-defined color (default yellow) for neutral zones (when EMAs are close, determined by an ATR-based threshold). Users can widen the cloud for visibility.
RSI Filter: RSI is scaled to price levels and plotted on the chart (optional). Signals are filtered to ensure RSI is within user-defined buy/sell thresholds and not in overbought/oversold zones, with thresholds tailored to the market condition.
ATR Volatility Filter: An optional filter ensures signals occur during sufficient volatility (ATR(14) > SMA(ATR, 20)).
Time Filter: Signals are restricted to a user-defined or market-specific time window (e.g., 10:00–15:00 UTC for volatile markets), with an option for custom hours.
Visual Aids: Buy/sell signals appear as green triangles (buy) or red triangles (sell). Candlesticks in neutral zones are colored (default yellow). A table in the top-right corner shows the current trend (Uptrend, Downtrend, Neutral) and volatility (High or Low).
The indicator ensures compatibility with standard chart types (e.g., candlestick charts) to produce realistic signals, avoiding non-standard types like Heikin Ashi or Renko.
How to Use It
Add to Chart: Apply the indicator to a candlestick or bar chart on TradingView.
Configure Settings:
Timeframe: Choose a timeframe (1, 5, 15, 30, or 60 minutes) to align with your trading style.
Market Condition: Select one market condition (Trending, Ranging, or Volatile). Volatile is the default if none is selected. Only one condition can be active.
Filters:
Enable/disable the ATR volatility filter to trade only in high-volatility periods.
Enable the time filter and choose default hours (specific to the market condition) or set custom UTC hours.
Cloud Settings: Adjust the cloud width, neutral zone threshold, and color. Enable/disable the neutral cloud.
RSI Display: Toggle the scaled RSI and its thresholds on the chart.
Interpret Signals:
Buy Signal: A green triangle below the bar indicates a potential long entry (EMA crossover, RSI above buy threshold, within time window, and passing volatility filter).
Sell Signal: A red triangle above the bar indicates a potential short entry (EMA crossunder, RSI below sell threshold, within time window, and passing volatility filter).
Neutral Zone: Yellow candlesticks and cloud (if enabled) suggest a lack of clear trend; avoid trading or use for range-bound strategies.
Monitor the Table: Check the top-right table for real-time trend (Uptrend, Downtrend, Neutral) and volatility (High or Low) to confirm market context.
Unique Features
Adaptive Parameters: Automatically adjusts EMA lengths, RSI thresholds, and trading hours based on the selected market condition, reducing manual tweaking.
Neutral Zone Detection: Uses an ATR-based threshold to identify low-trend periods, helping traders avoid choppy markets.
Scaled RSI Visualization: Plots RSI and thresholds directly on the price chart, making it easier to assess momentum relative to price action.
Flexible Time Filtering: Supports both default and custom UTC-based trading windows, ideal for day traders targeting specific sessions.
Dynamic Cloud: Enhances trend visualization with customizable width and neutral zone coloring, improving readability.
Notes
Use on standard candlestick or bar charts to ensure realistic signals.
Test the indicator on a demo account to understand its behavior in your chosen market and timeframe.
Adjust settings to match your trading strategy, but avoid over-optimizing for past data.
The indicator is not a standalone system; combine it with other analysis (e.g., support/resistance, news events) for better results.
Limitations
Signals may lag in fast-moving markets due to EMA-based calculations.
Neutral zone detection may vary in extremely volatile or illiquid markets.
Time filters are UTC-based; ensure your platform’s timezone settings align.
This indicator is designed for traders seeking a customizable, trend-following tool that adapts to different market environments while providing clear visual cues and robust filtering.
Alert on Candle CloseAlert on Candle Close is a simple indicator allowing you to set alerts when a candlestick closes.
 Instructions for use
 
 
 From the chart window, click on "Indicators" and search for "Alert on Candle Close".
 Click on "Alert on Candle Close" to add the indicator to your chart. Click on the star icon to add it to your favourites to easily access later.
 Set your chart timeframe to the timeframe you wish to alert on. For example, to create an alert when a 4h candlestick closes, set your chart to the "4h" timeframe.
 Hover over the "Alert on Candle Close" indicator which has been added to your chart and click the ellipsis "..." icon, then click "Add alert on Alert on Candle Close" or use the keyboard shortcut "Alt+A" from the chart.
 In the alert pop-up window, make sure "Condition" is set to "Alert on Candle Close" and "Trigger" is set to "Once Per Bar".
 Optionally, you can set a custom expiry for the alert, give the alert a name and customise the alert message. You can configure notification settings from the "Notifications" tab.
 Click "Create" and your alert is set up!
 
Each alert is tied to the timeframe and chart it was created on, so you can change the timeframe or asset and create more alerts by repeating the above process.
 Note : this indicator is only designed to work with time-based chart types, such as Bars, Candles or Heikin Ashi. It will not work for non-time charts such as Renko. 
 FAQs
 
 Why do my alerts sometimes not fire as soon as the candle closes?
 This is a limitation with Pine Script's execution model. Indicators are calculated whenever a price or volume change occurs i.e. when a new trade happens. For illiquid or slow moving markets, there may be some time between when a candle closes and the next trade, leading to a delay in the alert triggering. The alert will trigger on the next tick of data on the chart. 
 Why can't I create more alerts?
 TradingView has a limit on the number of active technical alerts you can have based on your membership tier. To configure more alerts, consider upgrading your TradingView plan to a higher tier. See a comparison of TradingView plans at  www.tradingview.com 
 My alert only fired once, how can I get it to keep working? 
When configuring the alert in the alert pop-up window, make sure you set "Trigger" to "Once Per Bar" and "Expiration" to "Open-ended alert".
MACD HTF Hardcoded (A/B Presets) + Regimes [CHE]  MACD HTF Hardcoded  (A/B Presets) + Regimes — Higher-timeframe MACD emulation with acceptance-based regime filter and on-chart diagnostics
  Summary 
This indicator emulates a higher-timeframe MACD directly on the current chart using two hardcoded preset families and a time-bucket mapping, avoiding cross-timeframe requests. It classifies four MACD regimes and applies an acceptance filter that requires several consecutive bars before a state is considered valid. A small dead-band around zero reduces noise near the axis. An on-chart table reports the active preset, the inferred time bucket, the resolved lengths, and the current regime.
Pine version: v6
Overlay: false
Primary outputs: MACD line, Signal line, Histogram columns, zero line, regime-change alert, info table
  Motivation: Why this design? 
Cross-timeframe indicators often rely on external timeframe requests, which can introduce repaint paths and added latency. This design provides a deterministic alternative: it maps the current chart’s timeframe to coarse higher-timeframe buckets and uses fixed EMA lengths that approximate those views. The dead-band suppresses flip-flops around zero, and the acceptance counter reduces whipsaw by requiring sustained agreement across bars before acknowledging a regime.
  What’s different vs. standard approaches? 
 Baseline: Classical MACD with user-selected lengths on the same timeframe, or higher-timeframe MACD via cross-timeframe requests.
 Architecture differences:
   Hardcoded A and B length families with a bucket map derived from the chart timeframe.
   No `request.security`; all calculations occur on the current series.
   Regime classification from MACD and Histogram sign, gated by an acceptance count and a small zero dead-band.
   Diagnostics table for transparency.
 Practical effect: The MACD behaves like a slower, higher-timeframe variant without external requests. Regimes switch less often due to the dead-band and acceptance logic, which can improve stability in choppy sessions.
  How it works (technical) 
The script derives a coarse bucket from the chart timeframe using `timeframe.in_seconds` and maps it to preset-specific EMA lengths. EMAs of the source build MACD and Signal; their difference is the Histogram. Signs of MACD and Histogram define four regimes: strong bull, weak bull, strong bear, and weak bear. A small, user-defined band around zero treats values near the axis as neutral. An acceptance counter checks whether the same regime persisted for a given number of consecutive bars before it is emitted as the filtered regime. A single alert condition fires when the filtered regime changes. The histogram columns change shade based on position relative to zero and whether they are rising or falling. A persistent table object shows preset, bucket tag, resolved lengths, and the filtered regime. No cross-timeframe requests are used, so repaint risk is limited to normal live-bar movement; values stabilize on close.
  Parameter Guide 
Source — Input series for MACD — Default: Close — Using a smoother source increases stability but adds lag.
Preset — A or B length family — Default: “3,10,16” — Switch to “12,26,9” for the classic family mapped to buckets.
Table Position — Anchor for the info table — Default: Top right — Choose a corner that avoids covering price action.
Table Size — Table text size — Default: Normal — Use small on dense charts, large for presentations.
Dark Mode — Table theme — Default: Enabled — Match your chart background for readability.
Show Table — Toggle diagnostics table — Default: Enabled — Disable for a cleaner pane.
Zero dead-band (epsilon) — Noise gate around zero — Default: Zero — Increase slightly when you see frequent flips near zero.
Acceptance bars (n) — Bars required to confirm a regime — Default: Three — Raise to reduce whipsaw; lower to react faster.
  Reading & Interpretation 
 Histogram columns: Above zero indicates bullish pressure; below zero indicates bearish pressure. Darker shade implies the histogram increased compared with the prior bar; lighter shade implies it decreased.
 MACD vs. Signal lines: The spread corresponds to histogram height.
 Regimes:
   Strong bull: MACD above zero and Histogram above zero.
   Weak bull: MACD above zero and Histogram below zero.
   Strong bear: MACD below zero and Histogram below zero.
   Weak bear: MACD below zero and Histogram above zero.
 Table: Inspect active preset, bucket tag, resolved lengths, and the filtered regime number with its description.
  Practical Workflows & Combinations 
 Trend following: Use strong bull to favor long exposure and strong bear to favor short exposure. Use weak states as pullback or transition context. Combine with structure tools such as swing highs and lows or a baseline moving average for confirmation.
 Exits and risk: In strong trends, consider exiting partial size on a regime downgrade to a weak state. In choppy sessions, increase the acceptance bars to reduce churn.
 Multi-asset / Multi-timeframe: Works on time-based charts across liquid futures, indices, currencies, and large-cap equities. Bucket mapping helps retain a consistent feel when moving from lower to higher timeframes.
  Behavior, Constraints & Performance 
 Repaint/confirmation: No cross-timeframe requests; values can evolve intrabar and settle on close. Alerts follow your TradingView alert timing settings.
 Resources: `max_bars_back` is set to five thousand. Very large resolved lengths require sufficient history to seed EMAs; expect a warm-up period on first load or after switching symbols.
 Known limits: Dead-band and acceptance can delay recognition at sharp turns. Extremely thin markets or large gaps may still cause brief regime reversals.
  Sensible Defaults & Quick Tuning 
Start with preset “3,10,16”, dead-band near zero, and acceptance of three bars.
 Too many flips near zero: increase the dead-band slightly or raise the acceptance bars.
 Too sluggish in clean trends: reduce the acceptance bars by one.
 Too sensitive on fast lower timeframes: switch to the “12,26,9” preset family or raise the acceptance bars.
 Want less clutter: hide the table and keep the alert.
  What this indicator is—and isn’t 
This is a visualization and regime layer for MACD using higher-timeframe emulation and stability gates. It is not a complete trading system and does not generate position sizing or risk management. Use it with market structure, execution rules, and protective stops.
 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 
Quantum Fluxtrend [CHE]  Quantum Fluxtrend   — A dynamic Supertrend variant with integrated breakout event tracking and VWAP-guided risk management for clearer trend decisions.
  Summary 
The Quantum Fluxtrend   builds on traditional Supertrend logic by incorporating a midline derived from smoothed high and low values, creating adaptive bands that respond to market range expansion or contraction. This results in fewer erratic signals during volatile periods and smoother tracking in steady trends, while an overlaid event system highlights breakout confirmations, potential traps, or continuations with visual lines, labels, and percentage deltas from the close. Users benefit from real-time VWAP calculations anchored to events, providing dynamic stop-loss suggestions to help manage exits without manual adjustments. Overall, it layers signal robustness with actionable annotations, reducing noise in fast-moving charts.
  Motivation: Why this design? 
Standard Supertrend indicators often generate excessive flips in choppy conditions or lag behind in low-volatility drifts, leading to whipsaws that erode confidence in trend direction. This design addresses that by centering bands around a midline that reflects recent price spreads, ensuring adjustments are proportional to observed variability. The added event layer captures regime shifts explicitly, turning abstract crossovers into labeled milestones with trailing VWAP for context, which helps traders distinguish genuine momentum from fleeting noise without over-relying on raw price action.
  What’s different vs. standard approaches? 
- Baseline reference: Diverges from the classic Supertrend, which uses average true range for fixed offsets from a median price.
- Architecture differences:
  - Bands form around a central line averaged from smoothed highs and lows, with offsets scaled by half the range between those smooths.
  - Regime direction persists until a clear breach of the prior opposite band, preventing premature reversals.
  - Event visualization draws persistent lines from flip points, updating labels based on price sustainment relative to the trigger level.
  - VWAP resets at each event, accumulating volume-weighted prices forward for a trailing reference.
- Practical effect: Charts show fewer direction changes overall, with color-coded annotations that evolve from initial breakout to continuation or trap status, making it easier to spot sustained moves early. VWAP lines provide a volume-informed anchor that curves with price, offering visual cues for adverse drifts.
  How it works (technical) 
The process starts by smoothing high and low prices over a user-defined period to form upper and lower references. A midline sits midway between them, and half the spread acts as a base for band offsets, adjusted by a multiplier to widen or narrow sensitivity. On each bar, the close is checked against the previous bar's opposite band: crossing above expands the lower band downward in uptrends, or below contracts the upper band upward in downtrends, creating a ratcheting effect that locks in direction until breached.
Persistent state tracks the current regime, seeding initial bands from the smoothed values if no prior data exists. Flips trigger new horizontal lines at the breach level, styled by direction, alongside labels that monitor sustainment—price holding above for up-flips or below for down-flips keeps the regime, while reversal flags a trap.
Separately, at each flip, a dashed VWAP line initializes at the breach price and extends forward, accumulating the product of typical prices and volumes divided by total volume. This yields a curving reference that updates bar-by-bar. Warnings activate if price strays adversely from this VWAP, tinting the background for quick alerts.
No higher timeframe data is pulled, so all computations run on the chart's native resolution, avoiding lookahead biases unless repainting is enabled via input.
  Parameter Guide 
SMA Length — Controls smoothing of highs and lows for midline and range base; longer values dampen noise but increase lag. Default: 20. Trade-offs: Shortens responsiveness in trends (e.g., 10–14) but risks more flips; extend to 30+ for stability in ranging markets.
Multiplier — Scales band offsets from the half-range; higher amplifies to capture bigger swings. Default: 1.0. Trade-offs: Above 1.5 widens for volatile assets, reducing false signals; below 0.8 tightens for precision but may miss subtle shifts.
Show Bands — Toggles visibility of basic and adjusted band lines for reference. Default: false. Tip: Enable briefly to verify alignment with price action.
Show Background Color — Displays red tint on VWAP adverse crosses for visual warnings. Default: false. Trade-offs: Helps in live monitoring but can clutter clean charts.
Line Width — Sets thickness for event and VWAP lines. Default: 2. Tip: Thicker (3–5) for emphasis on key levels.
+Bars after next event — Extends old lines briefly before cleanup on new flips. Default: 20. Trade-offs: Longer preserves history (40+) at resource cost; shorter keeps charts tidy.
Allow Repainting — Permits live-bar updates for smoother real-time view. Default: false. Tip: Disable for backtest accuracy.
Extension 1 Settings (Show, Width, Size, Decimals, Colors, Alpha) — Manages dotted connector from event label to current close, showing percentage change. Defaults: Shown, width 2, normal size, 2 decimals, lime/red for gains/losses, gray line, 90% transparent background. Trade-offs: Fewer decimals for clean display; adjust alpha for readability.
Extension 2 Settings (Show, Method, Stop %, Ticks, Decimals, Size, Color, Inherit, Alpha) — Positions stop label at VWAP end, offset by percent or ticks. Defaults: Shown, percent method, 1.0%, 20 ticks, 4 decimals, normal size, white text, inherit tint, 0% alpha. Trade-offs: Percent for proportional risk; ticks for fixed distance in tick-based assets.
Alert Toggles — Enables notifications for breakouts, continuations, traps, or VWAP warnings. All default: true. Tip: Layer with chart alerts for multi-condition setups.
  Reading & Interpretation 
The main Supertrend line colors green for up-regimes (price above lower band) and red for down (below upper band), serving as a dynamic support/resistance trail. Flip shapes (up/down triangles) mark regime changes at band breaches.
Event lines extend horizontally from flips: green for bull, red for bear. Labels start blank and update to "Bull/Bear Cont." if price sustains the direction, or "Trap" if it reverses, with colors shifting lime/red/gray accordingly. A dotted vertical links the trailing label to the current close, mid-labeled with the percentage delta (positive green, negative red).
VWAP dashes yellow (bull) or orange (bear) from the event, curving to reflect volume-weighted average. At its end, a left-aligned label shows suggested stop price, annotated with offset details. Background red hints at weakening if price crosses VWAP opposite the regime.
Deltas near zero suggest consolidation; widening extremes signal momentum buildup or exhaustion.
  Practical Workflows & Combinations 
- Trend following: Enter long on green flip shapes confirmed by higher highs, using the event line as initial stop below. Trail stops to VWAP for bull runs, exiting on trap labels or red background warnings. Filter with volume spikes to avoid low-conviction breaks.
- Exits/Stops: Conservative: Set hard stops at suggested SL labels. Aggressive: Hold through minor traps if delta stays positive, but cut on regime flip. Pair with momentum oscillators for overbought pullbacks.
- Multi-asset/Multi-TF: Defaults suit forex/stocks on 15m–4H; for crypto, bump multiplier to 1.5 for volatility. Scale SMA length proportionally across timeframes (e.g., double for daily). Combine with structure tools like Fibonacci for confluence on event lines.
  Behavior, Constraints & Performance 
Live bars update lines and labels dynamically if repainting is allowed, but signals confirm on close for stability—flips only trigger post-bar. No higher timeframe calls, so no inherent lookahead, though volume weighting assumes continuous data.
Resources cap at 1000 bars back, 50 lines/labels max; events prune old ones on new flips to stay under budget, with brief extensions for visibility. Arrays or loops absent, keeping it lightweight.
Known limits include lag in extreme gaps (e.g., overnight opens) where bands may not adjust instantly, and VWAP sensitivity to sparse volume in illiquid sessions.
  Sensible Defaults & Quick Tuning 
Start with SMA 20, multiplier 1.0 for balanced response across majors. For choppy pairs: Lengthen SMA to 30, multiplier 0.8 to tighten bands and cut flips. For trending equities: Shorten to 14, multiplier 1.2 for quicker entries. If traps dominate, enable bands to inspect range compression; for sluggish signals, reduce extension bars to focus on recent events.
  What this indicator is—and isn’t 
This serves as a visualization and signal layer for trend regimes and breakouts, highlighting sustainment via annotations and risk cues through VWAP—ideal atop price action for confirmation. It is not a standalone system, predictive oracle, or risk calculator; always integrate with broader analysis, position sizing, and stops. Use responsibly as an educational tool.
  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
TFRSI & RSI Analog Dial [CHE]  TFRSI & RSI Analog Dial    — Interactive analog visualization for TFRSI or RSI with gradient zones, radial markers, and a trailing hand pointer.
  Summary 
This indicator renders an interactive analog dial for either TFRSI or standard RSI, providing a visual gauge with gradient-filled zones for oversold, neutral, and overbought regions. The hand pointer tracks the current value, with optional trailing dots at recent positions to show momentum direction. Radial lines mark key thresholds, and a digital readout displays the exact value. This design enhances readability over linear plots by leveraging familiar clock-like intuition, reducing cognitive load during quick scans. Signals are robust due to clamping to safe bounds and mode-specific scaling, ensuring consistent display across different volatility regimes.
  Motivation: Why this design? 
Traditional linear RSI or momentum indicators often feel abstract, especially in fast-paced screening where users scan multiple assets. Sharp swings can make thresholds hard to gauge at a glance, leading to missed nuances in overbought or oversold conditions. This dial addresses that by mapping values to a curved scale with color gradients, making extremes visually pop while the hand's trail hints at recent path without cluttering the chart. The dual-mode support allows seamless switching between advanced momentum (TFRSI) and classic RSI, fitting diverse strategies without reloading scripts.
  What’s different vs. standard approaches? 
- Baseline reference: Diverges from linear plotlines like the built-in RSI oscillator, which stacks values vertically and relies on horizontal lines for thresholds.
- Architecture differences:
  - Curved projection with perspective tilt for depth illusion, using polyline arcs instead of straight plots.
  - Mode-aware clamping and scaling to handle TFRSI's extended range versus RSI's standard bounds.
  - Persistent trail array for hand history, capped at three points to avoid performance drag.
  - Gradient segmentation for smooth zone transitions, rendered via multiple thin polylines.
- Practical effect: Charts show a compact, rotatable dial that fits in pane corners, with colors intuitively signaling bias (lime for buy zones, red for sell). The trail adds qualitative flow without numerical overload, helping spot divergences faster than static bars.
  How it works (technical) 
The indicator first computes the selected metric: for TFRSI, it processes price accelerations through a multi-step filter involving differencing, exponential damping, and normalization to a centered scale; for RSI, it uses the standard gain-loss ratio over the specified period. The value is then clamped between mode-specific minimum and maximum bounds to prevent display overflow.
This clamped value drives the hand angle on a 300-degree arc, projected from a 3D-like model rotated for perspective. Arcs for zones are built as segmented polylines, with colors interpolated linearly across the gradient. Key levels are drawn as radial lines from inner to outer radius, colored by zone. The trail maintains up to three prior angles in an array, updated only on confirmed bars to avoid repainting, and rendered as sized dots fading from small to large.
Initialization seeds filter states to zero on first bar, with persistent variables holding smoothing history. Data flows from price to metric computation, clamping, angle mapping, and projection—all executed globally on the last bar for redraw efficiency.
  Parameter Guide 
Mode — Switches between TFRSI (extended momentum gauge) and RSI (classic oscillator); affects bounds, zones, and labels. Default: "TFRSI". Trade-offs: TFRSI adds sensitivity to accelerations but may amplify noise; RSI is more stable for trend confirmation.
Dial Size — Sets radius in pixels, scaling all elements proportionally. Default: 200. Bounds: 50–500. Tips: Larger for detailed views, smaller for multi-pane layouts; auto-scales hand length to match.
Dial Vertical Offset — Shifts entire dial up/down in pixels. Default: 0. Bounds: -200–200. Trade-offs: Negative pulls toward price action; positive spaces below—use to avoid overlap.
Camera Angle — Tilts view from top-down (0) to side (90) for 3D effect. Default: 45. Bounds: 0–90. Tips: Steeper angles emphasize depth but compress horizontally; flat for precision.
Resolution — Polygon sides for smooth arcs. Default: 64. Bounds: 4–64. Trade-offs: Higher reduces jaggedness but increases draw calls—balance with pane zoom.
TFRSI Hand Length — Base pointer length at 200px dial, auto-scaled. Default: 170. Bounds: 10–200. Tips: Longer for emphasis in large dials; shorter avoids edge clipping.
Show TFRSI Hand — Toggles pointer visibility. Default: true. Trade-offs: Off for clean zones only; on for value tracking.
Show Hand Trail Dots — Displays 3 fading dots at recent tips. Default: true. Trade-offs: Adds motion context but may clutter static views—disable in alerts.
TFRSI Hand Color — Pointer hue, used for trail dots too. Default: 7E57C2. Tips: Match strategy theme; gradients auto-blend to zones.
Dial Base Color — Arc outline/fill tint. Default: blue. Trade-offs: Opaque for contrast; transparent blends with background.
Neutral Color (50) — Mid-zone shade. Default: gray. Tips: Neutral tones reduce bias in balanced markets.
Oversold Color — Low-zone fill. Default: lime. Trade-offs: Bright for alerts; muted for subtlety.
Overbought Color — High-zone fill. Default: red. Trade-offs: As above—pair with hand blending.
Label Size — Text scaling for thresholds. Default: "normal". Options: tiny/small/normal/large/huge. Tips: Smaller for dense charts; larger for presentations.
Digital TFRSI Size — Readout font. Default: "large". Options: as above. Trade-offs: Balances visibility without dominating dial.
Digital Vertical Offset — Readout position shift. Default: -50. Bounds: -200–200. Tips: Negative centers above dial; adjust for multi-indicators.
TFRSI Length — Core lookback for accelerations. Default: 6. Min: 1. Trade-offs: Shorter heightens reactivity, risks whipsaws; longer smooths extremes.
TFRSI Trigger Length — Final smoothing passes. Default: 2. Min: 1. Tips: Increase for fewer false crosses; decrease for quicker pivots.
RSI Length — Period for gain-loss averaging. Default: 14. Min: 1. Trade-offs: Classic 14 balances; shorter for scalps, longer for swings.
  Reading & Interpretation 
The dial arcs sweep from overbought (right, red) through neutral (top, gray) to oversold (left, lime), with the hand pointing to the current value—clockwise for rising, counterclockwise for falling. Trail dots grow larger toward the present, colored to match hand zones, indicating recent direction without numbers. Threshold lines thicken at center (50) for quick zeroing; labels confirm levels. Digital readout below shows precise value prefixed by mode. Hand color gradients from neutral to extremes signal building pressure verbally: deepening red warns of potential pullbacks, brightening lime suggests bounces.
  Practical Workflows & Combinations 
Trend following: Enter long when hand crosses above 50 from oversold trail; confirm with higher highs in price structure. Filter shorts below 50 in downtrends using volume spikes.
Exits/Stops: Trail stops to recent dot positions in overbought; tighten on red gradients exceeding thresholds. Conservative: Exit at neutral; aggressive: Hold to extremes if trail aligns with momentum.
Multi-asset/Multi-TF: Defaults suit forex/stocks on 1H–4H; for crypto, shorten lengths by 20% for volatility. Stack with HTF security calls (e.g., daily mode on 15m chart) for confluence—watch for alignment across dials.
  Behavior, Constraints & Performance 
Closed-bar updates ensure no repainting; live bars show provisional hand/trail, confirmed on close. No security or HTF calls, so zero lookahead bias. Resources: Caps at 500 lines/labels/polylines, rebuilds only on last bar; max_bars_back=2000 handles history without lag. Known limits: Trail may stutter in flat markets; gradients approximate smooth fills via segments, visible at low resolution.
  Sensible Defaults & Quick Tuning 
Start with TFRSI mode, length=6, trigger=2 for responsive momentum on daily charts. Too choppy? Bump trigger to 4 for stability. Lagging entries? Drop length to 4, watch for overreactions. For RSI trend filter, set length=21; combine with MA cross for entries when dial nears 30/70.
  What this indicator is—and isn’t 
This is a visualization layer for momentum gauges, aiding quick bias assessment and threshold spotting. Pair it with price action, volume, and risk rules for decisions. It’s not a standalone signal generator or predictive tool—values reflect past data, prone to whipsaws in ranging conditions.
  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
3D Session Clock | Live Time with Sessions [CHE]  3D Session Clock | Live Time with Sessions   — Projects a perspective clock face onto the chart to display current time and market session periods for enhanced situational awareness during trading hours.
  Summary 
This indicator renders a three-dimensional clock projection directly on the price chart, showing analog hands for hours, minutes, and seconds alongside a digital time readout. It overlays session arcs for major markets like New York, London, Tokyo, and Sydney, highlighting the active one with thicker lines and contrasting labels. By centralizing time and session visibility, it reduces the need to reference external clocks, allowing traders to maintain focus on price action while noting overlaps or transitions that influence volatility.
The design uses perspective projection to simulate depth, making the clock appear tilted for better readability on varying chart scales. Sessions are positioned radially outward from the main clock, with the current time marker pulsing on the relevant arc. This setup provides a static yet live-updating view, confirmed on bar close to avoid intrabar shifts.
  Motivation: Why this design? 
Traders often miss subtle session shifts amid fast-moving charts, leading to entries during low-liquidity periods or exits before peak activity. Standard chart tools lack integrated time visualization, forcing constant tab-switching. This indicator addresses that by embedding a customizable clock with session rings, ensuring time context is always in view without disrupting workflow.
  What’s different vs. standard approaches? 
- Reference baseline: Traditional session highlighters use simple background fills or vertical lines, which clutter the chart and ignore global time zones.
- Architecture differences:
  - Perspective projection rotates and scales points to mimic 3D depth, unlike flat 2D drawings.
  - Nested radial arcs for sessions, with dynamic radius assignment to avoid overlap.
  - Live time calculation adjusted for user-selected time zones, including optional daylight savings offset.
- Practical effect: The tilted view prevents labels from bunching at chart edges, and active session emphasis draws the eye to liquidity hotspots, making multi-session overlaps immediately apparent for better timing.
  How it works (technical) 
The indicator calculates current time in the selected time zone by adjusting the system timestamp with a fixed offset, plus an optional one-hour bump for daylight savings. This yields hour, minute, and second values that drive hand positions: the hour hand advances slowly with fractional minute input, the minute hand ticks per 60 seconds, and the second hand sweeps fully each minute.
Points for the clock face and arcs are generated as arrays of coordinates, transformed via rotation around the x-axis to apply tilt, then projected onto chart space using a scaling factor based on depth. Radial lines mark every hour from zero to 23, extending to the outermost session ring. Session arcs span user-defined hour ranges, drawn as open polylines with step interpolation for smoothness.
On the last bar, all prior drawings are cleared, and new elements are added: filled clock circles, hand lines from center to tip, a small orbiting circle at the current time position, and centered labels for hours, sessions, and time. The active session is identified by checking if the current time falls within its range, then its arc thickens and label inverts colors. Initialization populates a timezone array once, with persistent bar time tracking for horizontal positioning.
  Parameter Guide 
Clock Size — Controls overall radius in pixels, affecting visibility on dense charts — Default: 200 — Larger values suit wide screens but may crowd small views; start smaller for mobile.
Camera Angle — Sets tilt from top-down (zero) to side (90 degrees), altering projection depth — Default: 45 — Steeper angles enhance readability on sloped trends but flatten at extremes.
Resolution — Defines polygon sides for circles and arcs, balancing smoothness and draw calls — Default: 64 — Higher improves curves on large clocks; lower aids performance on slow devices.
Hour/Minute/Second Hand Length — Scales each hand from center, with seconds longest for precision — Defaults: 100/150/180 — Proportional sizing prevents overlap; shorten for compact layouts.
Clock Base Color — Tints face and frame — Default: blue — Neutral shades reduce eye strain; match chart theme.
Hand Colors — Assigns distinct hues to each hand — Defaults: red/green/yellow — High contrast aids quick scans; avoid chart-matching to stand out.
Hour Label Size — Text scale for 1-12 markers — Default: normal — Larger for distant views, but risks clutter.
Digital Time Size — Scale for HH:MM:SS readout — Default: large — Matches clock for balance; tiny for minimalism.
Digital Time Vertical Offset — Shifts readout up (negative) or down — Default: -50 — Positions above clock to avoid hand interference.
Timezone — Selects reference city/offset — Default: New York (UTC-05) — Matches trading locale; verify offsets manually.
Summer Time (DST) — Adds one hour if active — Default: false — Enable for regions observing it; test transitions.
Show/Label/Session/Color for Each Market — Toggles arc, sets name, time window, and hue per session (New York/London/Tokyo/Sydney) — Defaults: true/"New York"/1300-2200/orange, etc. — Customize windows to local exchange hours; colors differentiate overlaps.
  Reading & Interpretation 
The analog face shows a blue-tinted circle with white 1-12 labels and gray hour ticks; hands extend from center in assigned colors, pointing to current positions. A white dot with orbiting ring marks exact time on the session arc. Digital readout below displays padded HH:MM:SS in white on black.
Active sessions glow with bold arcs and white labels on colored backgrounds; inactive ones use thin lines and colored text on light fills. Overlaps stack outward, with the innermost (New York) closest to the clock. If no session is active, the marker sits on the base ring.
  Practical Workflows & Combinations 
- Trend following: Enter longs during London-New York overlap (thicker dual arcs) confirmed by higher highs; filter with volume spikes.
- Exits/Stops: Tighten stops pre-Tokyo open if arc thickens, signaling volatility ramp; trail during Sydney for overnight holds.
- Multi-asset/Multi-TF: Defaults work across forex/stocks; on higher timeframes, enlarge clock size to counter bar spacing. Pair with session volume oscillators for confirmation.
  Behavior, Constraints & Performance 
Rendering occurs only on the last bar, using confirmed history for stable display; live bars update hands and marker without repainting prior elements. No security calls or higher timeframe fetches, so no lookahead bias.
Resource limits include 2000 bars back for positioning, 500 each for lines, labels, and boxes—sufficient for full sessions without overflow. Arrays hold timezone data statically. On very wide charts, projection may skew slightly due to fixed scale.
Known limits: Visual positioning drifts on extreme zooms; daylight savings assumes manual toggle, risking one-hour errors during changes.
  Sensible Defaults & Quick Tuning 
Start with New York timezone, 45-degree tilt, and all sessions enabled—these balance global coverage without clutter. For too-small visibility, bump clock size to 300 and resolution to 48. If labels overlap on narrow views, reduce hand lengths proportionally. To emphasize one session (e.g., London), disable others and widen its color contrast. For minimalism, set digital size to small and offset to -100.
  What this indicator is—and isn’t 
This is a visual time and session overlay to contextualize trading windows, not a signal generator or predictive tool. It complements price analysis and risk rules but requires manual interpretation. Use alongside order flow or momentum indicators for decisions.
  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 
  Acknowledgments 
This indicator draws inspiration from the open-source contributions of the TradingView community, whose advanced programming techniques have greatly influenced its development. Special thanks to LonesomeTheBlue for the innovative polyline handling and midpoint centering techniques in RSI Radar Multi Time Frame: 
Gratitude also extends to LuxAlgo for the precise timezone calculations in Sessions: 
Finally, appreciation to TradingView for their comprehensive documentation on polyline features, including the support article at www.tradingview.com and the blog post at www.tradingview.com These resources were instrumental in implementing smooth, dynamic drawings.
Mirpapa_Lib_RenkoLibrary   "Mirpapa_Lib_Renko" 
Mirpapa Renko Library - HL2 기반 ATR 렌코 차트 생성 라이브러리
 get_renko(atr_period, atr_multiplier) 
  ATR 기반 렌코 차트 생성
  Parameters:
     atr_period (simple int) : ATR 계산 기간
     atr_multiplier (float) : ATR 승수 (박스 크기 조절)
  Returns:   렌코 캔들 OHLC 값
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
Zero Lag Trend Signals (MTF) [Quant Trading] V7Overview 
The Zero Lag Trend Signals (MTF) V7 is a comprehensive trend-following strategy that combines Zero Lag Exponential Moving Average (ZLEMA) with volatility-based bands to identify high-probability trade entries and exits. This strategy is designed to reduce lag inherent in traditional moving averages while incorporating dynamic risk management through ATR-based stops and multiple exit mechanisms.
This is a longer term horizon strategy that takes limited trades. It is not a high frequency trading and therefore will also have limited data and not > 100 trades.
 How It Works 
 Core Signal Generation: 
The strategy uses a Zero Lag EMA (ZLEMA) calculated by applying an EMA to price data that has been adjusted for lag:
 
 Calculate lag period: floor((length - 1) / 2)
 Apply lag correction: src + (src - src )
 Calculate ZLEMA: EMA of lag-corrected price
 
Volatility bands are created using the highest ATR over a lookback period multiplied by a band multiplier. These bands are added to and subtracted from the ZLEMA line to create upper and lower boundaries.
 Trend Detection: 
The strategy maintains a trend variable that switches between bullish (1) and bearish (-1):
 
 Long Signal:  Triggers when price crosses above ZLEMA + volatility band
 Short Signal:  Triggers when price crosses below ZLEMA - volatility band
 
 Optional ZLEMA Trend Confirmation: 
When enabled, this filter requires ZLEMA to show directional momentum before entry:
 
 Bullish Confirmation:  ZLEMA must increase for 4 consecutive bars
 Bearish Confirmation:  ZLEMA must decrease for 4 consecutive bars
 
This additional filter helps avoid false signals in choppy or ranging markets.
 Risk Management Features: 
The strategy includes multiple stop-loss and take-profit mechanisms:
 
 Volatility-Based Stops:  Default stop-loss is placed at ZLEMA ± volatility band
 ATR-Based Stops:  Dynamic stop-loss calculated as entry price ± (ATR × multiplier)
 ATR Trailing Stop:  Ratcheting stop-loss that follows price but never moves against position
 Risk-Reward Profit Target:  Take-profit level set as a multiple of stop distance
 Break-Even Stop:  Moves stop to entry price after reaching specified R:R ratio
 Trend-Based Exit:  Closes position when price crosses EMA in opposite direction
 
 Performance Tracking: 
The strategy includes optional features for monitoring and analyzing trades:
 
 Floating Statistics Table:  Displays key metrics including win rate, GOA (Gain on Account), net P&L, and max drawdown
 Trade Log Labels:  Shows entry/exit prices, P&L, bars held, and exit reason for each closed trade
 CSV Export Fields:  Outputs trade data for external analysis
 
 Default Strategy Settings 
 Commission & Slippage: 
 
 Commission: 0.1% per trade
 Slippage: 3 ticks
 Initial Capital: $1,000
 Position Size: 100% of equity per trade
 
 Main Calculation Parameters: 
 
 Length: 70 (range: 70-7000) - Controls ZLEMA calculation period
 Band Multiplier: 1.2 - Adjusts width of volatility bands
 
 Entry Conditions (All Disabled by Default): 
 
 Use ZLEMA Trend Confirmation: OFF - Requires ZLEMA directional momentum
 Re-Enter on Long Trend: OFF - Allows multiple entries during sustained trends
 
 Short Trades: 
 
 Allow Short Trades: OFF - Strategy is long-only by default
 
 Performance Settings (All Disabled by Default): 
 
 Use Profit Target: OFF
 Profit Target Risk-Reward Ratio: 2.0 (when enabled)
 
 Dynamic TP/SL (All Disabled by Default): 
 
 Use ATR-Based Stop-Loss & Take-Profit: OFF
 ATR Length: 14
 Stop-Loss ATR Multiplier: 1.5
 Profit Target ATR Multiplier: 2.5
 Use ATR Trailing Stop: OFF
 Trailing Stop ATR Multiplier: 1.5
 Use Break-Even Stop-Loss: OFF
 Move SL to Break-Even After RR: 1.5
 Use Trend-Based Take Profit: OFF
 EMA Exit Length: 9
 
 Trade Data Display (All Disabled by Default): 
 
 Show Floating Stats Table: OFF
 Show Trade Log Labels: OFF
 Enable CSV Export: OFF
 Trade Label Vertical Offset: 0.5
 
 Backtesting Date Range: 
 
 Start Date: January 1, 2018
 End Date: December 31, 2069
 
 Important Usage Notes 
 
 Default Configuration:  The strategy operates in its most basic form with default settings - using only ZLEMA crossovers with volatility bands and volatility-based stop-losses. All advanced features must be manually enabled.
 Stop-Loss Priority:  If multiple stop-loss methods are enabled simultaneously, the strategy will use whichever condition is hit first. ATR-based stops override volatility-based stops when enabled.
 Long-Only by Default:  Short trading is disabled by default. Enable "Allow Short Trades" to trade both directions.
 Performance Monitoring:  Enable the floating stats table and trade log labels to visualize strategy performance during backtesting.
 Exit Mechanisms:  The strategy can exit trades through multiple methods: stop-loss hit, take-profit reached, trend reversal, or trailing stop activation. The trade log identifies which exit method was used.
 Re-Entry Logic:  When "Re-Enter on Long Trend" is enabled with ZLEMA trend confirmation, the strategy can take multiple long positions during extended uptrends as long as all entry conditions remain valid.
 Capital Efficiency:  Default setting uses 100% of equity per trade. Adjust "default_qty_value" to manage position sizing based on risk tolerance.
 Realistic Backtesting:  Strategy includes commission (0.1%) and slippage (3 ticks) to provide realistic performance expectations. These values should be adjusted based on your broker and market conditions.
 
 Recommended Use Cases 
 
 Trending Markets:  Best suited for markets with clear directional moves where trend-following strategies excel
 Medium to Long-Term Trading:  The default length of 70 makes this strategy more appropriate for swing trading rather than scalping
 Risk-Conscious Traders:  Multiple stop-loss options allow traders to customize risk management to their comfort level
 Backtesting & Optimization:  Comprehensive performance tracking features make this strategy ideal for testing different parameter combinations
 
 Limitations & Considerations 
 
 Like all trend-following strategies, performance may suffer in choppy or ranging markets
 Default 100% position sizing means full capital exposure per trade - consider reducing for conservative risk management
 Higher length values (70+) reduce signal frequency but may improve signal quality
 Multiple simultaneous risk management features may create conflicting exit signals
 Past performance shown in backtests does not guarantee future results
 
 Customization Tips 
For more aggressive trading:
 
 Reduce length parameter (minimum 70)
 Decrease band multiplier for tighter bands
 Enable short trades
 Use lower profit target R:R ratios
 
For more conservative trading:
 
 Increase length parameter
 Enable ZLEMA trend confirmation
 Use wider ATR stop-loss multipliers
 Enable break-even stop-loss
 Reduce position size from 100% default
 
For optimal choppy market performance:
 
 Enable ZLEMA trend confirmation
 Increase band multiplier
 Use tighter profit targets
 Avoid re-entry on trend continuation
 
 Visual Elements 
The strategy plots several elements on the chart:
 
 ZLEMA line (color-coded by trend direction)
 Upper and lower volatility bands
 Long entry markers (green triangles)
 Short entry markers (red triangles, when enabled)
 Stop-loss levels (when positions are open)
 Take-profit levels (when enabled and positions are open)
 Trailing stop lines (when enabled and positions are open)
 Optional ZLEMA trend markers (triangles at highs/lows)
 Optional trade log labels showing complete trade information
 
 Exit Reason Codes (for CSV Export) 
When CSV export is enabled, exit reasons are coded as:
 
 0 = Manual/Other
 1 = Trailing Stop-Loss
 2 = Profit Target
 3 = ATR Stop-Loss
 4 = Trend Change
 
 Conclusion 
Zero Lag Trend Signals V7 provides a robust framework for trend-following with extensive customization options. The strategy balances simplicity in its core logic with sophisticated risk management features, making it suitable for both beginner and advanced traders. By reducing moving average lag while incorporating volatility-based signals, it aims to capture trends earlier while managing risk through multiple configurable exit mechanisms.
The modular design allows traders to start with basic trend-following and progressively add complexity through ZLEMA confirmation, multiple stop-loss methods, and advanced exit strategies. Comprehensive performance tracking and export capabilities make this strategy an excellent tool for systematic testing and optimization.
 Note: This strategy is provided for educational and backtesting purposes. All trading involves risk. Past performance does not guarantee future results. Always test thoroughly with paper trading before risking real capital, and adjust position sizing and risk parameters according to your risk tolerance and account size. 
================================================================================
 TAGS: 
================================================================================
trend following, ZLEMA, zero lag, volatility bands, ATR stops, risk management, swing trading, momentum, trend confirmation, backtesting
================================================================================
 CATEGORY: 
================================================================================
Strategies
================================================================================
 CHART SETUP RECOMMENDATIONS: 
================================================================================
For optimal visualization when publishing:
 
 Use a clean chart with no other indicators overlaid
 Select a timeframe that shows multiple trade signals (4H or Daily recommended)
 Choose a trending asset (crypto, forex major pairs, or trending stocks work well)
 Show at least 6-12 months of data to demonstrate strategy across different market conditions
 Enable the floating stats table to display key performance metrics
 Ensure all indicator lines (ZLEMA, bands, stops) are clearly visible
 Use the default chart type (candlesticks) - avoid Heikin Ashi, Renko, etc.
 Make sure symbol information and timeframe are clearly visible
 
================================================================================
 COMPLIANCE NOTES: 
================================================================================
✅ Open-source publication with complete code visibility
✅ English-only title and description
✅ Detailed explanation of methodology and calculations
✅ Realistic commission (0.1%) and slippage (3 ticks) included
✅ All default parameters clearly documented
✅ Performance limitations and risks disclosed
✅ No unrealistic claims about performance
✅ No guaranteed results promised
✅ Appropriate for public library (original trend-following implementation with ZLEMA)
✅ Educational disclaimers included
✅ All features explained in detail
================================================================================
Holt Damped Forecast [CHE]A Friendly Note on These Pine Script Scripts 
Hey there! Just wanted to share a quick, heartfelt heads-up: All these Pine Script examples come straight from my own self-study adventures as a total autodidact—think late nights tinkering and learning on my own. They're purely for educational vibes, helping me (and hopefully you!) get the hang of Pine Script basics, cool indicators, and building simple strategies.
That said, please know this isn't any kind of financial advice, investment nudge, or pro-level trading blueprint. I'd love for you to dive in with your own research, run those backtests like a champ, and maybe bounce ideas off a qualified expert before trying anything in a real trading setup. No guarantees here on performance or spot-on accuracy—trading's got its risks, and those are totally on each of us.
Let's keep it fun and educational—happy coding! 😊
  Holt Damped Forecast    — Damped trend forecasts with fan bands for uncertainty visualization and momentum integration
  Summary 
This indicator applies damped exponential smoothing to generate forward price forecasts, displaying them as probabilistic fan bands to highlight potential ranges rather than point estimates. It incorporates residual-based uncertainty to make projections more reliable in varying market conditions, reducing overconfidence in strong trends. Momentum from the trend component is shown in an optional label alongside signals, aiding quick assessment of direction and strength without relying on lagging oscillators.
  Motivation: Why this design? 
Standard exponential smoothing often extrapolates trends indefinitely, leading to unrealistic forecasts during mean reversion or weakening momentum. This design uses damping to gradually flatten long-term projections, better suiting real markets where trends fade. It addresses the need for visual uncertainty in forecasts, helping traders avoid entries based on overly optimistic point predictions.
  What’s different vs. standard approaches? 
- Reference baseline: Diverges from basic Holt's linear exponential smoothing, which assumes persistent trends without decay.
- Architecture differences:
  - Adds damping to the trend extrapolation for finite-horizon realism.
  - Builds fan bands from historical residuals for probabilistic ranges at multiple confidence levels.
  - Integrates a dynamic label combining forecast details, scaled momentum, and directional signals.
  - Applies tail background coloring to recent bars based on forecast direction for immediate visual cues.
- Practical effect: Charts show converging forecast bands over time, emphasizing shorter horizons where accuracy is higher. This visibly tempers aggressive projections in trends, making it easier to spot when uncertainty widens, which signals potential reversals or consolidation.
  How it works (technical) 
The indicator maintains two persistent components: a level tracking the current price baseline and a trend capturing directional slope. On each bar, the level updates by blending the current source price with a one-step-ahead expectation from the prior level and damped trend. The trend then adjusts by weighting the change in level against the prior damped trend. Forecasts extend this forward over a user-defined number of steps, with damping ensuring the trend influence diminishes over distance.
Uncertainty derives from the standard deviation of historical residuals—the differences between actual prices and one-step expectations—scaled by the damping structure for the forecast horizon. Bands form around the median forecast at specified confidence intervals using these scaled errors. Initialization seeds the level to the first bar's price and trend to zero, with persistence handling subsequent updates. A security call fetches the last bar index for tail logic, using lookahead to align with realtime but introducing minor repaint on unconfirmed bars.
  Parameter Guide 
The Source parameter selects the price input for level and residual calculations, defaulting to close; consider using high or low for assets sensitive to volatility, as close works well for most trend-following setups. Forecast Steps (h) defines the number of bars ahead for projections, defaulting to 4—shorter values like 1 to 5 suit intraday trading, while longer ones may widen bands excessively in choppy conditions. The Color Scheme (2025 Trends) option sets the base, up, and down colors for bands, labels, and backgrounds, starting with Ruby Dawn; opt for serene schemes on clean charts or vibrant ones to stand out in dark themes.
Level Smoothing α controls the responsiveness of the price baseline, defaulting to 0.3—values above 0.5 enhance tracking in fast markets but may amplify noise, whereas lower settings filter disturbances better. Trend Smoothing β adjusts sensitivity to slope changes, at 0.1 by default; increasing to 0.2 helps detect emerging shifts quicker, but keeping it low prevents whipsaws in sideways action. Damping φ (0..1) governs trend persistence, defaulting to 0.8—near 0.9 preserves carryover in sustained moves, while closer to 0.5 curbs overextensions more aggressively.
Show Fan Bands (50/75/95) toggles the probabilistic range display, enabled by default; disable it in oscillator panes to reduce clutter, but it's key for overlay forecasts. Residual Window (Bars) sets the length for deviation estimates, at 400 bars initially—100 to 200 works for short timeframes, and 500 or more adds stability over extended histories. Line Width determines the thickness of band and median lines, defaulting to 2; go thicker at 3 to 5 for emphasis on higher timeframes or thinner for layered indicators.
Show Median/Forecast Line reveals the central projection, on by default—hide if bands provide enough detail, or keep for pinpoint entry references. Show Integrated Label activates the combined view of forecast, momentum, and signal, defaulting to true; it's right-aligned for convenience, so turn it off on smaller screens to save space. Show Tail Background colors the last few bars by forecast direction, enabled initially; pair low transparency for subtle hints or higher for bolder emphasis.
Tail Length (Bars) specifies bars to color backward from the current one, at 3 by default—1 to 2 fits scalping, while 5 or more underscores building momentum. Tail Transparency (%) fades the background intensity, starting at 80; 50 to 70 delivers strong signals, and 90 or above allows seamless blending. Include Momentum in Label adds the scaled trend value, defaulting to true—ATR% scaling here offers relative strength context across assets.
Include Long/Short/Neutral Signal in Label displays direction from the trend sign, on by default; neutral helps in ranging markets, though it can be overlooked during strong trends. Scaling normalizes momentum output (raw, ATR-relative, or level-relative), set to ATR% initially—ATR% ensures cross-asset comparability, while %Level provides percentage perspectives. ATR Length defines the period for true range averaging in scaling, at 14; align it with your chart timeframe or shorten for quicker volatility responses.
Decimals sets precision in the momentum label, defaulting to 2—0 to 1 yields clean integers, and 3 or more suits detailed forex views. Show Zero-Cross Markers places arrows at direction changes, enabled by default; keep size small to minimize clutter, with text labels for fast scanning.
  Reading & Interpretation 
Fan bands expand outward from the current bar, with the median line as the central forecast—narrower bands indicate lower uncertainty, wider suggest caution. Colors tint up (positive forecast vs. prior level) in the scheme's up hue and down otherwise. The optional label lists the horizon, median, and range brackets at 50%, 75%, and 95% levels, followed by momentum (scaled per mode) and signal (Long if positive trend, Short if negative, Neutral if zero). Zero-cross arrows mark trend flips: upward triangle below bar for bullish cross, downward above for bearish. Tail background reinforces the forecast direction on recent bars.
  Practical Workflows & Combinations 
- Trend following: Enter long on upward zero-cross if median forecast rises above price and bands contain it; confirm with higher highs/lows. Short on downward cross with falling median.
- Exits/Stops: Trail stops below 50% lower band in longs; exit if momentum drifts negative or signal turns neutral. Use wider bands (75/95%) for conservative holds in volatile regimes.
- Multi-asset/Multi-TF: Defaults work across stocks, forex, crypto on 5m-1D; scale steps by TF (e.g., 10+ on daily). Layer with volume or structure tools—avoid over-reliance on isolated crosses.
  Behavior, Constraints & Performance 
Closed-bar logic ensures stable historical plots, but realtime updates via security lookahead may shift forecasts until bar confirmation, introducing minor repaint on the last bar. No explicit HTF calls beyond bar index fetch, minimizing gaps but watch for low-liquidity assets. Resources include a 2000-bar lookback for residuals and up to 500 labels, with no loops—efficient for most charts. Known limits: Early bars show wide bands due to sparse residuals; assumes stationary errors, so gaps or regime shifts widen inaccuracies.
  Sensible Defaults & Quick Tuning 
Start with defaults for balanced smoothing on 15m-4H charts. For choppy conditions (too many crosses), lower β to 0.05 and raise residual window to 600 for stability. In trending markets (sluggish signals), increase α/β to 0.4/0.2 and shorten steps to 2. If bands overexpand, boost φ toward 0.95 to preserve trend carry. Tune colors for theme fit without altering logic.
  What this indicator is—and isn’t 
This is a visualization and signal layer for damped forecasts and momentum, complementing price action analysis. It isn’t a standalone system—pair with risk rules and broader context. Not predictive beyond the horizon; use for confirmation, not blind entries.
  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 
Relative Momentum Rotation [CHE]  Relative Momentum Rotation   — Ranks assets by multi-horizon momentum for guided rotational selection with regime overlay
  Summary 
This indicator evaluates a universe of assets using a blended momentum measure across three time horizons, then ranks them to highlight top performers for potential portfolio rotation. It incorporates a regime filter to contextualize signals, tinting the background to indicate favorable or unfavorable market conditions and labeling transitions for awareness. By focusing on relative strength within a selectable universe, it helps identify leaders without relying on absolute thresholds, reducing noise from isolated trends and promoting disciplined asset switching.
  Motivation: Why this design? 
Traders often struggle with momentum signals that perform unevenly across market phases, such as overreacting in volatile periods or lagging in steady uptrends, leading to suboptimal rotations in multi-asset portfolios. The core idea of relative momentum rotation addresses this by comparing assets head-to-head within a defined group, blending short- and long-term changes to capture sustained strength while a regime overlay adds a macro layer to avoid fighting broader trends. This setup prioritizes peer-relative outperformance over standalone measures, aiding consistent selection in rotational strategies.
  What’s different vs. standard approaches? 
- Reference baseline: Traditional rate-of-change indicators track absolute price shifts over a single window, which can generate whipsaws in sideways markets or miss cross-asset opportunities.
- Architecture differences:
  - Blends three distinct horizons into one composite score for a fuller momentum picture, rather than isolating one period.
  - Applies ranking across a customizable universe (e.g., crypto or tech stocks) to emphasize relatives, not absolutes.
  - Integrates a simple regime check via moving average crossover on a reference symbol, gating selections without overcomplicating the core logic.
  - Outputs a dynamic table for visual ranking, plus subtle visual cues like background tints, instead of cluttered plots.
- Practical effect: Charts show clearer hierarchy among assets, with regime tints providing at-a-glance context—top ranks stand out more reliably in bull regimes, helping traders focus rotations without constant recalibration.
  How it works (technical) 
The indicator starts by assembling a list of symbols from the selected universe, including only those marked as active to keep the group focused. For each symbol, it gathers change rates over three specified horizons on a higher timeframe, blends them using user-defined weights (automatically normalized if they do not sum to one), and computes a single composite score. Scores are then ranked to select the top performers up to a set number, forming a rotation candidate list.
To add context, a regime state is determined by comparing the reference symbol's price to its moving average on daily bars—above signals a positive environment, below a negative one, with an option to invert this logic. The current chart's symbol is checked against the top list for inclusion status. All higher-timeframe data pulls are set to avoid lookahead bias, though updates may shift slightly until bars close. Persistent variables track the table state and prior regime to handle redraws efficiently, ensuring the display rebuilds only when the selection count changes.
  Parameter Guide 
Universe — Switches between predefined crypto or US-tech symbol sets for ranking peers. Default: Crypto. Trade-offs/Tips: Crypto for volatile assets; US-Tech for equities—match to your portfolio to avoid mismatched volatility.
Include Symbol 1–12 — Toggles individual symbols in the universe on or off. Default: Varies (true for top 10, false for extras). Trade-offs/Tips: Start with defaults for a balanced group; disable laggards to sharpen focus, but keep at least 5–8 for robust ranking.
Scoring Timeframe — Sets the aggregation period for momentum changes (e.g., monthly bars). Default: Monthly. Trade-offs/Tips: Monthly for long-term rotation; weekly for faster signals—increases noise if too short.
Weight 12m / 6m / 3m — Adjusts emphasis on long/medium/short horizons in the blend. Default: 0.50 / 0.30 / 0.20. Trade-offs/Tips: Heavier long-term for stability in trends; balance to fit asset class—test sums near 1.0 to avoid auto-normalization surprises.
ROC over MA instead of Close — Uses smoothed averages for change rates to reduce chop. Default: False. Trade-offs/Tips: Enable in noisy markets for fewer false tops; adds slight lag, so monitor for delayed rotations.
Top N to hold — Limits selections to this many highest-ranked assets. Default: 10. Trade-offs/Tips: Lower for concentrated bets (higher risk/reward); higher for diversification—align with your position sizing.
Mark current symbol if in Top N — Highlights if the chart's asset ranks in the selection. Default: True. Trade-offs/Tips: Useful for self-scanning; disable in multi-chart setups to declutter.
Enable Regime Filter — Activates macro overlay using reference symbol. Default: True. Trade-offs/Tips: Core for trend-aware trading; disable for pure momentum plays, but risks counter-trend entries.
Regime Symbol — Chooses the benchmark for regime (e.g., broad index). Default: QQQ. Trade-offs/Tips: Broad market proxy like SPY for equities; swap for BTC in crypto to match universe.
SMA Length (D) — Sets the averaging window for regime comparison. Default: 100. Trade-offs/Tips: Longer for fewer flips (smoother regimes); shorter for quicker detection—default suits daily checks.
Invert (rare) — Flips the regime logic (price above average becomes negative). Default: False. Trade-offs/Tips: Only if your view inverts the benchmark; test thoroughly as it reverses all tints/labels.
Show Ranking Table — Displays the ranked list with scores and regime status. Default: True. Trade-offs/Tips: Essential for selection; position tweaks help on crowded charts.
Table X / Y — Places the table on the chart (e.g., top-right). Default: Right / Top. Trade-offs/Tips: Corner placement avoids price overlap; middle for central focus in reviews.
Dark Theme — Applies inverted colors for visibility. Default: True. Trade-offs/Tips: Matches most TradingView themes; toggle for light backgrounds without losing contrast.
Text Size — Scales table font for readability. Default: Normal. Trade-offs/Tips: Smaller for dense data; larger on big screens—impacts only last-bar render.
Background Tint by Regime — Colors the chart faintly green/red based on state. Default: True. Trade-offs/Tips: Subtle cue for immersion; disable if it distracts from price action.
Label on Regime Flip — Adds text markers at state changes. Default: True. Trade-offs/Tips: Aids journaling flips; space them by disabling in low-vol periods to cut clutter.
 Reading & Interpretation
The ranking table lists top assets by position, symbol, percentage score (higher indicates stronger blended momentum), and regime status—green "ON" for favorable, red "OFF" for cautionary. Background shifts to a light teal in positive regimes (suggesting alignment for longs) or pale red in negative ones (hinting at reduced exposure). Flip labels appear as green "Regime ON" above bars or red "Regime OFF" below, marking transitions without ongoing noise. If the current symbol appears in the top rows with a solid score, it signals potential hold or entry priority within rotations.
  Practical Workflows & Combinations 
- Trend following: Scan the table weekly on monthly charts for top entrants; confirm with higher highs/lows in price structure before rotating in. Use regime tint as a veto—skip buys in red phases.
- Exits/Stops: Rotate out of bottom-half ranks monthly; tighten stops below recent lows during regime flips to protect against reversals. Pair with volatility filters like average true range for dynamic sizing.
- Multi-asset/Multi-TF: Defaults work across crypto/equities on daily+ timeframes; for intraday, shorten scoring to weekly but expect more interim noise. Scale universe size with portfolio count—e.g., top 5 for aggressive crypto rotations.
  Behavior, Constraints & Performance 
Signals update on bar close to confirm higher-timeframe data, but live bars may preview shifts from security calls, introducing minor repaint until finalized—mitigated by non-lookahead settings, though daily regime checks can lag by one session. Arrays handle up to 12 symbols efficiently, with loops capped at selection size; max bars back at 5000 supports historical depth without overload. Resource use stays low, but dense universes on very long charts may slow initial loads.
Known limits include sensitivity to universe composition (skewed groups amplify biases) and regime lag at sharp market turns, potentially delaying rotations by a period.
  Sensible Defaults & Quick Tuning 
Defaults assume a 10-asset crypto rotation on monthly scoring with balanced weights and QQQ regime—ideal for intermediate-term equity-like plays. For too-frequent table reshuffles, extend scoring timeframe or weight longer horizons more. If selections feel sluggish, shorten the 3-month weight or enable MA smoothing off. In high-vol environments, raise top N and SMA length for stability; for crypto bursts, drop to weekly scoring and invert regime if using a volatile proxy.
  What this indicator is—and isn’t 
This is a selection and visualization tool for momentum-based rotations, layering relative ranks and regime context onto charts to inform asset picks. It is not a standalone system—pair it with entry/exit rules, position sizing, and risk limits. Nor is it predictive; it reacts to past changes and may underperform in prolonged ranges or during universe gaps.
  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 
 Where does it come from, specifically? 
The principle of “composite momentum across multiple horizons” is common in TAA/rotation strategies. As a documented example: Keller/Butler use a composite 1/3/6/12-month momentum (“13612W”)—same idea, different windows/weights.
Robot Wealth
A practical vendor example: EPS Momentum calculates an RMR composite as a weighted mix of 12/6/3/1-month ranks (very close to “12/6/3”).
EPS Momentum
Related but not identical: StockCharts’ RRG measures the momentum rotation of relative strength—often mentioned in the same context, but it doesn’t have a fixed “12/6/3” composite.
chartschool.stockcharts.com
How is it typically computed?
ROC_12 + ROC_6 + ROC_3 (often scaled/weighted), then ranked vs. peers; the rotation periodically holds the top ranks in the portfolio. (Variants use different weights or additionally include 1-month—see the sources above.)
robotwealth.com
epsmomentum.com
PM Range Breaker [CHE]  PM Range Breaker   — Premarket bias with first-five range breaks, optional SWDEMA regime latch, and simple two-times-range targets
  Summary 
This indicator sets a once-per-day directional bias during New York premarket and then tracks a strict first-five-minutes range from the session open. After the first five complete, it marks clean breakouts and can project targets at two times the measured range. A second mode latches an EMA-based regime to inform the bias and optional background tinting. A compact panel reports live state, first-five levels, and rolling hit rates of both bias modes using a user-defined midday close for statistics.
  Motivation: Why this design? 
Intraday traders often get whipsawed by early noise or by fast flips in trend filters. This script commits to a bias at a single premarket minute and then waits for the market to present an objective structure: the first-five range. Breaks after that window are clearer and easier to manage. The alternative SWDEMA regime gives a slower, latched context for users who prefer a trend scaffold rather than a midpoint reference.
  What’s different vs. standard approaches? 
 Baseline: Typical open-range-breakout lines or a single moving-average filter without daily commitment.
 Architecture differences:
   Bias decision at a fixed New York time using either a midpoint lookback (“Classic”) or a two-EMA regime latch (“SWDEMA”).
   Strict five-minute window from session open; breakout shapes print only after that window.
   Single-shot breakout direction per session (debounce) and optional two-times-range targets.
   On-chart panel with hit rates using a configurable midday close for statistics.
 Practical effect: Cleaner visuals, fewer repeated signals, and a traceable daily decision that can be evaluated over time.
  How it works (technical) 
 Time handling uses New York session times for premarket decision, open, first-five end, and a midday statistics checkpoint.
 Classic bias: A midpoint is computed from the highest and lowest over a user period; at the premarket minute, the bias is set long when the close is above the midpoint, short otherwise.
 SWDEMA bias: Two EMAs define a regime score that requires price and trend agreement; when both agree on a confirmed bar, the regime latches. At the premarket minute, the daily bias is set from the current regime.
 The first-five range captures high and low from open until the end minute, then freezes. Breakouts are detected after that window using close-based cross logic.
 The script draws range lines and optional targets at two times the frozen range. A session break direction latch prevents duplicate break markers.
 Statistics compare daily open and a configurable midday close to record if the chosen bias aligned with the move.
 Optional elements include EMA lines, midpoint line, latched-regime background, and regime switch markers.
 Data aggregation for day logic and the first-five window is sampled on one-minute data with explicit lookahead off. On charts above one minute, values update intra-bar until the underlying minute closes.
  Parameter Guide 
Premarket Start (NY) — Minute when the bias is decided — Default: 08:30 — Move earlier for more stability; later for recency.
Market Open (NY) — Session start used for the first-five window — Default: 09:30 — Align to instrument’s RTH if different.
First-5 End (NY) — End of the first-five window — Default: 09:35 — Extend slightly to capture wider opening ranges.
Day End (NY) for Stats — Midday checkpoint for hit rate — Default: 12:00 — Use a later time for a longer evaluation window.
Show First-5 Lines — Draw the frozen range lines — Default: On — Turn off if your chart is crowded.
Show Bias Background (Session) — Tint by daily bias during session — Default: On — Useful for directional context.
Show Break Shapes — Print breakout triangles — Default: On — Disable if you only want lines and alerts.
Show 2R Targets (Optional) — Plot targets at two times the range — Default: On — Switch off if you manage exits differently.
Line Length Right — Extension length of drawn lines — Default: 20 (bars) — Increase for slower timeframes.
High/Low Line Colors — Visual colors for range levels — Defaults: Green/Red — Adjust to your theme.
Long/Short Bias Colors — Background tints — Defaults: Green/Red with high transparency — Lower transparency for stronger emphasis.
Show Corner Panel — Enable the info panel — Default: On — Centralizes status and numbers.
Show Hit Rates in Panel — Include success rates — Default: On — Turn off to reduce panel rows.
Panel Position — Anchor on chart — Default: Top right — Move to avoid overlap.
Panel Size — Text size in panel — Default: Small — Increase on high-resolution displays.
Dark Panel — Dark theme for the panel — Default: On — Match your chart background.
Show EMA Lines — Plot blue and red EMAs — Default: Off — Enable for SWDEMA context.
Show Midpoint Line — Plot the midpoint — Default: Off — Useful for Classic mode visualization.
Midpoint Lookback Period — Bars for high-low midpoint — Default: 300 — Larger values stabilize; smaller values respond faster.
Midpoint Line Color — Color for midpoint — Default: Gray — A neutral line works best.
SWDEMA Lengths (Blue/Red) — Periods for the two EMAs — Defaults: 144 and 312 — Longer values reduce flips.
Sources (Blue/Red) — Price sources — Defaults: Close and HLC3 — Adjust if you prefer consistency.
Offsets (Blue/Red) — Pixel offsets for EMA plots — Defaults: zero — Use only for visual shift.
Show Latched Regime Background — Background by SWDEMA regime — Default: Off — Separate from session bias.
Latched Background Transparency — Opacity of regime background — Default: eighty-eight — Lower value for stronger tint.
Show Latch Switch Markers — Plot regime change markers — Default: Off — For auditing regime changes.
Bias Mode — Classic midpoint or SWDEMA latch — Default: Classic — Choose per your style.
Background Mode — Session bias or SWDEMA regime — Default: Session — Decide which background narrative you want.
  Reading & Interpretation 
 Panel: Shows the active bias, first-five high and low, and a state that reads Building during the window, Ready once frozen, and Break arrows when a breakout occurs. Hit rates show the percentage of days where each bias mode aligned with the midday move.
 Colors and shapes: Green background implies long bias; red implies short bias. Triangle markers denote the first valid breakout after the first-five window. Optional regime markers flag regime changes.
 Lines: First-five high and low form the core structure. Optional targets mark a level at two times the frozen range from the breakout side.
  Practical Workflows & Combinations 
 Trend following: Choose a bias mode. Wait for the first clean breakout after the first-five window in the direction of the bias. Confirm with structure such as higher highs and higher lows or lower highs and lower lows.
 Exits and risk: Conservative users can trail behind the opposite side of the first-five range. Aggressive users can scale near the two-times-range target.
 Multi-asset and multi-TF: Works well on intraday timeframes from one minute upward. For non-US sessions, adjust the time inputs to the instrument’s regular trading hours.
  Behavior, Constraints & Performance 
 Repaint and confirmation: Bias and regime decisions use confirmed bars. Breakout signals evaluate on bar close at the chart timeframe. On higher timeframes, minute-based sources update within the live bar until the minute closes.
 security and HTF: The script samples one-minute data. Lookahead is off. Values stabilize once the source minute closes.
 Resources: `max_bars_back` is five thousand. Drawing objects and the panel update efficiently, with position extensions handled on the last bar.
 Known limits: Midday statistics use the configured time, not the official daily close. Session logic assumes New York session timing. Targets are simple multiples of the first-five range and do not adapt to volatility beyond that structure.
  Sensible Defaults & Quick Tuning 
Start with Classic bias, midpoint lookback at three hundred, and all visuals on.
 Too many flips in context → switch to SWDEMA mode or increase EMA lengths.
 Breakouts feel noisy → extend the first-five end by a minute or two, or wait for a retest by your own rules.
 Too sluggish → reduce midpoint lookback or shorten EMA lengths.
 Chart cluttered → hide EMA or midpoint lines and keep only range levels and breakout shapes.
  What this indicator is—and isn’t 
This is a visualization and signal layer for session bias and first-five structure. It does not manage orders, position sizing, or risk. It is not predictive. Use it alongside market structure, execution rules, and independent risk controls.
 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 
Many thanks to LonesomeTheBlue
 for the original work. I adapted the midpoint calculation for this script. www.tradingview.com 
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
NY 4H Wyckoff State Machine [CHE]  NY 4H Wyckoff State Machine  — Full (Re-Entry, Breakout, Wick, Re-Accum/Distrib, Dynamic Table) — One-Candle Wyckoff Re-Entry (OCWR)
  Summary 
OCWR operationalizes a one-candle session workflow: mark the first four-hour New York candle, fix its high and low as the session range when the window closes, and drive entries through a Wyckoff-style state machine on intraday bars. The script adds an ATR-scaled buffer around the range and requires multi-bar acceptance before treating breaks or re-entries as valid. Optional wick-cluster evidence, a proximity retest, and simple volume or RSI gates increase selectivity. Background tints expose regimes, shapes mark events, a dynamic table explains the current state, and hidden plots supply alert payloads. The design reduces random flips and makes state transitions auditable without higher-timeframe calls.
  Origin and name 
Method name: One-Candle Wyckoff Re-Entry (OCWR)
Transcript origin: The source idea is a “stupid simple one-candle scalping” routine: mark the first New York four-hour candle (commonly between one and five in the morning New York time), drop to five minutes, observe accumulation inside, wait for a manipulation move outside, then trade the re-entry back inside. Stops go beyond the excursion extreme; targets are either a fixed reward multiple or the opposite side of the range. Preference is given to several manipulation candles. This indicator codifies that workflow with explicit states, acceptance counters, buffers, and optional quality filters. Any external performance claims are not part of the code.
  Motivation: Why this design? 
Session levels are widely respected, yet single-bar breaches around them are noisy. OCWR separates range discovery from trade logic. It locks the range at the end of the window, applies an ATR-scaled buffer to ignore marginal oversteps, and requires acceptance over several bars for breaks and re-entries. Wick evidence and optional retest proximity help confirm that an excursion likely cleared liquidity rather than launched a trend. This yields cleaner transitions from test to commitment.
  What’s different vs. standard approaches? 
 Baseline: Static session lines or one-shot Wyckoff tags without process control.
 Architecture: Dual long and short state machines; ATR-buffered edges; multi-bar acceptance for breaks and re-entries; optional wick dominance and cluster checks; optional retest tolerance; direct and opposite breakout paths; cooldown after fires; distribution timeout; dynamic table with highlighted row.
 Practical effect: Fewer single-bar head-fakes, clearer hand-offs, and on-chart explanations of the machine’s view.
  Wyckoff structure by example — OCWR on five minutes 
One-candle setup:
On the four-hour chart, mark the first New York candle’s high and low, then switch to five minutes. Solid lines show the fixed range; dashed lines show ATR-buffered edges.
 Long path (verbal mapping): 
 Phase A, Stopping Action: Price stabilizes inside the range.
 Phase B, Consolidation: Sustained balance while the window is closed and after the range is fixed.
 Phase C, Test (Spring): Excursion below the buffered low with preference for several outside bars and dominant lower wicks, then a return inside.
 Re-entry acceptance: A required run of inside bars validates the test.
 Phase D, Breakout to Markup: Long signal fires; stop beyond the excursion extreme; objective is the opposite range or a fixed reward multiple.
 Phase E, Trend (Markup) and Re-Accumulation: Advance continues until target, stop, confirmation back against the box, or timeout. A pause inside trend may register as re-accumulation.
Short path mirrors the above: A UTAD-style move forms above the buffered high, then re-entry leads to Markdown and possible re-distribution.
 Variant map (verbal): 
 Accumulation after a downtrend: with Spring and Test, or without Spring; both proceed to Markup and may pause in Re-Accumulation.
 Distribution after an uptrend: with UTAD and Test, or without UTAD; both proceed to Markdown and may pause in Re-Distribution.
  Note: Phases A through E occur within each variant and are not separate variants.
  How it works (technical) 
 Session window: A configurable four-hour New York window records its high and low. At window end, the bounds are fixed for the session.
 ATR buffer: A margin above and below the fixed range discourages triggers from tiny oversteps.
 Inside and outside: Users choose close-based or wick-based detection. Overshoot requirements are expressed verbally as a fraction of the range with an optional absolute minimum.
 Manipulation tracking: The machine counts bars spent outside and records the side extreme.
 Re-entry acceptance: After a return inside, a specified number of inside bars must print before acceptance.
 Direct and opposite breakouts: Direct breakouts from accumulation and opposite breakouts after manipulation are supported, subject to acceptance and optional filters.
 Targets and exits: Choose the opposite boundary or a fixed reward multiple. Distribution ends on target, stop, confirmation back against the range, or timeout.
 Context filters (optional): Volume above a scaled SMA, RSI thresholds, and a trend SMA for simple regime context.
 Diagnostics: Background tints for regimes; arrows for re-entries; triangles for breakouts; table with row highlights; hidden plots for alert values.
  Central table (Wyckoff console) 
The table sits top-right and explains the machine’s stance. Columns: Structure label, plain-English description, active state pair for long and short, and human phase tags. Rows: Start and range building; accumulation branch with Spring and Test as well as direct breakout; Markup and re-accumulation; distribution branch with UTAD and Test as well as direct short breakout; Markdown and re-distribution. Only the active state cell is rewritten each last bar, for example “L_ACCUM slash S_ACCUM”. Row highlighting is context-aware: accumulation, Spring or UTAD, breakout, Markup or Markdown, and re-accumulation or re-distribution checks can highlight independently so users see simultaneous conditions. The table is created once, updated only on the last bar for efficiency, and functions as a read-only console to audit why a signal fired and where the path currently sits.
  Parameter Guide 
 Session window and time zone: First four hours of New York by default; time zone “America/New_York”.
 ATR length and buffer factor: Control buffer size; larger reduces sensitivity, smaller reacts faster.
 Minimum overshoot (fraction and absolute): Demand meaningful extension beyond the buffer.
 Break mode: Close-based is stricter; wick-based is more reactive.
 Acceptance counts: Separate counts for break, re-entry, and opposite breakout; higher values reduce noise.
 Minimum bars outside: Ensures manipulation is not a single spike.
 Wick detection and clusters (optional): Dominance thresholds and cluster size within a short window.
 Retest required and tolerance (optional): Gate re-entry by proximity to the buffered edge.
 Volume and RSI filters (optional): Simple gates on activity and momentum.
 TP mode and reward multiple: Opposite range or fixed multiple.
 Cooldown and distribution timeout: Rate-limit signals and prevent endless distribution.
 Visualization toggles: Background phases, labels, table, and helper lines.
  Reading & Interpretation 
Solid lines are the fixed session bounds; dashed lines are buffers. Backgrounds tint accumulation, manipulation, and distribution. Arrows show accepted re-entries; triangles show direct or opposite breakouts. Labels can summarize entry, stop, target, and risk. The table highlights the active row and the current state pair.
  Practical Workflows & Combinations 
 OCWR baseline: Each morning, mark the New York four-hour candle, move to five minutes, prefer multi-bar manipulation outside, then wait for a qualified re-entry inside. Stop beyond the excursion extreme. Target the opposite range for conservative management or a fixed multiple for uniform sizing.
 Trend following: Favor direct breakouts with trend alignment and no contradictory wick evidence.
 Quality control: When noise rises, increase acceptance, raise the buffer factor, enable retest, and require wick clusters.
 Discretionary confluences: Fair-value gaps and trend lines can be added by the user; they are not computed by this script.
  Behavior, Constraints & Performance 
Closed-bar confirmation is recommended when you require finality; live-bar conditions can change until close. The script does not call higher-timeframe data. It uses arrays, lines, labels, boxes, and a table; maximum bars back is five thousand; table updates are last-bar only. Known limits include compressed buffers in quiet sessions, unreliable wick evidence in thin markets, and session misalignment if the platform time zone is not New York.
  Sensible Defaults & Quick Tuning 
Start with ATR length fourteen, buffer factor near zero point fifteen, overshoot fraction near zero point ten, acceptance counts of two, minimum outside duration three, retest required on.
Too many flips: increase acceptance, raise buffer, enable retest, and tighten wick thresholds.
Too slow: reduce acceptance, lower buffer, switch to wick-based breaks, disable retest.
Noisy wicks: increase minimum wick ratio and cluster size, or disable wick detection.
  What this indicator is—and isn’t 
A session-anchored visualization and signal layer that formalizes a Wyckoff-style re-entry and breakout workflow derived from a single four-hour New York candle. It is not predictive and not a complete trading system. Use with structure analysis, risk controls, and position management.
  Disclaimer 
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
 Best regards and happy trading
Chervolino 
Experimental Supertrend [CHE]Experimental Supertrend   — Combines EMA crossovers for trend regime detection with an adaptive ATR-based hull that selects the narrowest band to contain recent highs and lows, minimizing false breaks in varying volatility.
  Summary 
This indicator overlays a dynamic supertrend boundary around a midline derived from dual EMAs, using EMA crossovers to switch between bullish and bearish regimes. The hull adapts by evaluating multiple ATR periods and selecting the tightest one that fully encloses price action over a specified window, which helps in creating more stable trend lines that hug price without excessive gaps or breaches. Fills between the midline and hull provide visual cues for trend strength, darkening temporarily after regime changes to highlight transitions. Alerts trigger on crossovers, and markers label entry points, making it suitable for trend-following setups where standard supertrends might whipsaw. Overall, it offers robustness through auto-adjustment, reducing sensitivity to noise while maintaining responsiveness to genuine shifts.
  Motivation: Why this design? 
Standard supertrend indicators often flip prematurely in choppy markets due to fixed multipliers that do not account for localized volatility patterns, leading to frequent false signals and eroded confidence in trends. This design addresses that by incorporating an EMA-based regime filter for directional bias and an auto-adaptive hull that dynamically tunes the band width based on recent price containment needs. By prioritizing the narrowest effective enclosure, it avoids over-wide bands in calm periods that cause lag or under-wide ones in volatility spikes that invite breaks, providing a more consistent trailing reference without manual tweaking.
  What’s different vs. standard approaches? 
- Reference baseline: Diverges from the classic ATR-multiplier supertrend, which uses a single fixed period and constant factor applied to close or high/low deviations.
- Architecture differences:
  - Auto-selection from candidate ATR lengths to find the optimal period for current conditions.
  - Dynamic multiplier clamped between floor and cap values, adjusted by padding to ensure reliable containment.
  - Regime-gated rendering, where hull position flips based on EMA relative positioning.
  - Post-transition visual fading to emphasize change points without altering core logic.
- Practical effect: Charts show tighter, more reactive bands that rarely breach during trends, reducing visual clutter from flips; the adaptive nature means less intervention across assets, as the hull self-adjusts to volatility clusters rather than applying a one-size-fits-all scale.
  How it works (technical) 
The indicator first computes two EMAs from close prices using lengths derived from a preset pair or manual inputs, establishing a midline as their average. This midline serves as the central reference for the hull. True range values are then smoothed into multiple ATR candidates using exponential weighting over the specified lengths. For each candidate, deviations of recent highs and lows from the midline are ratioed against the ATR to determine a required multiplier that would enclose all extremes in the containment window—the highest ratio plus padding sets the base, clamped to user-defined bounds. Among valid candidates (those with sufficient history), the one yielding the narrowest overall band width is selected. The hull boundaries are then offset from the midline by this multiplier times the chosen ATR, and further smoothed with a fixed EMA to reduce jitter. Regime direction from EMA comparison gates which boundary acts as support or resistance, with initialization seeding arrays on the first bar to handle state persistence. No higher timeframe data is used, so all logic runs on the chart's native bars without lookahead.
  Parameter Guide 
EMA Pair — Selects preset lengths for fast and slow EMAs, influencing regime sensitivity and midline stability. Default: "21/55". Trade-offs/Tips: Faster pairs like "9/21" increase cross frequency for scalping but raise false signals; slower like "50/200" smooths for swings, potentially missing early turns. Use Manual for fine control.
Manual Fast — Sets fast EMA length when Manual mode is active; shorter values make regime switches quicker. Default: 21. Trade-offs/Tips: Lower than 10 risks over-reactivity; pair with slow at least double for clear separation.
Manual Slow — Sets slow EMA length when Manual mode is active; longer values anchor the midline more firmly. Default: 55. Trade-offs/Tips: Above 100 adds lag in trends; balance with fast to avoid perpetual neutrality.
ATR Lengths (comma-separated) — Defines candidate periods for ATR smoothing; more options allow finer auto-selection. Default: "7,10,14,21,28,35". Trade-offs/Tips: Fewer candidates speed computation but may miss optimal fits; keep under 10 for efficiency.
Containment Window — Number of recent bars the hull must fully enclose highs/lows of; larger windows favor stability. Default: 50. Trade-offs/Tips: Shorter (under 20) adapts faster to breaks but increases breach risk; longer smooths but delays response.
Min Multiplier Floor — Lowest allowed multiplier for hull width; prevents overly tight bands in low volatility. Default: 0.5. Trade-offs/Tips: Raise to 0.75 for conservative enclosures; too low allows pinches that flip easily.
Max Multiplier Cap — Highest allowed multiplier; caps expansion in spikes to avoid wide, lagging bands. Default: 1.0. Trade-offs/Tips: Lower to 0.75 tightens overall; higher permits more room but risks detachment from price.
Padding (+) — Adds buffer to the auto-multiplier for safer containment without exact touches. Default: 0.05. Trade-offs/Tips: Increase to 0.10 in gappy markets; minimal values hug closer but may still breach on outliers.
Fill Between (Mid ↔ Supertrend) — Toggles shaded area between midline and active hull for trend visualization. Default: true. Trade-offs/Tips: Disable for cleaner charts; pairs well with transparency tweaks.
Base Fill Transparency (0..100) — Sets default opacity of fills; higher values make them subtler. Default: 80. Trade-offs/Tips: Under 50 overwhelms price action; adjust with darken boost for emphasis.
Darken on Trend Change — Enables temporary opacity increase after regime shifts to spotlight transitions. Default: true. Trade-offs/Tips: Off for steady visuals; on aids spotting reversals in real-time.
Darken Fade Bars — Duration in bars for the darken effect to ramp back to base; longer prolongs highlight. Default: 8. Trade-offs/Tips: Shorter (4-6) for fast-paced charts; longer holds attention on changes.
Darken Boost at Change (Δ transp) — Intensity of opacity reduction at crossover; higher values make shifts more prominent. Default: 50. Trade-offs/Tips: Cap at 70 to avoid blackout; tune down if fades obscure details.
Show Supertrend Line — Displays the active hull boundary as a line. Default: true. Trade-offs/Tips: Hide for fill-only views; linewidth fixed at 3 for visibility.
Show EMA Cross Markers — Places circles and labels at crossover points for entry cues. Default: true. Trade-offs/Tips: Disable in clutter; labels show "Buy"/"Sell" at absolute positions.
Alert: EMA Cross Up (Long) — Triggers notification on bullish crossover. Default: true. Trade-offs/Tips: Pair with filters; once-per-bar frequency.
Alert: EMA Cross Down (Short) — Triggers notification on bearish crossover. Default: true. Trade-offs/Tips: Use for exits; ensure broker integration.
Show Debug — Reveals internal diagnostics like selected ATR details (if implemented). Default: false. Trade-offs/Tips: Enable for troubleshooting selections; minimal overhead.
  Reading & Interpretation 
Bullish regime shows a green line below price as support, with upward fill from midline; bearish uses red line above as resistance, downward fill. Crossovers flip the active boundary, marked by tiny green/red circles and "Buy"/"Sell" labels at the hull level. Fills start at base transparency but darken sharply at changes, fading over the specified bars to signal fresh momentum. If the hull rarely breaches during trends, containment is effective; frequent touches without flips indicate tight adaptation. Debug mode (when enabled) overlays text or plots for selected length and multiplier, helping verify auto-choices.
  Practical Workflows & Combinations 
- Trend following: Enter long on green "Buy" label above prior low structure; confirm with higher high. Trail stops along the green hull line, tightening as fills stabilize post-fade.
- Exits/Stops: Conservative exit on opposite crossover or hull breach; aggressive hold until fade completes if volume supports. Use darken boost as a volatility cue—high delta suggests waiting for confirmation.
- Multi-asset/Multi-TF: Defaults suit forex/stocks on 15m-4h; for crypto, widen containment to 75 for gaps. Layer on volume oscillator for cross filters; avoid on low-liquidity assets where ATR candidates skew.
  Behavior, Constraints & Performance 
Closed-bar logic ensures signals confirm at bar end, with live bars updating hull adaptively but no repaints since no future data or security calls are used. Arrays persist ATR states across bars, initialized once with candidates parsed from string. Small fixed loops (over 6 lengths max, inner up to 50) run per bar, capped by max_bars_back=500 for history needs. Resources stay low with 500 labels/lines limits, but dense charts may hit on markers. Known limits include initial lag until containment history builds (50+ bars), potential wide bands on gaps, and suboptimal selections if candidates omit ideal lengths.
  Sensible Defaults & Quick Tuning 
Start with "21/55" pair, 50-window, 0.5-1.0 multipliers, and 80% transparency for balanced responsiveness on daily charts. For too many flips, raise min floor to 0.75 or add lengths like "42"; for sluggishness, shorten window to 30 or pick faster pair. In high-vol environments, boost padding to 0.10; for smoother visuals, extend fade bars to 12.
  What this indicator is—and isn’t 
This is a visualization and signal layer for trend regime and adaptive boundaries, aiding entry/exit timing in directional markets. It is not a standalone system—pair with price structure, risk sizing, and broader context. Not predictive of turns, just reactive to containment and crosses.
  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.
 Happy trading
Chervolino
Outside Candle Session Breakout [CHE]Outside Candle Session Breakout   
Session - anchored HTF levels for clear market-structure and precise breakout context
  Summary 
This indicator is a relevant market-structure tool. It anchors the session to the first higher-timeframe bar, then activates only when the second bar forms an outside condition. Price frequently reacts around these anchors, which provides precise breakout context and a clear overview on both lower and higher timeframes. Robustness comes from close-based validation, an adaptive volatility and tick buffer, first-touch enforcement, optional retest, one-signal-per-session, cooldown, and an optional trend filter.
Pine version: v6. Overlay: true.
  Motivation: Why this design? 
Short-term breakout tools often trigger during noise, duplicate within the same session, or drift when volatility shifts. The core idea is to gate signals behind a meaningful structure event: a first-bar anchor and a subsequent outside bar on the session timeframe. This narrows attention to structurally important breaks while adaptive buffering and debouncing reduce false or mid-run triggers.
  What’s different vs. standard approaches? 
 Baseline: Simple high-low breaks or fixed buffers without session context.
 Architecture: Session-anchored first-bar high/low; outside-bar gate; close-based confirmation with an adaptive ATR and tick buffer; first-touch enforcement; optional retest window; one-signal-per-session and cooldown; optional EMA trend and slope filter; higher-timeframe aggregation with lookahead disabled; themeable visuals and a range fill between levels.
 Practical effect: Cleaner timing at structurally relevant levels, fewer redundant or late triggers, and better multi-timeframe situational awareness.
  How it works (technical) 
 The chart timeframe is mapped to an analysis timeframe and a session timeframe.
 The first session bar defines the anchor high and low. The setup becomes active only after the next bar forms an outside range relative to that first bar.
 While active, the script tracks these anchors and checks for a breakout beyond a buffered threshold, using closing prices or wicks by preference.
 The buffer scales with volatility and is limited by a minimum tick floor. First-touch enforcement avoids mid-run confirmations.
 Optional retest requires a pullback to the raw anchor followed by a new close beyond the buffered level within a user window.
 Optional trend gating uses an EMA on the analysis timeframe, including an optional slope requirement and price-location check.
 Higher-timeframe data is requested with lookahead disabled. Values can update during a forming higher-timeframe bar; waiting and confirmation mitigate timing shifts.
  Parameter Guide 
Enable Long / Enable Short — Direction toggles. Default: true / true. Reduces unwanted side.
Wait Candles — Minimum bars after outside confirmation before entries. Default: five. More waiting increases stability.
Close-based Breakout — Confirm on candle close beyond buffer. Default: true. For wick sensitivity, disable.
ATR Buffer — Enables adaptive volatility buffer. Default: true.
ATR Multiplier — Buffer scaling. Default: zero point two. Increase to reduce noise.
Ticks Buffer — Minimum buffer in ticks. Default: two. Protects in quiet markets.
Cooldown Bars — Blocks new signals after a trigger. Default: three.
One Signal per Session — Prevents duplicates within a session. Default: true.
Require Retest — Pullback to raw anchor before confirming. Default: false.
Retest Window — Bars allowed for retest completion. Default: five.
HTF Trend Filter — EMA-based gating. Default: false.
EMA Length — EMA period. Default: two hundred.
Slope — Require EMA slope direction. Default: true.
Price Above/Below EMA — Require price location relative to EMA. Default: true.
Show Levels / Highlight Session / Show Signals — Visual controls. Default: true.
Color Theme — “Blue-Green” (default), “Monochrome”, “Earth Tones”, “Classic”, “Dark”.
Time Period Box — Visibility, size, position, and colors for the info box. (Optional)
  Reading & Interpretation 
 The two level lines represent the session’s first-bar high and low. The filled band illustrates the active session range.
 “OUT” marks that the outside condition is confirmed and the setup is live.
 “LONG” or “SHORT” appears only when the breakout clears buffer, debounce, and optional gates.
 Background tint indicates sessions where the setup is valid.
 Alerts fire on confirmed long or short breakout events.
  Practical Workflows & Combinations 
 Trend-following: Keep close-based validation, ATR buffer near the default, one-signal-per-session enabled; add EMA trend and slope for directional bias.
 Retest confirmation: Enable retest with a short window to prioritize cleaner continuation after a pullback.
 Lower-timeframe scalping: Reduce waiting and cooldown slightly; keep a small tick buffer to filter micro-whips.
 Swing and position context: Increase ATR multiplier and waiting; maintain once-per-session to limit duplicates.
  Timeframe Tiers and Trader Profiles 
The script adapts its internal mapping based on the chart timeframe:
 Under fifteen minutes → Analysis: one minute; Session: sixty minutes. Useful for scalpers and high-frequency intraday reads.
 Between fifteen and under sixty minutes → Analysis: fifteen minutes; Session: one day. Suits day traders who need intraday alignment to the daily session.
 Between sixty minutes and under one day → Analysis: sixty minutes; Session: one week. Serves intraday-to-swing transitions and end-of-day planning.
 Between one day and under one week → Analysis: two hundred forty minutes; Session: two weeks. Fits swing traders who monitor multi-day structure.
 Between one week and under thirty days → Analysis: one day; Session: three months. Supports position traders seeking quarterly context.
 Thirty days and above → Analysis: one day; Session: twelve months. Provides a broad annual anchor for macro context.
These tiers are designed to keep anchors meaningful across regimes while preserving responsiveness appropriate to the trader profile.
  Behavior, Constraints & Performance 
 Signals can be validated on closed bars through close-based logic; enabling this reduces intrabar flicker.
 Higher-timeframe values may evolve during a forming bar; waiting parameters and the outside-bar gate reduce, but do not remove, this effect.
 Resource footprint is light; the script uses standard indicators and a single higher-timeframe request per stream.
 Known limits: rare setups during very quiet periods, sensitivity to gaps, and reduced reliability on illiquid symbols.
  Sensible Defaults & Quick Tuning 
 Start with close-based validation on, ATR buffer on with a multiplier near zero point two, tick buffer two, cooldown three, once-per-session on.
 Too many flips: increase the ATR multiplier and cooldown; consider enabling the EMA filter and slope.
 Too sluggish: reduce the ATR multiplier and waiting; disable retest.
 Choppy conditions: keep close-based validation, increase tick buffer, shorten the retest window.
  What this indicator is—and isn’t 
This is a visualization and signal layer for session-anchored breakouts with stability gates. It is not a complete trading system, risk framework, or predictive engine. Combine it with structured analysis, position sizing, and disciplined risk controls.
  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 
TASC 2025.11 The Points and Line Chart█ OVERVIEW 
This script implements the Points and Line Chart described by Mohamed Ashraf Mahfouz and Mohamed Meregy in the  November 2025 edition of the TASC Traders' Tips , "Efficient Display of Irregular Time Series”. This novel chart type interprets regular time series chart data to create an irregular time series chart.
 █ CONCEPTS 
When formatting data for display on a price chart, there are two main categorizations of chart types: regular time series (RTS) and irregular time series (ITS).
 
 RTS charts, such as a typical candlestick chart, collect data over a specified amount of time and display it at one point. A one-minute candle, for example, represents the entirety of price movements within the minute that it represents. 
 ITS charts display data only after certain conditions are met. Since they do not plot at a consistent time period, they are called “irregular”. 
Typically, ITS charts, such as Point and Figure (P&F) and Renko charts, focus on price change, plotting only when a certain threshold of change occurs.
 
The Points and Line (P&L) chart operates similarly to a P&F chart, using price change to determine when to plot points. However, instead of plotting the price in points, the P&L chart (by default) plots the closing price from RTS data. In other words, the P&L chart plots its points at the actual RTS close, as opposed to (price) intervals based on point size. This approach creates an ITS while still maintaining a reference to the RTS data, allowing us to gain a better understanding of time while consolidating the chart into an ITS format.
 █ USAGE 
Because the P&L chart forms bars based on price action instead of time, it displays displays significantly more history than a typical RTS chart. With this view, we are able to more easily spot support and resistance levels, which we could use when looking to place trades.
In the chart below, we can see over 13 years of data consolidated into one single view.
  
To view specific chart details, hover over each point of the chart to see a list of information.
In addition to providing a compact view of price movement over larger periods, this new chart type helps make classic chart patterns easier to interpret. When considering breakouts, the closing price provides a clearer representation of the actual breakout, as opposed to point size plots which are limited.
  
Because P&L is a new charting type, this script still requires a standard RTS chart for proper calculations. However, the main price chart is not intended for interpretation alongside the P&L chart; users can hide the main price series to keep the chart clean.
 █ DISPLAYS 
  
This indicator creates two displays: the "Price Display" and the "Data Display".
With the "Price display" setting, users can choose between showing a line or OHLC candles for the P&L drawing. The line display shows the close price of the P&L chart. In the candle display, the close price remains the same, while the open, high, and low values depend on the price action between points.
With the "Data display" setting, users can enable the display of a histogram that shows either the total volume or days/bars between the points in the P&L chart. For example, a reading of 12 days would indicate that the time since the last point was 12 days.
 Note:  The "Days" setting actually shows the number of chart bars elapsed between P&L points. The displayed value represents days only if the chart uses the "1D" timeframe.
The "Overlay P&L on chart" input controls whether the P&L line or candles appear on the main chart pane or in a separate pane.
Users can deactivate either display by selecting "None" from the corresponding input.
 Technical Note:  Due to drawing limitations, this indicator has the following display limits:
 
  The line display can show data to 10,000 P&L points.
  The candle display and tooltips show data for up to 500 points.
  The histograms show data for up to 3,333 points.
 
 █ INPUTS 
 Reversal Amount:  The number of points/steps required to determine a reversal.
 Scale size Method:   The method used to filter price movements. By default, the P&L chart uses the same scaling method as the P&F chart. Optionally, this scaling method can be changed to use ATR or Percent.
 P&L Method:  The prices to plot and use for filtering:
 
 “Close” plots the closing price and uses it to determine movements.
 “High/Low” uses the high price on upside moves and low price on downside moves.
 "Point Size" uses the closing price for filtration, but locks the price to plot at point size intervals.
Institutional Orderflow Pro — VWAP, Delta, and Liquidity 
Institutional Orderflow Pro is a next-generation order flow analysis indicator designed to help traders identify institutional participation, directional bias, and exhaustion zones in real time.
Unlike traditional volume-based indicators, it merges VWAP dynamics, cumulative delta, relative volume, and liquidity proximity into a single unified dashboard that updates tick-by-tick — without repainting.
The indicator is open-source, transparent, and educational. It aims to provide traders with a clearer read on who controls the market — buyers or sellers — and where liquidity lies.
The indicator combines multiple institutional-grade analytics into one framework:
RVOL (Relative Volume) = Compares current volume against the average of recent bars to identify strong institutional participation.
zΔ (Delta Z-Score) = Normalizes the buying/selling delta to reveal unusually aggressive market behavior.
CVDΔ (Cumulative Volume Delta Change) = Shows which side (buyers/sellers) is dominating this bar’s order flow.
VWAP Direction & Slope = Determines whether price is trading above/below VWAP and whether VWAP is trending or flat.
PD Distance (Prev Day Confluence) = Measures the current price’s distance from previous day’s high, low, close, and VWAP in ATR units — highlighting liquidity zones.
ABS/EXH Detection = Identifies institutional absorption and exhaustion patterns where momentum may reverse.
Bias Computation = Combines VWAP direction + slope to give a simplified regime signal: UP, DOWN, or FLAT.
All metrics are displayed through a color-coded, non-repainting HUD:
🟢 = bullish / favorable conditions
🔴 = bearish / weak conditions
⚫ = neutral / flat
🟡 = absorption (potential trap zone)
🟠 = exhaustion (momentum fading)
| Metric                 | Signal  | Meaning                                        |
| ---------------------- | ------- | ---------------------------------------------- |
| **RVOL ≥ 1.3**         | 🟢      | High institutional activity — valid setup zone |
| **zΔ ≥ 1.2 / ≤ -1.2**  | 🟢 / 🔴 | Unusual buy/sell aggression                    |
| **CVDΔ > 0**           | 🟢      | Buyers dominate this bar                       |
| **VWAP dir ↑ / ↓**     | 🟢 / 🔴 | Institutional bias long/short                  |
| **Slope ok = YES**     | 🟢      | Trending market                                |
| **PD dist ≤ 0.35 ATR** | 🟢      | Near key liquidity zones                       |
| **Bias = UP/DOWN**     | 🟢 / 🔴 | Trend-aligned environment                      |
| **ABS/EXH active**     | 🟡 / 🟠 | Caution — possible reversal zone               |
How to Use
Confirm Volume Context → RVOL > 1.2
Align with Bias → Take longs only when Bias = UP, shorts only when Bias = DOWN.
Check Slope and VWAP Dir → Ensure trending context (Slope = YES).
Confirm CVD and zΔ → Flow should agree with price direction.
Avoid ABS/EXH Triggers → These signal exhaustion or absorption by large players.
Enter Near PD Zones → Ideal trade zones are within 0.35 ATR of prior-day levels.
This multi-factor confirmation reduces noise and focuses only on high-probability institutional setups.
Originality
This script was written from scratch in Pine v6.
It does not reuse existing public indicators except for standard built-ins (ta.vwap, ta.atr, etc.).
The unique combination of delta z-scoring, VWAP slope filtering, and real-time confluence zones distinguishes it from typical orderflow tools or cumulative delta overlays.
The core innovation is its merged real-time HUD that integrates institutional metrics and natural-language feedback directly on the chart, allowing traders to read market context intuitively rather than decode multiple subplots.
Notes & Disclaimers
This indicator does not repaint.
It’s intended for educational and analytical purposes only — not as financial advice or a guaranteed signal system.
Works best on liquid instruments (Futures, Indices, FX majors).
Avoid non-standard chart types (Heikin Ashi, Renko, etc.) for accurate readings.
Open-source, modifiable, and compatible with Pine v6.
Recommended Use
Apply it with clean charts and standard candles for the best clarity.
Use alongside a basic structure or volume profile to contextualize institutional bias zones.
Author: Dhawal Ranka
Category - Orderflow / VWAP / Institutional Analysis
Version: Pine Script™ v6
License: Open Source (Educational Use)
Forecast PriceTime Oracle [CHE]  Forecast PriceTime Oracle   — Prioritizes quality over quantity by using Power Pivots via RSI %B metric to forecast future pivot highs/lows in price and time
  Summary 
This indicator identifies potential pivot highs and lows based on out-of-bounds conditions in a modified RSI %B metric, then projects future occurrences by estimating time intervals and price changes from historical medians. It provides visual forecasts via diagonal and horizontal lines, tracks achievement with color changes and symbols, and displays a dashboard for statistical overview including hit rates. Signals are robust due to median-based aggregation, which reduces outlier influence, and optional tolerance settings for near-misses, making it suitable for anticipating reversals in ranging or trending markets.
  Motivation: Why this design? 
Standard pivot detection often lags or generates false signals in volatile conditions, missing the timing of true extrema. This design leverages out-of-bounds excursions in RSI %B to capture "Power Pivots" early—focusing on quality over quantity by prioritizing significant extrema rather than every minor swing—then uses historical deltas in time and price to forecast the next ones, addressing the need for proactive rather than reactive analysis. It assumes that pivot spacing follows statistical patterns, allowing users to prepare entries or exits ahead of confirmation.
  What’s different vs. standard approaches? 
- Reference baseline: Diverges from traditional ta.pivothigh/low, which require fixed left/right lengths and confirm only after bars close, often too late for dynamic markets.
- Architecture differences:
  - Detects extrema during OOB runs rather than post-bar symmetry.
  - Aggregates deltas via medians (or alternatives) over a user-defined history, capping arrays to manage resources.
  - Applies tolerance thresholds for hit detection, with options for percentage, absolute, or volatility-adjusted (ATR) flexibility.
  - Freezes achieved forecasts with visual states to avoid clutter.
- Practical effect: Charts show proactive dashed projections instead of retrospective dots; the dashboard reveals evolving hit rates, helping users gauge reliability over time without manual calculation.
  How it works (technical) 
The indicator first computes a smoothed RSI over a specified length, then applies Bollinger Bands to derive %B, flagging out-of-bounds below zero or above one hundred as potential run starts. During these runs, it tracks the extreme high or low price and bar index. Upon exit from the OOB state, it confirms the Power Pivot at that extreme and records the time delta (bars since prior) and price change percentage to rolling arrays.
For forecasts, it calculates the median (or selected statistic) of recent deltas, subtracts the confirmation delay (bars from apex to exit), and projects ahead by that adjusted amount. Price targets use the median change applied to the origin pivot value. Lines are drawn from the apex to the target bar and price, with a short horizontal at the endpoint. Arrays store up to five active forecasts, pruning oldest on overflow.
Tolerance adjusts hit checks: for highs, if the high reaches or exceeds the target (adjusted by tolerance); for lows, if the low drops to or below. Once hit, the forecast freezes, changing colors and symbols, and extends the horizontal to the hit bar. Persistent variables maintain last pivot states across bars; arrays initialize empty and grow until capped at history length.
  Parameter Guide 
Source: Specifies the data input for the RSI computation, influencing how price action is captured. Default is close. For conservative signals in noisy environments, switch to high; using low boosts responsiveness but may increase false positives.
RSI Length: Sets the smoothing period for the RSI calculation, with longer values helping to filter out whipsaws. Default is 32. Opt for shorter lengths like 14 to 21 on faster timeframes for quicker reactions, or extend to 50 or more in strong trends to enhance stability at the cost of some lag.
BB Length: Defines the period for the Bollinger Bands applied to %B, directly affecting how often out-of-bounds conditions are triggered. Default is 20. Align it with the RSI length: shorter periods detect more potential runs but risk added noise, while longer ones provide better filtering yet might overlook emerging extrema.
BB StdDev: Controls the multiplier for the standard deviation in the bands, where wider settings reduce false out-of-bounds alerts. Default is 2.0. Narrow it to 1.5 for highly volatile assets to catch more signals, or broaden to 2.5 or higher to emphasize only major movements.
Show Price Forecast: Enables or disables the display of diagonal and target lines along with their updates. Default is true. Turn it off for simpler chart views, or keep it on to aid in trade planning.
History Length: Determines the number of recent pivot samples used for median-based statistics, where more history leads to smoother but potentially less current estimates. Default is 50. Start with a minimum of 5 to build data; limit to 100 to 200 to prevent outdated regimes from skewing results.
Max Lookahead: Limits the number of bars projected forward to avoid overly extended lines. Default is 500. Reduce to 100 to 200 for intraday focus, or increase for longer swing horizons.
Stat Method: Selects the aggregation technique for time and price deltas: Median for robustness against outliers, Trimmed Mean (20%) for a balanced trim of extremes, or 75th Percentile for a conservative upward tilt. Default is Median. Use Median for even distributions; switch to Percentile when emphasizing potential upside in trending conditions.
Tolerance Type: Chooses the approach for flexible hit detection: None for exact matches, Percentage for relative adjustments, Absolute for fixed point offsets, or ATR for scaling with volatility. Default is None. Begin with Percentage at 0.5 percent for currency pairs, or ATR for adapting to cryptocurrency swings.
Tolerance %: Provides the relative buffer when using Percentage mode, forgiving small deviations. Default is 0.5. Set between 0.2 and 1.0 percent; higher values accommodate gaps but can overstate hit counts.
Tolerance Points: Establishes a fixed offset in price units for Absolute mode. Default is 0.0010. Tailor to the asset, such as 0.0001 for forex pairs, and validate against past wick behavior.
ATR Length: Specifies the period for the Average True Range in dynamic tolerance calculations. Default is 14. This is the standard setting; shorten to 10 to reflect more recent volatility.
ATR Multiplier: Adjusts the ATR scale for tolerance width in ATR mode. Default is 0.5. Range from 0.3 for tighter precision to 0.8 for greater leniency.
Dashboard Location: Positions the summary table on the chart. Default is Bottom Right. Consider Top Left for better visibility on mobile devices.
Dashboard Size: Controls the text scaling for dashboard readability. Default is Normal. Choose Tiny for dense overlays or Large for detailed review sessions.
Text/Frame Color: Sets the color scheme for dashboard text and borders. Default is gray. Align with your chart theme, opting for lighter shades on dark backgrounds.
  Reading & Interpretation 
Forecast lines appear as dashed diagonals from confirmed pivots to projected targets, with solid horizontals at endpoints marking price levels. Open targets show a target symbol (🎯); achieved ones switch to a trophy symbol (🏆) in gray, with lines fading to gray. The dashboard summarizes median time/price deltas, sample counts, and hit rates—rising rates indicate improving forecast alignment. Colors differentiate highs (red) from lows (lime); frozen states signal validated projections.
  Practical Workflows & Combinations 
- Trend following: Enter long on low forecast hits during uptrends (higher highs/lower lows structure); filter with EMA crossovers to ignore counter-trend signals.
- Reversal setups: Short above high projections in overextended rallies; use volume spikes as confirmation to reduce false breaks.
- Exits/Stops: Trail stops to prior pivot lows; conservative on low hit rates (below 50%), aggressive above 70% with tight tolerance.
- Multi-TF: Apply on 1H for entries, 4H for time projections; combine with Ichimoku clouds for confluence on targets.
- Risk management: Position size inversely to delta uncertainty (wider history = smaller bets); avoid low-liquidity sessions.
  Behavior, Constraints & Performance 
Confirmation occurs on OOB exit, so live-bar pivots may adjust until close, but projections update only on events to minimize repaint. No security or HTF calls, so no external lookahead issues. Arrays cap at history length with shifts; forecasts limited to five active, pruning FIFO. Loops iterate over small fixed sizes (e.g., up to 50 for stats), efficient on most hardware. Max lines/labels at 500 prevent overflow.
Known limits: Sensitive to OOB parameter tuning—too tight misses runs; assumes stationary pivot stats, which may shift in regime changes like low vol. Gaps or holidays distort time deltas.
  Sensible Defaults & Quick Tuning 
Defaults suit forex/crypto on 1H–4H: RSI 32/BB 20 for balanced detection, Median stats over 50 samples, None tolerance for exactness. 
- Too many false runs: Increase BB StdDev to 2.5 or RSI Length to 50 for filtering.
- Lagging forecasts: Shorten History Length to 20; switch to 75th Percentile for forward bias.
- Missed near-hits: Enable Percentage tolerance at 0.3% to capture wicks without overcounting.
- Cluttered charts: Reduce Max Lookahead to 200; disable dashboard on lower TFs.
  What this indicator is—and isn’t 
This is a forecasting visualization layer for pivot-based analysis, highlighting statistical projections from historical patterns. It is not a standalone system—pair with price action, volume, and risk rules. Not predictive of all turns; focuses on OOB-derived extrema, ignoring volume or news impacts.
  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
Anchored VWAP Polyline [CHE]  Anchored VWAP Polyline   — Anchored VWAP drawn as a polyline from a user-defined bar count with last-bar updates and optional labels
  Summary 
This indicator renders an anchored Volume-Weighted Average Price as a continuous polyline starting from a user-selected anchor point a specified number of bars back. It accumulates price multiplied by volume only from the anchor forward and resets cleanly when the anchor moves. Drawing is object-based (polyline and labels) and updated on the most recent bar only, which reduces flicker and avoids excessive redraws. Optional labels mark the anchor and, conditionally, a delta label when the current close is below the historical close at the anchor offset.
  Motivation: Why this design? 
Anchored VWAP is often used to track fair value after a specific event such as a swing, breakout, or session start. Traditional plot-based lines can repaint during live updates or incur overhead when frequently redrawn. This implementation focuses on explicit state management, last-bar rendering, and object recycling so the line stays stable while remaining responsive when the anchor changes. The design emphasizes deterministic updates and simple session gating from the anchor.
  What’s different vs. standard approaches? 
 Baseline: Classic VWAP lines plotted from session open or full history.
 Architecture differences:
   Anchor defined by a fixed bar offset rather than session or day boundaries.
   Object-centric drawing via `polyline` with an array of `chart.point` objects.
   Last-bar update pattern with deletion and replacement of the polyline to apply all points cleanly.
   Conditional labels: an anchor marker and an optional delta label only when the current close is below the historical close at the offset.
 Practical effect: You get a visually continuous anchored VWAP that resets when the anchor shifts and remains clean on chart refreshes. The labels act as lightweight diagnostics without clutter.
  How it works (technical) 
 The anchor index is computed as the latest bar index minus the user-defined bar count.
 A session flag turns true from the anchor forward; prior bars are excluded.
 Two persistent accumulators track the running sum of price multiplied by volume and the running sum of volume; they reset when the session flag turns from false to true.
 The anchored VWAP is the running sum divided by the running volume whenever both are valid and the volume is not zero.
 Points are appended to an array only when the anchored VWAP is valid. On the most recent bar, any existing polyline is deleted and replaced with a new one built from the point array.
 Labels are refreshed on the most recent bar:
   A yellow warning label appears when there are not enough bars to compute the reference values.
   The anchor label marks the anchor bar.
   The delta label appears only when the current close is below the close at the anchor offset; otherwise it is suppressed.
 No higher-timeframe requests are used; repaint is limited to normal live-bar behavior.
  Parameter Guide 
Bars back — Sets the anchor offset in bars; default two hundred thirty-three; minimum one. Larger values extend the anchored period and increase stability but respond more slowly to regime changes.
Labels — Toggles all labels; default enabled. Disable to keep the chart clean when using multiple instances.
  Reading & Interpretation 
 The polyline represents the anchored VWAP from the chosen anchor to the current bar. Price above the line suggests strength relative to the anchored baseline; price below suggests weakness.
 The anchor label shows where the accumulation starts.
 The delta label appears only when today’s close is below the historical close at the offset; it provides a quick context for negative drift relative to that reference.
 A yellow message at the current bar indicates the chart does not have enough history to compute the reference comparison yet.
  Practical Workflows & Combinations 
 Trend following: Anchor after a breakout bar or a swing confirmation. Use the anchored VWAP as dynamic support or resistance; look for clean retests and holds for continuation.
 Mean reversion: Anchor at a local extreme and watch for approaches back toward the line; require structure confirmation to avoid early entries.
 Session or event studies: Re-set the anchor around earnings, macro releases, or session opens by adjusting the bar offset.
 Combinations: Pair with structure tools such as swing highs and lows, or with volatility measures to filter chop. The labels can be disabled when combining multiple instances to maintain chart clarity.
  Behavior, Constraints & Performance 
 Repaint and confirmation: The line is updated on the most recent bar only; historical values do not rely on future bars. Normal live-bar movement applies until the bar closes.
 No higher timeframe: There is no `security` call; repaint paths related to higher-timeframe lookahead do not apply here.
 Resources: Uses one polyline object that is rebuilt on the most recent bar, plus two labels when conditions are met. `max_bars_back` is two thousand. Arrays store points from the anchor forward; extremely long anchors or very long charts increase memory usage.
 Known limits: With very thin volume, the VWAP can be unavailable for some bars. Very large anchors reduce responsiveness. Labels use ATR for vertical placement; extreme gaps can place them close to extremes.
  Sensible Defaults & Quick Tuning 
 Starting point: Bars back two hundred thirty-three with Labels enabled works well on many assets and timeframes.
 Too noisy around the line: Increase Bars back to extend the accumulation window.
 Too sluggish after regime changes: Decrease Bars back to focus on a shorter anchored period.
 Chart clutter with multiple instances: Disable Labels while keeping the polyline visible.
  What this indicator is—and isn’t 
This is a visualization of an anchored VWAP with optional diagnostics. It is not a full trading system and does not include entries, exits, or position management. Use it alongside clear market structure, risk controls, and a plan for trade management. It does not predict future prices.
 Inputs with defaults 
 Bars back: two hundred thirty-three bars, minimum one.
 Labels: enabled or disabled toggle, default enabled.
Pine version: v6
Overlay: true
Primary outputs: one polyline, optional labels (anchor, conditional delta, and a warning when insufficient bars).
Metrics and functions: volume, ATR for label offset, object drawing via polyline and chart points, last-bar update pattern.
Special techniques: session gating from the anchor, persistent state, object recycling, explicit guards against unavailable values and zero volume.
Compatibility and assets: Designed for standard candlestick or bar charts across liquid assets and common timeframes.
Diagnostics: Yellow warning label when history is insufficient.
  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 






















