Relative Strength Index Remastered [CHE]Relative Strength Index Remastered   — Enhanced RSI with robust divergence detection using price-based pivots and line-of-sight validation to reduce false signals compared to the standard RSI indicator.
  Summary 
RSI Remastered builds on the classic Relative Strength Index by adding a more reliable divergence detection system that relies on price pivots rather than RSI pivots alone, incorporating a line-of-sight check to ensure the RSI path between points remains clear. This approach filters out many false divergences that occur in the original RSI indicator due to its volatile pivot detection on the RSI line itself. Users benefit from clearer reversal and continuation signals, especially in noisy markets, with optional hidden divergence support for trend confirmation. The core RSI calculation and smoothing options remain familiar, but the divergence logic provides materially fewer alerts while maintaining sensitivity.
  Motivation: Why this design? 
The standard RSI indicator often generates misleading divergence signals because it detects pivots directly on the RSI values, which can fluctuate erratically in volatile conditions, leading to frequent false positives that confuse traders during ranging or choppy price action. RSI Remastered addresses this by shifting pivot detection to the underlying price highs and lows, which are more stable, and adding a validation step that confirms the RSI line does not cross the direct path between pivot points. This design targets the real problem of over-signaling in the original, promoting more actionable insights without altering the RSI's core momentum measurement.
  What’s different vs. standard approaches? 
- Reference baseline: The classical TradingView RSI indicator, which uses simple RSI-based pivot detection for divergences.
- Architecture differences:
  - Pivot identification on price extremes (highs and lows) instead of RSI values, extracting RSI levels at those points for comparison.
  - Addition of a line-of-sight validation that checks the RSI path bar by bar between pivots to prevent signals where the line is interrupted.
  - Inclusion of hidden divergence types alongside regular ones, using the same robust framework.
  - Configurable drawing of connecting lines between validated pivot RSI points for visual clarity.
- Practical effect: Charts show fewer but higher-quality divergence markers and lines, reducing clutter from the original's frequent RSI pivot triggers; this matters for avoiding whipsaws in intraday trading, where the standard version might flag dozens of invalid setups per session.
  Key Comparison Aspects 
 Aspect:  Title/Shorttitle  
Original RSI: "Relative Strength Index" / "RSI"  
Robust Variant: "Relative Strength Index Remastered  " / "RSI RM"
 Aspect:  Max. Lines/Labels  
Original RSI: No specification (Standard: 50/50)  
Robust Variant: max_lines_count=200, max_labels_count=200 (for more lines/markers in divergences)
 Aspect:  RSI Calculation & Plots  
Original RSI: Identical: RSI with RMA, Plots (line, bands, gradient fills)  
Robust Variant: Identical: RSI with RMA, Plots (line, bands, gradient fills)
 Aspect:  Smoothing (MA)  
Original RSI: Identical: Inputs for MA types (SMA, EMA etc.), Bollinger Bands optional  
Robust Variant: Identical: Inputs for MA types (SMA, EMA etc.), Bollinger Bands optional
 Aspect:  Divergence Activation  
Original RSI: input.bool(false, "Calculate Divergence") (disabled by default)  
Robust Variant: input.bool(true, "Calculate Divergence") (enabled by default, with tooltip)
 Aspect:  Pivot Calculation  
Original RSI: Pivots on RSI (ta.pivotlow/high on RSI values)  
Robust Variant: Pivots on price (ta.pivotlow/high on low/high), RSI values then extracted
 Aspect:  Lookback Values  
Original RSI: Fixed: lookbackLeft=5, lookbackRight=5  
Robust Variant: Input: L=5 (Pivot Left), R=5 (Pivot Right), adjustable (min=1, max=50)
 Aspect:  Range Between Pivots  
Original RSI: Fixed: rangeUpper=60, rangeLower=5 (via _inRange function)  
Robust Variant: Input: rangeUpper=60 (Max Bars), rangeLower=5 (Min Bars), adjustable (min=1–6, max=100–300)
 Aspect:  Divergence Types  
Original RSI: Only Regular Bullish/Bearish: - Bull: Price LL + RSI HL - Bear: Price HH + RSI LH  
Robust Variant: Regular + Hidden (optional via showHidden=true): - Regular Bull: Price LL + RSI HL - Regular Bear: Price HH + RSI LH - Hidden Bull: Price HL + RSI LL - Hidden Bear: Price LH + RSI HH
 Aspect:  Validation  
Original RSI: No additional check (only pivot + range check)  
Robust Variant: Line-of-Sight Check: RSI line must not cross the connecting line between pivots (line_clear function with slope calculation and loop for each bar in between)
 Aspect:  Signals (Plots/Shapes)  
Original RSI: - Plot of pivot points (if divergence) - Shapes: "Bull"/"Bear" at RSI value, offset=-5  
Robust Variant: - No pivot plots, instead shapes at RSI , offset=-R (adjustable) - Shapes: "Bull"/"Bear" (Regular), "HBull"/"HBear" (Hidden) - Colors: Lime/Red (Regular), Teal/Orange (Hidden)
 Aspect:  Line Drawing  
Original RSI: No lines  
Robust Variant: Optional (showLines=true): Lines between RSI pivots (thick for regular, dashed/thin for hidden), extend=none
 Aspect:  Alerts  
Original RSI: Only Regular Bullish/Bearish (with pivot lookback reference)  
Robust Variant: Regular Bullish/Bearish + Hidden Bullish/Bearish (specific "at latest pivot low/high")
 Aspect:  Robustness  
Original RSI: Simple, prone to false signals (RSI pivots can be volatile)  
Robust Variant: Higher: Price pivots are more stable, line-of-sight filters "broken" divergences, hidden support for trend continuations
 Aspect:  Code Length/Structure  
Original RSI: ~100 lines, simple if-blocks for bull/bear  
Robust Variant: ~150 lines, extended helper functions (e.g., inRange, line_clear), var group for inputs
  How it works (technical) 
The indicator first computes the core RSI value based on recent price changes, separating upward and downward movements over the specified length and smoothing them to derive a momentum reading scaled between zero and one hundred. This value is then plotted in a separate pane with fixed upper and lower reference lines at seventy and thirty, along with optional gradient fills to highlight overbought and oversold zones.
For smoothing, a moving average type is applied to the RSI if enabled, with an option to add bands around it based on the variability of recent RSI values scaled by a multiplier. Divergence detection activates on confirmed price pivots: lows for bullish checks and highs for bearish. At each new pivot, the system retrieves the bar index and values (price and RSI) for the current and prior pivot, ensuring they fall within a configurable bar range to avoid unrelated points.
Comparisons then assess whether the price has made a lower low (or higher high) while the RSI at those points moves in the opposite direction—higher for bullish regular, lower for bearish regular. For hidden types, the directions reverse to capture trend strength. The line-of-sight check calculates the straight path between the two RSI points and verifies that the actual RSI values in between stay entirely above (for bullish) or below (for bearish) that path, breaking the signal if any bar violates it. Valid signals trigger shapes at the RSI level of the new pivot and optional lines connecting the points. Initialization uses built-in functions to track prior occurrences, with states persisting across bars for accurate historical comparisons. No higher timeframe data is used, so confirmation occurs after the right pivot bars close, minimizing live-bar repaints.
  Parameter Guide 
Length — Controls the period for measuring price momentum changes — Default: 14 — Trade-offs/Tips: Shorter values increase responsiveness but add noise and more false signals; longer smooths trends but delays entries in fast markets.  
Source — Selects the price input for RSI calculation — Default: Close — Trade-offs/Tips: Use high or low for volatility focus, but close works best for most assets; mismatches can skew overbought/oversold reads.  
Calculate Divergence — Enables the enhanced divergence logic — Default: True — Trade-offs/Tips: Disable for pure RSI view to save computation; essential for signal reliability over the standard method.  
Type (Smoothing) — Chooses the moving average applied to RSI — Default: SMA — Trade-offs/Tips: None for raw RSI; EMA for quicker adaptation, but SMA reduces whipsaws; Bollinger Bands option adds volatility context at cost of added lines.  
Length (Smoothing) — Period for the smoothing average — Default: 14 — Trade-offs/Tips: Match RSI length for consistency; shorter boosts signal speed but amplifies noise in the smoothed line.  
BB StdDev — Multiplier for band width around smoothed RSI — Default: 2.0 — Trade-offs/Tips: Lower narrows bands for tighter signals, risking more touches; higher widens for fewer but stronger breakouts.  
Pivot Left — Bars to the left for confirming price pivots — Default: 5 — Trade-offs/Tips: Increase for stricter pivots in noisy data, reducing signals; too high delays confirmation excessively.  
Pivot Right — Bars to the right for confirming price pivots — Default: 5 — Trade-offs/Tips: Balances with left for symmetry; longer right ensures maturity but shifts signals backward.  
Max Bars Between Pivots — Upper limit on distance for valid pivot pairs — Default: 60 — Trade-offs/Tips: Tighten for short-term trades to focus recent action; widen for swing setups but risks unrelated comparisons.  
Min Bars Between Pivots — Lower limit to avoid clustered pivots — Default: 5 — Trade-offs/Tips: Raise to filter micro-moves; too low invites overlapping signals like the original RSI.  
Detect Hidden — Includes trend-continuation hidden types — Default: True — Trade-offs/Tips: Enable for full trend analysis; disable simplifies to reversals only, akin to basic RSI.  
Draw Lines — Shows connecting lines between valid pivots — Default: True — Trade-offs/Tips: Turn off for cleaner charts; helps visually confirm line-of-sight in backtests.
  Reading & Interpretation 
The main RSI line oscillates between zero and one hundred, crossing above fifty suggesting building momentum and below indicating weakness; touches near seventy or thirty flag potential extremes. The optional smoothed line and bands provide a filtered view—price above the upper band on the RSI pane hints at overextension. Divergence shapes appear as upward labels for bullish (lime for regular, teal for hidden) and downward for bearish (red regular, orange hidden) at the pivot's RSI level, signaling a mismatch only after validation. Connecting lines, if drawn, slope between points without RSI interference, their color matching the shape type; a dashed style denotes hidden. Fewer shapes overall compared to the standard RSI mean higher conviction, but always confirm with price structure.
  Practical Workflows & Combinations 
- Trend following: Enter longs on regular bullish shapes near support with higher highs in price; filter hidden bullish for pullback buys in uptrends, pairing with a rising smoothed RSI above fifty.
- Exits/Stops: Use bearish regular as reversal warnings to tighten stops; hidden bearish in downtrends confirms continuation—exit if lines show RSI crossing the path.
- Multi-asset/Multi-TF: Defaults suit forex and stocks on one-hour charts; for crypto volatility, widen pivot ranges to ten; scale min/max bars proportionally on daily for swings, avoiding the original's intraday spam.
  Behavior, Constraints & Performance 
Signals confirm only after the right pivot bars close, so live bars may show tentative pivots that vanish on close, unlike the standard RSI's immediate RSI-pivot triggers—plan for this delay in automation. No higher timeframe calls, so no security-related repaints. Resources include up to two hundred lines and labels for dense charts, with a loop in validation scanning up to three hundred bars between pivots, which is efficient but could slow on very long histories. Known limits: Slight lag at pivot confirmation in trending markets; volatile RSI might rarely miss fine path violations; not ideal for gap-heavy assets where pivots skip.
  Sensible Defaults & Quick Tuning 
Start with defaults for balanced momentum and divergence on most timeframes. For too many signals (like the original), raise pivot left/right to eight and min bars to ten to filter noise. If sluggish in trends, shorten RSI length to nine and enable EMA smoothing for faster adaptation. In high-volatility assets, widen max bars to one hundred but disable hidden to focus essentials. For clean reversal hunts, set smoothing to none and lines on.
  What this indicator is—and isn’t 
RSI Remastered serves as a refined momentum and divergence visualization tool, enhancing the standard RSI for better signal quality in technical analysis setups. It is not a standalone trading system, nor does it predict price moves—pair it with volume, structure breaks, and risk rules for decisions. Use alongside position sizing and broader context, not in isolation.
  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
In den Scripts nach "renko" suchen
Squeeze Weekday Frequency [CHE]  Squeeze Weekday Frequency   — Tracks historical frequency of low-volatility squeezes by weekday to inform timing of low-risk setups.
  Summary 
This indicator monitors periods of unusually low volatility, defined as when the average true range falls below a percentile threshold, and tallies their occurrences across each weekday. By aggregating these counts over the chart's history, it reveals patterns in squeeze frequency, helping traders avoid or target specific days for reduced noise. The approach uses persistent counters to ensure accurate daily tallies without duplicates, providing a robust view of weekday biases in volatility regimes.
  Motivation: Why this design? 
Traders often face inconsistent signal quality due to varying volatility patterns tied to the trading calendar, such as quieter mid-week sessions or busier Mondays. This indicator addresses that by binning low-volatility events into weekday buckets, allowing users to spot recurring low-activity days where trends may develop with less whipsaw. It focuses on historical aggregation rather than real-time alerts, emphasizing pattern recognition over prediction.
  What’s different vs. standard approaches? 
- Reference baseline: Traditional volatility trackers like simple moving averages of range or standalone Bollinger Band squeezes, which ignore temporal distribution.
- Architecture differences:
  - Employs array-based persistent counters for each weekday to accumulate events without recounting.
  - Includes duplicate prevention via day-key tracking to handle sparse data.
  - Features on-demand sorting and conditional display modes for focused insights.
- Practical effect: Charts show a persistent table of ranked weekdays instead of transient plots, making it easier to glance at biases like higher squeezes on Fridays, which reduces the need for manual logging and highlights calendar-driven edges.
  How it works (technical) 
The indicator first computes the average true range over a specified lookback period to gauge recent volatility. It then ranks this value against its own history within a sliding window to identify squeezes when the rank drops below the threshold. Each bar's timestamp is resolved to a weekday using the selected timezone, and a unique day identifier is generated from the date components.
On detecting a squeeze and valid price data, it checks against a stored last-marked day for that weekday to avoid multiple counts per day. If it's a new occurrence, the corresponding weekday counter in an array increments. Total days and data-valid days are tracked separately for context.
At the chart's last bar, it sums all counters to compute shares, sorts weekdays by their squeeze proportions, and populates a table with the selected subset. The table alternates row colors and highlights the peak weekday. An info label above the final bar summarizes totals and the top day. Background shading applies a faint red to squeeze bars for visual confirmation. State persists via variable arrays initialized once, ensuring counts build incrementally without resets.
  Parameter Guide 
ATR Length — Sets the lookback for measuring average true range, influencing squeeze sensitivity to short-term swings. Default: 14. Trade-offs/Tips: Shorter values increase responsiveness but raise false positives in chop; longer smooths for stability, potentially missing early squeezes.
Percentile Window (bars) — Defines the history length for ranking the current ATR, balancing recent relevance with sample size. Default: 252. Trade-offs/Tips: Narrower windows adapt faster to regime shifts but amplify noise; wider ones stabilize ranks yet lag in fast markets—aim for 100-500 bars on daily charts.
Squeeze threshold (PR < x) — Determines the cutoff for low-volatility classification; lower values flag rarer, tighter squeezes. Default: 10.0. Trade-offs/Tips: Tighter thresholds (under 5) yield fewer but higher-quality signals, reducing clutter; looser (over 20) captures more events at the cost of relevance.
Timezone — Selects the reference for weekday assignment; exchange default aligns with asset's session. Default: Exchange. Trade-offs/Tips: Use custom for cross-market analysis, but verify alignment to avoid offset errors in global pairs.
Show — Toggles the results table visibility for quick on/off of the display. Default: true. Trade-offs/Tips: Disable in multi-indicator setups to save screen space; re-enable for periodic reviews.
Pos — Positions the table on the chart pane for optimal viewing. Default: Top Right. Trade-offs/Tips: Bottom options suit long-term charts; test placements to avoid overlapping price action.
Font — Adjusts text size in the table for readability at different zooms. Default: normal. Trade-offs/Tips: Smaller fonts fit more data but strain eyes on small screens; larger for presentations.
Dark — Applies a dark color scheme to the table for contrast against chart backgrounds. Default: true. Trade-offs/Tips: Toggle false for light themes; ensures legibility without manual recoloring.
Display — Filters table rows to show all, top three, or bottom three weekdays by squeeze share. Default: All. Trade-offs/Tips: Use "Top 3" for focus on high-frequency days in active trading; "All" for full audits.
  Reading & Interpretation 
Red-tinted backgrounds mark individual squeeze bars, indicating current low-volatility conditions. The table's summary row shows the highest squeeze count, its percentage of total events, and the associated weekday in teal. Detail rows list selected weekdays with their absolute counts, proportional shares, and a left arrow for the peak day—higher percentages signal days where squeezes cluster, suggesting potential for calmer trend development. The info label reports overall days observed, valid data days, and reiterates the top weekday with its count. Drifting counts toward zero on a weekday imply rarity, while elevated ones point to habitual low-activity sessions.
  Practical Workflows & Combinations 
- Trend following: Scan for squeezes on high-frequency weekdays as entry filters, confirming with higher highs or lower lows in the structure; pair with momentum oscillators to time breaks.
- Exits/Stops: On low-squeeze days, widen stops for breathing room, tightening them during peak squeeze periods to guard against false breaks—use the table's percentages as a regime proxy.
- Multi-asset/Multi-TF: Defaults work across forex and indices on hourly or daily frames; for stocks, adjust percentile window to 100 for shorter histories. Scale thresholds up by 5-10 points for high-vol assets like crypto to maintain signal sparsity.
 Behavior, Constraints & Performance
- Repaint/confirmation: Counts update only on confirmed bars via day-key changes, with no future references—live bars may shade red tentatively but tallies finalize at session close.
- security()/HTF: Not used, so no higher-timeframe repaint risks; all computations stay in the chart's resolution.
- Resources: Relies on a fixed-size array of seven elements and small loops for sorting and table fills, capped at 5000 bars back—efficient for most charts but may slow on very long intraday histories.
- Known limits: Ignores weekends and holidays implicitly via data presence; early chart bars lack full percentile context, leading to initial undercounting; assumes continuous sessions, so gaps in data (e.g., news halts) skew totals.
  Sensible Defaults & Quick Tuning 
Start with the built-in values for broad-market daily charts: ATR at 14, window at 252, threshold at 10. For noisier environments, lower the threshold to 5 and shorten the window to 100 to prioritize rare squeezes. If too few events appear, raise the threshold to 15 and extend ATR to 20 for broader capture. To combat overcounting in sparse data, widen the window to 500 while keeping others stock—monitor the info label's data-days count before trusting patterns.
  What this indicator is—and isn’t 
This serves as a statistical overlay for spotting calendar-based volatility biases, aiding in session selection and filter design. It is not a standalone signal generator, predictive model, or risk manager—integrate it with price action, volume, and broader strategy rules 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
First-Move-Wrong Toolkit [CHE]  First-Move-Wrong Toolkit   — Session-bound sweep rejection with structure confirmation
  Summary 
This indicator marks potential “first move wrong” reversals during a defined trading session. It looks for a quick sweep beyond the prior day high or low, or the opening range high or low, followed by rejection and a basic structure confirmation. Optional rules require a retest and a VWAP reclaim in the direction of the trade idea. The script renders session levels as right-extended lines, signals as labels, optional SL/TP guide lines for visualization, and background tints during sweep events. Pivots are confirmed using swing width, which reduces repaint risk compared to live swings.
  Motivation: Why this design? 
Intraday reversals often start with a liquidity sweep around obvious highs or lows. Acting on the sweep alone can be noisy, while waiting for structure break and a retest can be slow. This tool balances both by checking a sweep and rejection at session-relevant levels, then requiring a simple structure cue and, optionally, a retest and a VWAP filter. The goal is a clear, rule-based signal layer that is easy to audit on chart without hidden state.
  What’s different vs. standard approaches? 
 Baseline reference: Simple sweep detectors or basic CHOCH markers that ignore session context and liquidity anchors.
 Architecture differences:
   Session-aware opening range tracking that finalizes after the chosen minutes from session start.
   Daily previous high and low pulled without lookahead, then extended forward as visual anchors.
   Confirmed pivot highs and lows to avoid repaint from live, unconfirmed swings.
   Optional retest rule using crossover or crossunder at the trigger level.
   Optional VWAP filter to demand reclaim in the intended direction.
   Global label cooldown to prevent clusters of signals.
 Practical effect: Fewer one-off flips around noisy levels, clearer alignment with session structure, and compact visual feedback through lines, labels, and tints.
  How it works (technical) 
 Levels: During the defined session, the script builds an opening range high and low until the configured minute mark after session start, then freezes those levels for the day. It also fetches the previous day high and low from the daily timeframe without lookahead and extends them forward.
 Sweep and rejection: A sweep is defined as price moving beyond a target level and then rejecting back inside on the same bar. The script checks this condition separately for highs and lows against opening range and previous-day levels.
 Structure validation: Confirmed pivot highs and lows are computed using a symmetric swing width. A bearish idea requires a prior sweep of a high plus a break through the last confirmed swing low. A bullish idea requires a prior sweep of a low plus a break through the last confirmed swing high.
 Optional retest: If enabled, a bearish signal needs a cross under the bearish trigger level; a bullish signal needs a cross over the bullish trigger level.
 VWAP filter (optional): The script requires a reclaim of VWAP in the intended direction when enabled.
 State handling: Opening range values, previous-day lines, and the label cooldown timestamp are stored in persistent variables. Lines are created once and updated each bar to extend forward.
 Repaint considerations: Pivots confirm only after the specified swing width, reducing repaint. The daily level request is performed without lookahead. Signals use closed-bar checks implied by crossover and crossunder logic.
  Parameter Guide 
 Session (local) — Defines the active trading window. Default nine to seventeen. Narrower windows focus on the main session drive.
 Opening Range (min) — Minutes from session start to finalize OR levels. Default fifteen. Shorter values react faster; longer values stabilize levels.
 Use PrevDay H/L levels — Toggle previous-day anchors. On by default.
 Use OR H/L levels — Toggle opening range anchors. On by default.
 Equal H/L tolerance (ticks) — Intended tolerance for equal highs or lows. Default one. (Unknown/Optional) in current signals.
 Swing width — Bars on both sides for confirmed pivots. Default two. Larger values reduce noise but confirm later.
 Require CHOCH after sweep — Enforces structure break after a sweep. On by default.
 Prefer retest entries — Requires crossover or crossunder of the trigger level. On by default.
 VWAP filter — Demands a reclaim of VWAP in signal direction. Off by default.
 TP in R (guide) — Multiplier for visual TP guides. Default one. Visualization only.
 Show levels / Show signals / Show R-guides — Rendering toggles. R-guides are visual aids, not orders.
 Label cooldown (bars) — Minimum bars between labels. Default five. Higher values reduce clusters.
 Palette inputs — Colors and transparencies for levels, labels, VWAP, and tints.
  Reading & Interpretation 
 Lines: Dotted lines represent opening range high and low after the OR window completes. Dashed lines represent previous-day high and low.
 Signals: “Long” labels appear after a low-side sweep with rejection and structure confirmation, subject to optional retest and VWAP rules. “Short” labels mirror this on the high side.
 Background tints: Red-tinted bars indicate a high-side sweep and rejection. Green-tinted bars indicate a low-side sweep and rejection.
 R-guides: Circles display a visual stop level at the bar extreme and a target guide based on the selected multiple. They are informational only.
  Practical Workflows & Combinations 
 Session reversal scans: During the first hour, watch for sweeps around previous-day or opening range levels, then wait for structure confirmation and optional retest.
 Trend following with filters: Combine signals with higher-timeframe structure or a moving average regime check. Ignore signals against the dominant regime.
 Exits and stops: Use the visual stop as a reference near the sweep extreme; adapt the target guide to volatility and market conditions.
 Multi-asset / Multi-TF: Works on intraday timeframes for liquid futures, indices, forex, and large-cap equities. Start with default settings and adjust swing width and OR minutes to instrument volatility.
  Behavior, Constraints & Performance 
 Repaint/confirmation: Pivots confirm after the swing window completes. Signals occur only when conditions are met on closed bars.
 security()/HTF: Daily previous-day levels are requested without lookahead to reduce repaint.
 Resources: Uses persistent variables and line updates per bar; no heavy loops or arrays.
 Known limits: Signals can arrive later when swing width is large. Gaps around session boundaries may distort OR levels. VWAP behavior may vary with partial sessions or illiquid assets.
  Sensible Defaults & Quick Tuning 
 Starting point: Session nine to seventeen, opening range fifteen minutes, swing width two, CHOCH required, retest on, VWAP off, cooldown five bars.
 Too many flips: Increase swing width, enable VWAP filter, or raise label cooldown.
 Too sluggish: Reduce swing width or shorten the opening range window.
 Too many session-level hits: Disable either previous-day levels or opening range levels to simplify context.
  What this indicator is—and isn’t 
This is a session-aware visualization and signal layer focused on sweep-plus-structure behavior. It is not a complete trading system and does not manage orders, risk, or portfolio exposure. Use it with market structure, risk limits, and execution rules that fit your process.
 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 
Squeeze Hour Frequency [CHE]Squeeze Hour Frequency (ATR-PR) — Standalone — Tracks daily squeeze occurrences by hour to reveal time-based volatility patterns 
  Summary 
This indicator identifies periods of unusually low volatility, defined as squeezes, and tallies their frequency across each hour of the day over historical trading sessions. By aggregating counts into a sortable table, it helps users spot hours prone to these conditions, enabling better scheduling of trading activity to avoid or target specific intraday regimes. Signals gain robustness through percentile-based detection that adapts to recent volatility history, differing from fixed-threshold methods by focusing on relative lowness rather than absolute levels, which reduces false positives in varying market environments.
  Motivation: Why this design? 
Traders often face uneven intraday volatility, with certain hours showing clustered low-activity phases that precede or follow breakouts, leading to mistimed entries or overlooked calm periods. The core idea of hourly squeeze frequency addresses this by binning low-volatility events into 24 hourly slots and counting distinct daily occurrences, providing a historical profile of when squeezes cluster. This reveals time-of-day biases without relying on real-time alerts, allowing proactive adjustments to session focus.
  What’s different vs. standard approaches? 
- Reference baseline: Classical volatility tools like simple moving average crossovers or fixed ATR thresholds, which flag squeezes uniformly across the day.
- Architecture differences:
  - Uses persistent arrays to track one squeeze per hour per day, preventing overcounting within sessions.
  - Employs custom sorting on ratio arrays for dynamic table display, prioritizing top or bottom performers.
  - Handles timezones explicitly to ensure consistent binning across global assets.
- Practical effect: Charts show a persistent table ranking hours by squeeze share, making intraday patterns immediately visible—such as a top hour capturing over 20 percent of total events—unlike static overlays that ignore temporal distribution, which matters for avoiding low-liquidity traps in crypto or forex.
  How it works (technical) 
The indicator first computes a rolling volatility measure over a specified lookback period. It then derives a relative ranking of the current value against recent history within a window of bars. A squeeze is flagged when this ranking falls below a user-defined cutoff, indicating the value is among the lowest in the recent sample.
On each bar, the local hour is extracted using the selected timezone. If a squeeze occurs and the bar has price data, the count for that hour increments only if no prior mark exists for the current day, using a persistent array to store the last marked day per hour. This ensures one tally per unique trading day per slot.
At the final bar, arrays compile counts and ratios for all 24 hours, where the ratio represents each hour's share of total squeezes observed. These are sorted ascending or descending based on display mode, and the top or bottom subset populates the table. Background shading highlights live squeezes in red for visual confirmation. Initialization uses zero-filled arrays for counts and negative seeds for day tracking, with state persisting across bars via variable declarations.
No higher timeframe data is pulled, so there is no repaint risk from external fetches; all logic runs on confirmed bars.
  Parameter Guide 
ATR Length — Controls the lookback for the volatility measure, influencing sensitivity to short-term fluctuations; shorter values increase responsiveness but add noise, longer ones smooth for stability — Default: 14 — Trade-offs/Tips: Use 10-20 for intraday charts to balance quick detection with fewer false squeezes; test on historical data to avoid over-smoothing in trending markets.
Percentile Window (bars) — Sets the history depth for ranking the current volatility value, affecting how "low" is defined relative to past; wider windows emphasize long-term norms — Default: 252 — Trade-offs/Tips: 100-300 bars suit daily cycles; narrower for fast assets like crypto to catch recent regimes, but risks instability in sparse data.
Squeeze threshold (PR < x) — Defines the cutoff for flagging low relative volatility, where values below this mark a squeeze; lower thresholds tighten detection for rarer events — Default: 10.0 — Trade-offs/Tips: 5-15 percent for conservative signals reducing false positives; raise to 20 for more frequent highlights in high-vol environments, monitoring for increased noise.
Timezone — Specifies the reference for hourly binning, ensuring alignment with market sessions — Default: Exchange — Trade-offs/Tips: Set to "America/New_York" for US assets; mismatches can skew counts, so verify against chart timezone.
Show Table — Toggles the results display, essential for reviewing frequencies — Default: true — Trade-offs/Tips: Disable on mobile for performance; pair with position tweaks for clean overlays.
Pos — Places the table on the chart pane — Default: Top Right — Trade-offs/Tips: Bottom Left avoids candle occlusion on volatile charts.
Font — Adjusts text readability in the table — Default: normal — Trade-offs/Tips: Tiny for dense views, large for emphasis on key hours.
Dark — Applies high-contrast colors for visibility — Default: true — Trade-offs/Tips: Toggle false in light themes to prevent washout.
Display — Filters table rows to focus on extremes or full list — Default: All — Trade-offs/Tips: Top 3 for quick scans of risky hours; Bottom 3 highlights safe low-squeeze periods.
  Reading & Interpretation 
Red background shading appears on bars meeting the squeeze condition, signaling current low relative volatility. The table lists hours as "H0" to "H23", with columns for daily squeeze counts, percentage share of total squeezes (summing to 100 percent across hours), and an arrow marker on the top hour. A summary row above details the peak count, its share, and the leading hour. A label at the last bar recaps total days observed, data-valid days, and top hour stats. Rising shares indicate clustering, suggesting regime persistence in that slot.
  Practical Workflows & Combinations 
- Trend following: Scan for hours with low squeeze shares to enter during stable regimes; confirm with higher highs or lower lows on the 15-minute chart, avoiding top-share hours post-news like tariff announcements.
- Exits/Stops: Tighten stops in high-share hours to guard against sudden vol spikes; use the table to shift to conservative sizing outside peak squeeze times.
- Multi-asset/Multi-TF: Defaults work across crypto pairs on 5-60 minute timeframes; for stocks, widen percentile window to 500 bars. Combine with volume oscillators—enter only if squeeze count is below average for the asset.
  Behavior, Constraints & Performance 
Logic executes on closed bars, with live bars updating counts provisionally but finalizing on confirmation; table refreshes only at the last bar, avoiding intrabar flicker. No security calls or higher timeframes, so no repaint from external data. Resources include a 5000-bar history limit, loops up to 24 iterations for sorting and totals, and arrays sized to 24 elements; labels and table are capped at 500 each for efficiency. Known limits: Skips hours without bars (e.g., weekends), assumes uniform data availability, and may undercount in sparse sessions; timezone shifts can alter profiles without warning.
  Sensible Defaults & Quick Tuning 
Start with ATR Length at 14, Percentile Window at 252, and threshold at 10.0 for broad crypto use. If too many squeezes flag (noisy table), raise threshold to 15.0 and narrow window to 100 for stricter relative lowness. For sluggish detection in calm markets, drop ATR Length to 10 and threshold to 5.0 to capture subtler dips. In high-vol assets, widen window to 500 and threshold to 20.0 for stability.
  What this indicator is—and isn’t 
This is a historical frequency tracker and visualization layer for intraday volatility patterns, best as a filter in multi-tool setups. It is not a standalone signal generator, predictive model, or risk manager—pair it with price action, news filters, and position sizing rules.
  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
Thanks to Duyck
for the ma sorter
MILLION MEN - Smart ZonesMILLION MEN — Smart Zones
What it is
A smart, structure-based Support/Resistance indicator that automatically anchors dynamic Smart Zones from the latest confirmed swing high and low. It identifies two adaptive regions — the Premium Zone near swing highs and the Discount Zone near swing lows — with an optional 50% equilibrium line for balanced price analysis.
How it works (high-level)
Confirmed swings: Uses ta.pivothigh and ta.pivotlow with adaptive or manual lookback.
Smart pairing: When both recent pivots are confirmed, the script anchors a new pair and builds zones based on that range.
Dynamic zones:
Discount Zone: Bottom portion of the range (e.g., 25%).
Premium Zone: Top portion of the range.
Midline: Optional 50% equilibrium; can extend right.
Lifecycle control:
Zones auto-update as new highs/lows appear.
Option to re-anchor when a new swing pair forms.
Option to auto-expire after a set number of bars for clean charts.
Color scheme:
Green = Discount Zone
Fuchsia = Premium Zone
Gray = Midline
How to use
Works well on 5m–1H for intraday, or 4H–1D for swing.
Use the Discount Zone for long bias setups and the Premium Zone for short bias confirmations.
Combine with your preferred momentum, VWAP, or volume tools for confluence.
Adjust Zone Depth % and Auto-expire depending on your timeframe.
Originality & value
Unlike static S/R indicators, Smart Zones evolve with price structure — re-anchoring on new swing formations while maintaining clarity and balance. Its confirmed-pivot logic avoids repainting and produces professional, non-cluttered charts for precision trading.
Limitations & transparency
Pivots confirm with delay equal to pivot length; this prevents repaint.
Results differ by asset and volatility regime.
Non-standard chart types (Heikin-Ashi, Renko, Range) are not supported.
This script provides analytical guidance, not financial advice.
Dominant DATR [CHE]  Dominant DATR   — Directional ATR stream with dominant-side EMA, bands, labels, and alerts 
  Summary 
Dominant DATR builds two directional volatility streams from the true range, assigns each bar’s range to the up or down side based on the sign of the close-to-close move, and then tracks the dominant side through an exponential average. A rolling band around the dominant stream defines recent extremes, while optional gradient coloring reflects relative magnitude. Swing-based labels mark new higher highs or lower lows on the dominant stream, and alerts can be enabled for swings, zero-line crossings, and band breakouts. The result is a compact pane that highlights regime bias and intensity without relying on price overlays.
  Motivation: Why this design? 
Conventional ATR treats all range as symmetric, which can mask directional pressure, cause late regime shifts, and produce frequent false flips during noisy phases. This design separates the range into up and down contributions, then emphasizes whichever side is stronger. A single smoothed dominant stream clarifies bias, while the band and swing markers help distinguish continuation from exhaustion. Optional normalization by close makes the metric comparable across instruments with different price scales.
  What’s different vs. standard approaches? 
 Reference baseline: Classic ATR or a basic EMA of price.
 Architecture differences:
   Directional weighting of range using positive and negative close-to-close moves.
   Separate moving averages for up and down contributions combined into one dominant stream.
   Rolling highest and lowest of the dominant stream to form a band.
   Optional normalization by close, window-based scaling for color intensity, and gamma adjustment for visual contrast.
   Event logic for swing highs and lows on the dominant stream, with label buffering and pruning.
   Configurable alerts for swings, zero-line crossings, and band breakouts.
 Practical effect: You see when volatility is concentrated on one side, how strong that bias currently is, and when the dominant stream pushes through or fails at its recent envelope.
  How it works (technical) 
 Each bar’s move is split into an up component and a down component based on whether the close increased or decreased relative to the prior close. The bar’s true range is proportionally assigned to up or down using those components as weights.
 Each side is smoothed with a Wilder-style moving average. The dominant stream is the side with the larger value, recorded as positive for up dominance and negative for down dominance.
 The dominant stream is then smoothed with an exponential moving average to reduce noise and provide a responsive yet stable signal line.
 A rolling window tracks the highest and lowest values of the dominant EMA to form an envelope. Crossings of these bounds indicate unusual strength or weakness relative to recent history.
 For visualization, the absolute value of the dominant EMA is scaled over a lookback window and passed through a gamma curve to modulate gradient intensity. Colors are chosen separately for up and down regimes.
 Swing events are detected by comparing the dominant EMA to its recent extremes over a short lookback. Labels are placed when a prior bar set an extreme and the current bar confirms it. A managed array prunes older labels when the user-defined maximum is exceeded.
 Alerts mirror these events and also include zero-line crossings and band breakouts. The script does not force closed-bar confirmation; users should configure alert execution timing to suit their workflow.
 There are no higher-timeframe requests and no security calls. State is limited to simple arrays for labels and persistent color parameters.
  Parameter Guide 
Parameter — Effect — Default — Trade-offs/Tips
 ATR Length — Smoothing of directional true range streams — fourteen — Longer reduces noise and may delay regime shifts; shorter increases responsiveness.
 EMA Length — Smoothing of the dominant stream — twenty-five — Lower values react faster; higher values reduce whipsaw.
 Band Length — Window for recent highs and lows of the dominant stream — ten — Short windows flag frequent breakouts; long windows emphasize only exceptional moves.
 Normalize by Close — Divide by close price to produce a percent-like scale — false — Useful across assets with very different price levels.
 Enable gradient color — Turn on magnitude-based coloring — true — Visual aid only; can be disabled for simplicity.
 Gradient window — Lookback used to scale color intensity — one hundred — Larger windows stabilize the color scale.
 Gamma (lines) — Adjust gradient intensity curve — zero point eight — Lower values compress variation; higher values expand it.
 Gradient transparency — Transparency for gradient plots — zero, between zero and ninety — Higher values mute colors.
 Up dark / Up neon — Base and peak colors for up dominance — green tones — Styling only.
 Down dark / Down neon — Base and peak colors for down dominance — red tones — Styling only.
 Show zero line / Background tint — Visual references for regime — true and false — Background tint can help quick scanning.
 Swing length — Bars used to detect swing highs or lows — two — Larger values demand more structure.
 Show labels / Max labels / Label offset — Label visibility, cap, and vertical offset — true, two hundred, zero — Increase cap with care to avoid clutter.
 Alerts: HH/LL, Zero Cross, Band Break — Toggle alert rules — true, false, false — Enable only what you need.
  Reading & Interpretation 
 The dominant EMA above zero indicates up-side dominance; below zero indicates down-side dominance.
 Band lines show recent extremes of the dominant EMA; pushes through the band suggest unusual momentum on the dominant side.
 Gradient intensity reflects local magnitude of dominance relative to the chosen window.
 HH/LL labels appear when the dominant stream prints a new local extreme in the current regime and that extreme is confirmed on the next bar.
 Zero-line crosses suggest regime flips; combine with structure or filters to reduce noise.
  Practical Workflows & Combinations 
 Trend following: Consider entries when the dominant EMA is on the regime side and expands away from zero. Band breakouts add confirmation; structure such as higher highs or lower lows in price can filter signals.
 Exits and stops: Tighten exits when the dominant stream stalls near the band or fades toward zero. Opposite swing labels can serve as early caution.
 Multi-asset and multi-timeframe: Works across liquid assets and common timeframes. For lower noise instruments, reduce smoothing slightly; for high noise, increase lengths and swing length.
  Behavior, Constraints & Performance 
 Repaint and confirmation: No security calls and no future-looking references. Swing labels confirm one bar later by design. Real-time crosses can change intra-bar; use bar-close alerts if needed.
 Resources: `max_bars_back` is two thousand. The script uses an array for labels with pruning, gradient color computations, and a simple while loop that runs only when the label cap is exceeded.
 Known limits: The EMA can lag at sharp turns. Normalization by close changes scale and may affect thresholds. Extremely gappy data can produce abrupt shifts in the dominant side.
  Sensible Defaults & Quick Tuning 
 Starting point: ATR Length fourteen, EMA Length twenty-five, Band Length ten, Swing Length two, gradient enabled.
 Too many flips: Increase EMA Length and swing length, or enable only swing alerts.
 Too sluggish: Decrease EMA Length and Band Length.
 Inconsistent scales across symbols: Enable Normalize by Close.
 Visual clutter: Disable gradient or reduce label cap.
  What this indicator is—and isn’t 
This is a volatility-bias visualization and signal layer that highlights directional pressure and intensity. It is not a complete trading system and does not produce position sizing or risk management. Use it with market structure, context, 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 
Hour/Day/Month Optimizer [CHE]  Hour/Day/Month Optimizer   — Bucketed seasonality ranking for hours, weekdays, and months with additive or compounded returns, win rate, simple Sharpe proxy, and trade counts
  Summary 
This indicator profiles time-of-day, day-of-week, and month-of-year behavior by assigning every bar to a bucket and accumulating its return into that bucket. It reports per-bucket score (additive or compounded), win rate, a dispersion-aware return proxy, and trade counts, then ranks buckets and highlights the current one if it is best or worst. A compact on-chart table shows the top buckets or the full ranking; a last-bar label summarizes best and worst. Optional hour filtering and UTC shifting let you align buckets with your trading session rather than exchange time.
  Motivation: Why this design? 
Traders often see repetitive timing effects but struggle to separate genuine seasonality from noise. Static averages are easily distorted by sample size, compounding, or volatility spikes. The core idea here is simple, explicit bucket aggregation with user-controlled accumulation (sum or compound) and transparent quality metrics (win rate, a dispersion-aware proxy, and counts). The result is a practical, legible seasonality surface that can be used for scheduling and filtering rather than prediction.
  What’s different vs. standard approaches? 
 Reference baseline: Simple heatmaps or average-return tables that ignore compounding, dispersion, or sample size.
 Architecture differences:
Dual aggregation modes: additive sum of bar returns or compounded factor.
Per-bucket win rate and trade count to expose sample support.
A simple dispersion-aware return proxy to penalize unstable averages.
UTC offset and optional custom hour window.
Deterministic, closed-bar rendering via a lightweight on-chart table.
Practical effect: You see not only which buckets look strong but also whether the observation is supported by enough bars and whether stability is acceptable. The background tint and last-bar label give immediate context for the current bucket.
  How it works (technical) 
Each bar is assigned to a bucket based on the selected dimension (hour one to twenty-four, weekday one to seven, or month one to twelve) after applying the UTC shift. An optional hour filter can exclude bars outside a chosen window. For each bucket the script accumulates either the sum of simple returns or the compounded product of bar factors. It also counts bars and wins, where a win is any bar with a non-negative return. From these, it derives:
Score: additive total or compounded total minus the neutral baseline.
Win rate: wins as a percentage of bars in the bucket.
Dispersion-aware proxy (“Sharpe” column): a crude ratio that rises when average return improves and falls when variability increases.
Buckets are sorted by a user-selected key (score, win rate, dispersion proxy, or trade count). The current bar’s bucket is tinted if it matches the global best or worst. At the last bar, a table is drawn with headers, an optional info row, and either the top three or all rows, using zebra backgrounds and color-coding (lime for best, red for worst). Rendering is last-bar only; no higher-timeframe data is requested, and no future data is referenced.
  Parameter Guide 
 UTC Offset (hours) — Shifts bucket assignment relative to exchange time. Default: zero. Tip: Align to your local or desk session.
 Use Custom Hours — Enables a local session window. Default: off. Trade-off: Reduces noise outside your active hours but lowers sample size.
 Start / End — Inclusive hour window one to twenty-four. Defaults: eight to seventeen. Tip: Widen if rankings look unstable.
 Aggregation — “Additive” sums bar returns; “Multiplicative” compounds them. Default: Additive. Tip: Use compounded for long-horizon bias checks.
 Dimension — Bucket by Hour, Day, or Month. Default: Hour. Tip: Start Hour for intraday planning; switch to Day or Month for scheduling.
 Show — “Top Three” or “All”. Default: Top Three. Trade-off: Clarity vs. completeness.
 Sort By — Score, Win Rate, Sharpe, or Trades. Default: Score. Tip: Use Trades to surface stable buckets; use Win Rate for skew awareness.
 X / Y — Table anchor. Defaults: right / top. Tip: Move away from price clusters.
 Text — Table text size. Default: normal.
 Light Mode — Light palette for bright charts. Default: off.
 Show Parameters Row — Info header with dimension and span. Default: on.
 Highlight Current Bucket if Best/Worst — Background tint when current bucket matches extremes. Default: on.
 Best/Worst Barcolor — Tint colors. Defaults: lime / red.
 Mark Best/Worst on Last Bar — Summary label on the last bar. Default: on.
  Reading & Interpretation 
 Score column: Higher suggests stronger cumulative behavior for the chosen aggregation. Compounded mode emphasizes persistence; additive mode treats all bars equally.
 Win Rate: Stability signal; very high with very low trades is unreliable.
 “Sharpe” column: A quick stability proxy; use it to down-rank buckets that look good on score but fluctuate heavily.
 Trades: Sample size. Prefer buckets with adequate counts for your timeframe and asset.
 Tinting: If the current bucket is globally best, expect a lime background; if worst, red. This is context, not a trade signal.
  Practical Workflows & Combinations 
 Trend following: Use Hour or Day to avoid initiating trades during historically weak buckets; require structure confirmation such as higher highs and higher lows, plus a momentum or volatility filter.
 Mean reversion: Prefer buckets with moderate scores but acceptable win rate and dispersion proxy; combine with deviation bands or volume normalization.
 Exits/Stops: Tighten exits during historically weak buckets; relax slightly during strong ones, but keep absolute risk controls independent of the table.
 Multi-asset/Multi-TF: Start with Hour on liquid intraday assets; for swing, use Day. On monthly seasonality, require larger lookbacks to avoid overfitting.
  Behavior, Constraints & Performance 
 Repaint/confirmation: Calculations use completed bars only; table and label are drawn on the last bar and can update intrabar until close.
 security()/HTF: None used; repaint risk limited to normal live-bar updates.
 Resources: Arrays per dimension, light loops for metric building and sorting, `max_bars_back` two thousand, and capped label/table counts.
 Known limits: Sensitive to sample size and regime shifts; ignores costs and slippage; bar-based wins can mislead on assets with frequent gaps; compounded mode can over-weight streaks.
  Sensible Defaults & Quick Tuning 
 Start: Hour dimension, Additive, Top Three, Sort by Score, default session window off.
 Too many flips: Switch to Sort by Trades or raise sample by widening hours or timeframe.
 Too sluggish/over-smoothed: Switch to Additive (if on compounded) or shorten your chart timeframe while keeping the same dimension.
 Overfit risk: Prefer “All” view to verify that top buckets are not isolated with tiny counts; use Day or Month only with long histories.
  What this indicator is—and isn’t 
This is a seasonality and scheduling layer that ranks time buckets using transparent arithmetic and simple stability checks. It is not a predictive model, not a complete trading system, and it does not manage risk. Use it to plan when to engage, then rely on structure, confirmation, and independent risk management for entries and exits.
 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 
SuperTrend Optimizer Remastered[CHE]  SuperTrend Optimizer Remastered   — Grid-ranked SuperTrend with additive or multiplicative scoring
  Summary 
This indicator evaluates a fixed grid of one hundred and two SuperTrend parameter pairs and ranks them by a simple flip-to-flip return model. It auto-selects the currently best-scoring combination and renders its SuperTrend in real time, with optional gradient coloring for faster visual parsing. The original concept is by  KioseffTrading  Thanks a lot for it. 
For years I wanted to shorten the roughly two thousand three hundred seventy-one lines; I have now reduced the core to about three hundred eighty lines without triggering script errors. The simplification is generalizable to other indicators. A multiplicative return mode was added alongside the existing additive aggregation, enabling different rankings and often more realistic compounding behavior.
  Motivation: Why this design? 
SuperTrend is sensitive to its factor and period. Picking a single pair statically can underperform across regimes. This design sweeps a compact parameter grid around user-defined lower bounds, measures flip-to-flip outcomes, and promotes the combination with the strongest cumulative return. The approach keeps the visual footprint familiar while removing manual trial-and-error. The multiplicative mode captures compounding effects; the additive mode remains available for linear aggregation.
 Originally (by KioseffTrading) 
  Very long script (~2,371 lines), monolithic structure.
 SuperTrend optimization with additive (cumulative percentage-sum) scoring only.
 Heavier use of repetitive code; limited modularity and fewer UI conveniences.
 No explicit multiplicative compounding option; rankings did not reflect sequence-sensitive equity growth. 
 Now (remastered by CHE) 
  Compact core (~380 lines) with the same functional intent, no compile errors.
 Adds multiplicative (compounding) scoring alongside additive, changing rankings to reflect real equity paths and penalize drawdown sequences.
 Fixed 34×3 grid sweep, live ranking, gradient-based bar/wick/line visuals, top-table display, and an optional override plot.
 Cleaner arrays/state handling, last-bar table updates, and reusable simplification pattern that can be applied to other indicators. 
  What’s different vs. standard approaches? 
 Baseline: A single SuperTrend with hand-picked inputs.
 Architecture differences:
   Fixed grid of thirty-four factor offsets across three ATR offsets.
   Per-combination flip-to-flip backtest with additive or multiplicative aggregation.
   Live ranking with optional “Best” or “Worst” table output.
   Gradient bar, wick, and line coloring driven by consecutive trend counts.
   Optional override plot to force a specific SuperTrend independent of ranking.
 Practical effect: Charts show the currently best-scoring SuperTrend, not a static choice, plus an on-chart table of top performers for transparency.
  How it works (technical) 
For each parameter pair, the script computes SuperTrend value and direction. It monitors direction transitions and treats a change from up to down as a long entry and the reverse as an exit, measuring the move between entry and exit using close prices. Results are aggregated per pair either by summing percentage changes or by compounding return factors and then converting to percent for comparison. On the last bar, open trades are included as unrealized contributions to ranking. The best combination’s line is plotted, with separate styling for up and down regimes. Consecutive regime counts are normalized within a rolling window and mapped to gradients for bars, wicks, and lines. A two-column table reports the best or worst performers, with an optional row describing the parameter sweep.
  Parameter Guide 
 Factor (Lower Bound) — Starting SuperTrend factor; the grid adds offsets between zero and three point three. Default three point zero. Higher raises distance to price and reduces flips.
 ATR Period (Lower Bound) — Starting ATR length; the grid adds zero, one, and two. Default ten. Longer reduces noise at the cost of responsiveness.
 Best vs Worst — Ranks by top or bottom cumulative return. Default Best. Use Worst for stress tests.
 Calculation Mode — Additive sums percents; Multiplicative compounds returns. Multiplicative is closer to equity growth and can change the leaderboard.
 Show in Table — “Top Three” or “All”. Fewer rows keep charts clean.
 Show “Parameters Tested” Label — Displays the effective sweep ranges for auditability.
 Plot Override SuperTrend — If enabled, the override factor and ATR are plotted instead of the ranked winner.
 Override Factor / ATR Period — Values used when override is on.
 Light Mode (for Table) — Adjusts table colors for bright charts.
 Gradient/Coloring controls — Toggles for gradient bars and wick coloring, window length for normalization, gamma for contrast, and transparency settings. Use these to emphasize or tone down visual intensity.
 Table Position and Text Size — Places the table and sets typography.
  Reading & Interpretation 
The auto SuperTrend plots one line for up regimes and one for down regimes. Color intensity reflects consecutive trend persistence within the chosen window. A small square at the bottom encodes the same gradient as a compact status channel. Optional wick coloring uses the same gradient for maximum contrast. The performance table lists parameter pairs and their cumulative return under the chosen aggregation; positive values are tinted with the up color, negative with the down color. “Long” labels mark flips that open a long in the simplified model.
  Practical Workflows & Combinations 
 Trend following: Use the auto line as your primary bias. Enter on flips aligned with structure such as higher highs and higher lows. Filter with higher-timeframe trend or volatility contraction.
 Exits/Stops: Consider conservative exits when color intensity fades or when the opposite line is approached. Aggressive traders can trail near the plotted line.
 Override mode: When you want stability across instruments, enable override and standardize factor and ATR; keep the table visible for sanity checks.
 Multi-asset/Multi-TF: Defaults travel well on liquid instruments and intraday to daily timeframes. Heavier assets may prefer larger lower bounds or multiplicative mode.
  Behavior, Constraints & Performance 
 Repaint/confirmation: Signals are based on SuperTrend direction; confirmation is best assessed on closed bars to avoid mid-bar oscillation. No higher-timeframe requests are used.
 Resources: One hundred and two SuperTrend evaluations per bar, arrays for state, and a last-bar table render. This is efficient for the grid size but avoid stacking many instances.
 Known limits: The flip model ignores costs, slippage, and short exposure. Rapid whipsaws can degrade both aggregation modes. Gradients are cosmetic and do not change logic.
  Sensible Defaults & Quick Tuning 
Start with the provided lower bounds and “Top Three” table.
 Too many flips → raise the lower bound factor or period.
 Too sluggish → lower the bounds or switch to additive mode.
 Rankings feel unstable → prefer multiplicative mode and extend the normalization window.
 Visuals too strong → increase gradient transparency or disable wick coloring.
  What this indicator is—and isn’t 
This is a parameter-sweep and visualization layer for SuperTrend selection. It is not a complete trading system, not predictive, and does not include position sizing, transaction costs, or risk management. Combine with market structure, higher-timeframe context, and explicit risk controls.
Attribution and refactor note: The original work is by KioseffTrading. The script has been refactored from approximately two thousand three hundred seventy-one lines to about three hundred eighty core lines, retaining behavior without compiler errors. The general simplification pattern is reusable for other indicators.
  Metadata 
 Name/Tag: SuperTrend Optimizer Remastered  
 Pine version: v6
 Overlay or separate pane: true (overlay)
 Core idea/principle: Grid-based SuperTrend selection by cumulative flip returns with additive or multiplicative aggregation.
 Primary outputs/signals: Auto-selected SuperTrend up and down lines, optional override lines, gradient bar and wick colors, “Long” labels, performance table.
 Inputs with defaults: See Parameter Guide above.
 Metrics/functions used: SuperTrend, ATR, arrays, barstate checks, windowed normalization, gamma-based contrast adjustment, table API, gradient utilities.
 Special techniques: Fixed grid sweep, compounding vs linear aggregation, last-bar UI updates, gradient encoding of persistence.
 Performance/constraints: One hundred and two SuperTrend calls, arrays of length one hundred and two, label budget, last-bar table updates, no higher-timeframe requests.
 Recommended use-cases/workflows: Trend bias selection, quick parameter audits, override standardization across assets.
 Compatibility/assets/timeframes: Standard OHLC charts across intraday to daily; liquid instruments recommended.
 Limitations/risks: Costs and slippage omitted; mid-bar instability possible; not suitable for synthetic chart types.
 Debug/diagnostics: Ranking table, optional tested-range label; internal counters for consecutive trends.
 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
FibPulse144 [CHE]  FibPulse144   — ADX-gated 13/21 crossover with 144-trend regime and closed-bar labels 
  Summary 
FibPulse144 combines a fast moving-average crossover with a 144-period trend regime and an ADX strength gate. Signals are confirmed on closed bars only and drawn as labels on the price chart, while an ADX line in a separate pane provides context. Color gradients are derived from normalized ADX, so visual intensity reflects trend strength without changing the underlying logic. The approach reduces false flips during weak conditions and keeps entries aligned with the dominant trend.
  Motivation: Why this design? 
Traditional crossover signals can flip repeatedly during sideways phases and often trigger against the higher-time regime. By requiring alignment with a slower trend proxy and by gating entries through a rising ADX condition, FibPulse144 favors structurally cleaner transitions. Gradient coloring communicates strength visually, helping users temper aggressiveness without additional indicators.
  What’s different vs. standard approaches? 
 Baseline: Classic dual-MA crossover with unconditional signals.
 Architecture differences:
   Two-bar regime confirmation against a 144-period trend average.
   Pending-signal logic that waits for regime and optional ADX approval.
   ADX strength gate using the prior reading relative to a user threshold and earlier value.
   Gradient colors scaled by an ADX window with gamma controls.
   Price-chart labels enforced via overlay on an otherwise pane-based indicator.
 Practical effect: Fewer signals during weak or choppy conditions, labels that appear only after a bar closes, and color intensity that mirrors trend quality.
  How it works (technical) 
The script computes fast and slow moving averages using the selected method and lengths. A separate 144-length average defines the regime using a two-bar confirmation above or below it. Crossovers are observed on the previous bar to avoid intrabar ambiguity; once a prior crossover is detected, it is stored as pending. A pending long requires regime alignment and, if enabled, an ADX condition based on the previous reading being above the threshold and greater than an earlier reading. The state machine holds neutral, long, or short until an exit condition or ADX reset is met. ADX is normalized within a user window, scaled with gamma, and mapped to up and down color palettes to render gradients. Labels on the price panel are forced to overlay, while the ADX line and threshold guide remain in a separate pane.
  Parameter Guide 
 Source — Input data for all calculations. Default: close. Tip: keep consistent with your chart.
 MA Type — EMA or SMA. Default: EMA. EMA reacts faster; SMA is smoother.
 Fast / Slow — Fast and slow lengths for crossover. Defaults: 13 and 21. Shorter reacts earlier; longer reduces noise.
 Trend — Regime average length. Default: 144. Larger values stabilize regime; smaller values increase sensitivity.
 Use 144 as trend filter — Enables regime gating. Default: true. Disable to allow raw crossovers.
 Use ADX filter — Requires ADX strength. Default: true. Disable to allow signals regardless of strength.
 ADX Len — DI and ADX smoothing length. Default: 14. Higher values smooth strength; lower values react faster.
 ADX Thresh — Minimum strength for signals. Default: 25. Raise to reduce flips; lower to capture earlier moves.
 Entry/Exit labels (price) — Price-panel labels on state changes. Default: true.
 Signal labels in ADX pane — Small markers at the ADX value on entries. Default: true.
 Label size — tiny, small, normal, large. Default: normal.
 Enable barcolor — Optional candle tint by regime and gradient. Default: false.
 Enable gradient — Turns on ADX-driven color blending. Default: true.
 Window — Bars used to normalize ADX for colors. Default: 100; minimum: 5.
 Gamma bars / Gamma plots — Nonlinear scaling for bar and line intensities. Default: 0.80; between 0.30 and 2.00.
 Gradient transp (0–90) — Transparency for gradient colors. Default: 0.
 MA fill transparency (0–100) — Fill opacity between fast and slow lines. Default: 65.
 Palette colors (Up/Down) — Dark and neon endpoints for up and down gradients. Defaults as in the code.
  Reading & Interpretation 
 Fast/Slow lines: When the fast line is above the slow line, the line and fill use the long palette; when below, the short palette is used.
 Trend MA (144): Neutral gray line indicating the regime boundary.
 Labels on price: “LONG” appears when the state turns long; “SHORT” when it turns short. Labels appear only after the bar closes and conditions are satisfied.
 ADX pane: The ADX line shows current strength. The dotted threshold line is the user level for gating. Optional small markers indicate entries at the ADX value.
 Bar colors (optional): Candle tint intensity reflects normalized ADX. Higher intensity implies stronger conditions.
  Practical Workflows & Combinations 
 Trend following: Use long entries when fast crosses above slow and price has held above the trend average for two bars, with ADX above threshold. Mirror this for shorts below the trend average.
 Exits and stops: Consider reducing exposure when price closes on the opposite side of the trend average for two consecutive bars or when ADX fades below the threshold if the ADX filter is enabled.
 Structure confirmation: Combine with higher-timeframe structure such as swing highs and lows or a simple market structure overlay for confirmation.
 Multi-asset/Multi-TF: Works across liquid assets. For lower timeframes, consider a slightly lower ADX threshold; for higher timeframes, maintain or raise the threshold to avoid unnecessary flips.
  Behavior, Constraints & Performance 
 Repaint/confirmation: Signals are based on previous-bar crossovers and are confirmed on bar close. No higher-timeframe or security calls are used. Intrabar markers are not relied upon.
 Resources: The script declares `max_bars_back` of 2000, uses no loops or arrays, and employs persistent variables for pending signals and state.
 Known limits: Crossover systems can lag after sudden reversals. During tight ranges, disabling the ADX filter may increase flips; keeping it enabled may skip early transitions.
  Sensible Defaults & Quick Tuning 
 Starting point: EMA, 13/21/144, ADX length 14, ADX threshold 25, gradients on, barcolor off.
 Too many flips: Increase ADX threshold or length; increase trend length; consider SMA instead of EMA.
 Too sluggish: Lower ADX threshold slightly; shorten fast and slow lengths; reduce the trend length.
 Colors overpowering: Increase gradient transparency or reduce gamma values toward one.
  What this indicator is—and isn’t 
This is a visualization and signal layer that combines crossover, regime, and strength gating. It does not predict future movements, manage risk, or execute trades. Use it alongside clear structure, risk controls, and a defined position management plan.
  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 
Quarter Strength Table (3M) [CHE]  Quarter Strength Table (3M) — quarterly seasonality overview for the current symbol 
 Is there seasonality in certain assets? Some YouTubers claim there is—can you test it yourself? 
  Summary 
This indicator builds a compact table that summarizes quarterly seasonality from three-month bars. It aggregates the simple return of each historical quarter, counts observations, computes the average return and the win rate for each quarter, and flags the historically strongest quarter. The output is a five-column table rendered on the chart, designed for quick comparison rather than signal generation. Because it processes only confirmed higher-timeframe bars, results are stable once a quarter has closed.
  Motivation: Why this design? 
Seasonality tools often mix intraperiod estimates with live bars, which can lead to misleading flips and inconsistent statistics. The core idea here is to restrict aggregation to completed three-month bars only and to deduplicate events by timestamp. This avoids partial information and double counting, so the table reflects a consistent, closed-bar history.
  What’s different vs. standard approaches? 
 Baseline: Typical seasonality studies that compute monthly or quarterly stats directly on the chart timeframe or update on live higher-timeframe bars.
 Architecture differences:
   Uses explicit higher-timeframe requests for open, close, time, and calendar month from three-month bars.
   Confirms the higher-timeframe bar before recording a sample; deduplicates by the higher-timeframe timestamp.
   Keeps fixed arrays of length four for the four quarters; renders a fixed five-by-five table with zebra rows.
 Practical effect: Once a quarter closes, counts and averages are stable. The “Best” column marks the highest average quarter so you can quickly identify the historically strongest period.
  How it works (technical) 
On every chart bar, the script requests three-month open, close, time, and the calendar month derived from that bar’s time. When the three-month bar is confirmed, it computes the simple return for that bar and maps the month to a quarter index between zero and three. A guard stores the last seen three-month timestamp to avoid duplicate writes. Per quarter, it accumulates the sum of returns, the number of samples, and the number of positive samples. From these, it derives average return and win rate. The table header is created once on the first bar; content updates only on the last visible chart bar for efficiency. No forward references are used, and lookahead is disabled in all higher-timeframe requests to avoid peeking.
  Parameter Guide 
 Percent — Formats values as percentages. Default: true. Trade-off: Easier visual comparison; disable if you prefer raw unit returns.
 Decimals — Number of digits shown. Default: two. Bounds: zero to six. Trade-off: More digits improve precision but reduce readability.
 Show table — Toggles table rendering. Default: true. Trade-off: Disable when space is limited or for batch testing.
  Reading & Interpretation 
The table shows rows for Q1 through Q4 and columns for Count, Avg Ret, P(win), and Best.
 Count: Number of completed three-month bars observed for that quarter.
 Avg Ret: Average simple return across all samples in that quarter.
 P(win): Share of samples with a positive return.
 Best: An asterisk marks the quarter with the highest average return among those with at least one sample.
  Use the combination of average and win rate to judge both magnitude and consistency. Low counts signal limited evidence.
  Practical Workflows & Combinations 
 Trend following filter: Favor setups when the upcoming or active quarter historically shows a positive average and a stable win rate. Combine with structure analysis such as higher highs and higher lows to avoid fighting dominant trends.
 Exits and risk: When entering during a historically weak quarter, consider tighter risk controls and quicker profit taking.
 Multi-asset and multi-timeframe: The default settings work across most liquid symbols. For assets with sparse history, treat results as low confidence due to small sample sizes.
  Behavior, Constraints & Performance 
 Repaint and confirmation: Aggregation occurs only when the three-month bar is confirmed; values do not change afterward for that bar. During an open quarter, no new sample is added.
 Higher-timeframe usage: All higher-timeframe requests disable lookahead and rely on confirmation to mitigate repaint.
 Resources: Declared `max_bars_back` is two thousand. Arrays are fixed at length four. The script updates the table only on the last visible bar to reduce work.
 Known limits: Averages can be affected by outliers and structural market changes. Limited history reduces reliability. Corporate actions and contract rolls may influence returns depending on the symbol’s data source. This is a visualization and not a trading system.
  Sensible Defaults & Quick Tuning 
 Starting values: Percent true; Decimals two; Show table true.
 If numbers feel noisy: Decrease decimals to one to reduce visual clutter.
 If you need raw values: Turn off Percent to display unit returns.
 If the table overlaps price: Toggle Show table off when annotating, or reposition via your chart’s table controls.
  What this indicator is—and isn’t 
This is a historical summary of quarterly behavior. It visualizes evidence and helps frame expectations. It is not predictive, does not generate trade signals, and does not manage positions or risk. Always combine with market structure, liquidity considerations, and independent risk controls.
 Inputs with defaults 
 Percent: true, boolean.
 Decimals: two, integer between zero and six.
 Show table: true, boolean.
Pine version: v6
Overlay: true
Primary outputs: Table with five columns and five rows.
Metrics/functions used: Higher-timeframe data requests, table rendering, arrays, bar state checks, month mapping.
Special techniques: Closed-bar aggregation, deduplication by higher-timeframe timestamp, zebra row styling.
Performance/constraints: Two thousand bars back, small fixed loops, higher-timeframe requests without lookahead.
Compatibility/assets/timeframes: Works on time-based charts across most assets with sufficient history.
Limitations/risks: Sample size sensitivity, regime shifts, data differences across venues.
Debug/diagnostics: (Unknown/Optional)
 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 
BayesStack RSI [CHE]BayesStack RSI   — Stacked RSI with Bayesian outcome stats and gradient visualization
  Summary 
BayesStack RSI builds a four-length RSI stack and evaluates it with a simple Bayesian success model over a rolling window. It highlights bull and bear stack regimes, colors price with magnitude-based gradients, and reports per-regime counts, wins, and estimated win rate in a compact table. Signals seek to be more robust through explicit ordering tolerance, optional midline gating, and outcome evaluation that waits for events to mature by a fixed horizon. The design focuses on readable structure, conservative confirmation, and actionable context rather than raw oscillator flips.
  Motivation: Why this design? 
Classical RSI signals flip frequently in volatile phases and drift in calm regimes. Pure threshold rules often misclassify shallow pullbacks and stacked momentum phases. The core idea here is ordered, spaced RSI layers combined with outcome tracking. By requiring a consistent order with a tolerance and optionally gating by the midline, regime identification becomes clearer. A horizon-based maturation check and smoothed win-rate estimate provide pragmatic feedback about how often a given stack has recently worked.
  What’s different vs. standard approaches? 
 Reference baseline: Traditional single-length RSI with overbought and oversold rules or simple crossovers.
 Architecture differences:
   Four fixed RSI lengths with strict ordering and a spacing tolerance.
   Optional requirement that all RSI values stay above or below the midline for bull or bear regimes.
   Outcome evaluation after a fixed horizon, then rolling counts and a prior-smoothed win rate.
   Dispersion measurement across the four RSIs with a percent-rank diagnostic.
   Gradient coloring of candles and wicks driven by stack magnitude.
   A last-bar statistics table with counts, wins, win rate, dispersion, and priors.
 Practical effect: Charts emphasize sustained momentum alignment instead of single-length crosses. Users see when regimes start, how strong alignment is, and how that regime has recently performed for the chosen horizon.
  How it works (technical) 
The script computes RSI on four lengths and forms a “stack” when they are strictly ordered with at least the chosen tolerance between adjacent lengths. A bull stack requires a descending set from long to short with positive spacing. A bear stack requires the opposite. Optional gating further requires all RSI values to sit above or below the midline.
For evaluation, each detected stack is checked again after the horizon has fully elapsed. A bull event is a success if price is higher than it was at event time after the horizon has passed. A bear event succeeds if price is lower under the same rule. Rolling sums over the training window track counts and successes; a pair of priors stabilizes the win-rate estimate when sample sizes are small.
Dispersion across the four RSIs is measured and converted to a percent rank over a configurable window. Gradients for bars and wicks are normalized over a lookback, then shaped by gamma controls to emphasize strong regimes. A statistics table is created once and updated on the last bar to minimize overhead. Overlay markers and wick coloring are rendered to the price chart even though the indicator runs in a separate pane.
  Parameter Guide 
 Source — Input series for RSI. Default: close. Tips: Use typical price or hlc3 for smoother behavior.
 Overbought / Oversold — Guide levels for context. Defaults: seventy and thirty. Bounds: fifty to one hundred, zero to fifty. Tips: Narrow the band for faster feedback.
 Stacking tolerance (epsilon) — Minimum spacing between adjacent RSIs to qualify as a stack. Default: zero point twenty-five RSI points. Trade-off: Higher values reduce false stacks but delay entries.
 Horizon H — Bars ahead for outcome evaluation. Default: three. Trade-off: Longer horizons reduce noise but delay success attribution.
 Rolling window — Lookback for counts and wins. Default: five hundred. Trade-off: Longer windows stabilize the win rate but adapt more slowly.
 Alpha prior / Beta prior — Priors used to stabilize the win-rate estimate. Defaults: one and one. Trade-off: Larger priors reduce variance with sparse samples.
 Show RSI 8/13/21/34 — Toggle raw RSI lines. Default: on.
 Show consensus RSI — Weighted combination of the four RSIs. Default: on.
 Show OB/OS zones — Draw overbought, oversold, and midline. Default: on.
 Background regime — Pane background tint during bull or bear stacks. Default: on.
 Overlay regime markers — Entry markers on price when a stack forms. Default: on.
 Show statistics table — Last-bar table with counts, wins, win rate, dispersion, priors, and window. Default: on.
 Bull requires all above fifty / Bear requires all below fifty — Midline gate. Defaults: both on. Trade-off: Stricter regimes, fewer but cleaner signals.
 Enable gradient barcolor / wick coloring — Gradient visuals mapped to stack magnitude. Defaults: on. Trade-off: Clearer regime strength vs. extra rendering cost.
 Collection period — Normalization window for gradients. Default: one hundred. Trade-off: Shorter values react faster but fluctuate more.
 Gamma bars and shapes / Gamma plots — Curve shaping for gradients. Defaults: zero point seven and zero point eight. Trade-off: Higher values compress weak signals and emphasize strong ones.
 Gradient and wick transparency — Visual opacity controls. Defaults: zero.
 Up/Down colors (dark and neon) — Gradient endpoints. Defaults: green and red pairs.
 Fallback neutral candles — Directional coloring when gradients are off. Default: off.
 Show last candles — Limit for gradient squares rendering. Default: three hundred thirty-three.
 Dispersion percent-rank length / High and Low thresholds — Window and cutoffs for dispersion diagnostics. Defaults: two hundred fifty, eighty, and twenty.
 Table X/Y, Dark theme, Text size — Table anchor, theme, and typography. Defaults: right, top, dark, small.
  Reading & Interpretation 
 RSI stack lines: Alignment and spacing convey regime quality. Wider spacing suggests stronger alignment.
 Consensus RSI: A single line that summarizes the four lengths; use as a smoother reference.
 Zones: Overbought, oversold, and midline provide context rather than standalone triggers.
 Background tint: Indicates active bull or bear stack.
 Markers: “Bull Stack Enter” or “Bear Stack Enter” appears when the stack first forms.
 Gradients: Brighter tones suggest stronger stack magnitude; dull tones suggest weak alignment.
 Table: Count and Wins show sample size and successes over the window. P(win) is a prior-stabilized estimate. Dispersion percent rank near the high threshold flags stretched alignment; near the low threshold flags tight clustering.
  Practical Workflows & Combinations 
 Trend following: Enter only on new stack markers aligned with structure such as higher highs and higher lows for bull, or lower lows and lower highs for bear. Use the consensus RSI to avoid chasing into overbought or oversold extremes.
 Exits and stops: Consider reducing exposure when dispersion percent rank reaches the high threshold or when the stack loses ordering. Use the table’s P(win) as a context check rather than a direct signal.
 Multi-asset and multi-timeframe: Defaults travel well on liquid assets from intraday to daily. Combine with higher-timeframe structure or moving averages for regime confirmation. The script itself does not fetch higher-timeframe data.
  Behavior, Constraints & Performance 
 Repaint and confirmation: Stack markers evaluate on the live bar and can flip until close. Alert behavior follows TradingView settings. Outcome evaluation uses matured events and does not look into the future.
 HTF and security: Not used. Repaint paths from higher-timeframe aggregation are avoided by design.
 Resources: max bars back is two thousand. The script uses rolling sums, percent rank, gradient rendering, and a last-bar table update. Shapes and colored wicks add draw overhead.
 Known limits: Lag can appear after sharp turns. Very small windows can overfit recent noise. P(win) is sensitive to sample size and priors. Dispersion normalization depends on the collection period.
  Sensible Defaults & Quick Tuning 
Start with the shipped defaults.
 Too many flips: Increase stacking tolerance, enable midline gates, or lengthen the collection period.
 Too sluggish: Reduce stacking tolerance, shorten the collection period, or relax midline gates.
 Sparse samples: Extend the rolling window or increase priors to stabilize P(win).
 Visual overload: Disable gradient squares or wick coloring, or raise transparency.
  What this indicator is—and isn’t 
This is a visualization and context layer for RSI stack regimes with simple outcome statistics. It is not a complete trading system, not predictive, and not a signal generator on its own. Use it with market structure, risk controls, and position management that fit your process.
 Metadata 
- Pine version: v6
- Overlay: false (price overlays are drawn via forced overlay where applicable)
- Primary outputs: Four RSI lines, consensus line, OB/OS guides, background tint, entry markers, gradient bars and wicks, statistics table
- Inputs with defaults: See Parameter Guide
- Metrics and functions used: RSI, rolling sums, percent rank, dispersion across RSI set, gradient color mapping, table rendering, alerts
- Special techniques: Ordered RSI stacking with tolerance, optional midline gating, horizon-based outcome maturation, prior-stabilized win rate, gradient normalization with gamma shaping
- Performance and constraints: max bars back two thousand, rendering of shapes and table on last bar, no higher-timeframe data, no security calls
- Recommended use-cases: Regime confirmation, momentum alignment, post-entry management with dispersion and recent outcome context
- Compatibility: Works across assets and timeframes that support RSI
- Limitations and risks: Sensitive to parameter choices and market regime changes; not a standalone strategy
- Diagnostics: Statistics table, dispersion percent rank, gradient intensity
 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.
Best regards and happy trading
Chervolino.
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.
Swing Z | Zillennial Technologies Inc.Swing Z by Zillennial Technologies Inc. is an advanced algorithmic framework built specifically for cryptocurrency markets. It integrates multiple layers of technical analysis into a single decision-support tool, generating buy and sell signals only when several independent confirmations align.
Core Concept
Swing Z fuses trend structure, momentum oscillators, volatility signals, and price action tools to capture high-probability trading opportunities in volatile crypto environments.
Trend Structure (EMA 9, 21, 50, 200)
Short-term EMAs (9 & 21) detect immediate momentum shifts.
Longer-term EMAs (50 & 200) define the broader trend and dynamic support/resistance.
Momentum & Confirmation Layer
RSI measures relative strength and market conditions.
MACD crossovers confirm momentum shifts and trend continuations.
Volatility & Market Pressure
TTM Squeeze highlights compression zones likely to precede breakouts.
Volume analysis confirms conviction behind directional moves.
VWAP (Volume Weighted Average Price) establishes intraday value zones and institutional benchmarks.
Price Action Filters
Fibonacci retracements are integrated to identify key reversal and continuation levels.
Signals are produced only when multiple conditions agree, reducing noise and improving reliability in fast-moving crypto markets.
Features
Tailored for cryptocurrency trading across major pairs (BTC, ETH, and altcoins).
Works effectively on swing and trend-based timeframes (1H–1D).
Combines trend, momentum, volatility, and price action into a single framework.
Generates clear Buy/Sell markers and integrates with TradingView alerts.
How to Use
Apply to a clean chart for the clearest visualization.
Use Swing Z as a swing trading tool, aligning entries with both trend structure and momentum confirmation.
Combine with your own stop-loss, take-profit, and position sizing rules.
Avoid application on non-standard chart types such as Renko, Heikin Ashi, or Point & Figure, which may distort results.
Disclaimer
Swing Z is designed as a decision-support tool, not financial advice.
All backtesting should use realistic risk, commission, and slippage assumptions.
Past results do not guarantee future performance.
Signals do not repaint but may adjust as new data develops in real-time.
Why Swing Z is original & useful:
Swing Z unifies EMA trend structure, RSI, MACD, TTM Squeeze, VWAP, Fibonacci retracements, and volume analysis into a single algorithmic framework. This multi-confirmation approach improves accuracy by requiring consensus across trend, momentum, volatility, and price action — a design made specifically for the challenges and volatility of cryptocurrency markets.
Swing Z – Crypto Trading Algorithm | Zillennial Technologies IncSwing Z by Zillennial Technologies Inc. is an advanced algorithmic framework built specifically for cryptocurrency markets. It integrates multiple layers of technical analysis into a single decision-support tool, generating buy and sell signals only when several independent confirmations align.
Core Concept
Swing Z fuses trend structure, momentum oscillators, volatility signals, and price action tools to capture high-probability trading opportunities in volatile crypto environments.
Trend Structure (EMA 9, 21, 50, 200)
Short-term EMAs (9 & 21) detect immediate momentum shifts.
Longer-term EMAs (50 & 200) define the broader trend and dynamic support/resistance.
Momentum & Confirmation Layer
RSI measures relative strength and market conditions.
MACD crossovers confirm momentum shifts and trend continuations.
Volatility & Market Pressure
TTM Squeeze highlights compression zones likely to precede breakouts.
Volume analysis confirms conviction behind directional moves.
VWAP (Volume Weighted Average Price) establishes intraday value zones and institutional benchmarks.
Price Action Filters
Fibonacci retracements are integrated to identify key reversal and continuation levels.
Signals are produced only when multiple conditions agree, reducing noise and improving reliability in fast-moving crypto markets.
Features
Tailored for cryptocurrency trading across major pairs (BTC, ETH, and altcoins).
Works effectively on swing and trend-based timeframes (1H–1D).
Combines trend, momentum, volatility, and price action into a single framework.
Generates clear Buy/Sell markers and integrates with TradingView alerts.
How to Use
Apply to a clean chart for the clearest visualization.
Use Swing Z as a swing trading tool, aligning entries with both trend structure and momentum confirmation.
Combine with your own stop-loss, take-profit, and position sizing rules.
Avoid application on non-standard chart types such as Renko, Heikin Ashi, or Point & Figure, which may distort results.
Disclaimer
Swing Z is designed as a decision-support tool, not financial advice.
All backtesting should use realistic risk, commission, and slippage assumptions.
Past results do not guarantee future performance.
Signals do not repaint but may adjust as new data develops in real-time.
Why Swing Z is original & useful:
Swing Z unifies EMA trend structure, RSI, MACD, TTM Squeeze, VWAP, Fibonacci retracements, and volume analysis into a single algorithmic framework. This multi-confirmation approach improves accuracy by requiring consensus across trend, momentum, volatility, and price action — a design made specifically for the challenges and volatility of cryptocurrency markets.
Objective Doji Highlight (Range-Relative)This indicator highlights Doji candles using an objective, mathematics-based rule: a bar is Doji when the absolute difference between its open and close is less than or equal to a user-defined fraction (x) of that bar’s high–low range.
How it works:
Compute body size as the absolute difference between open and close.
Compute the bar’s range as high minus low.
Classify as Doji when body size ≤ x × range.
Only Doji candles are colored; non-Doji bars remain unchanged.
Inputs
Doji threshold (x of range): tolerance (0–1) controlling how small the body must be relative to the range.
Doji Candle Color: visual color for detected Doji candles.
Example:
If x = 0.10 and a candle has high = 100 and low = 90 (range = 10), the maximum allowed body is 1.
If the difference between open and close is ≤ 1, the candle is marked as Doji.
Why it can be useful
Doji candles are often studied as signs of market indecision. This tool provides a clear, parameter-based way to identify them consistently across any timeframe, without discretionary interpretation.
Notes & limitations
Works with standard candlesticks (not Heikin Ashi, Renko, or other synthetic bar types).
Visualization and research only: it does not produce buy/sell signals and makes no performance claims.
No repainting from future data; the logic uses only the current bar’s prices.
BB KC Triangle SignalsBased on Trader Oracle's engulfing candle off Bolinger Band. 
I added keltner channels as well. So this prints a symbol ( I use triangles) over the engulfing candle at or near the bolinger band/ keltner channel. Don't have to have the bands printed on the screen for them to work. Seems to work on renko too. 
High Timeframe Candle Overlay (Configurable)HTF Candle Overlay — Read Higher Timeframe on Lower Timeframe Charts
What it does
This indicator draws each selected Higher-Timeframe (HTF) candle directly on your lower-timeframe (LTF) chart. It shows a translucent range box (HTF high–low) and an inner body box (HTF open–close), so you can track how the bigger candle is forming while you analyze lower-timeframe structure, liquidity sweeps, and intrabar reactions.
Why it’s helpful
	•	See where the current HTF candle opened, where price sits inside its body, and how far wicks extend—without leaving your LTF chart.
	•	Combine HTF context (e.g., 1H/4H) with LTF execution (e.g., 1m–15m) to spot confluence, S/R flips, and failed breaks faster.
	•	The overlay is locked to the price scale and anchored by bar index, so it pans/zooms exactly with your chart (no drifting while dragging).
⸻
How it works (under the hood)
	•	Fetches HTF OHLC via request.security.
	•	When a new HTF bar starts, the previous HTF boxes are frozen at the true close.
	•	The current HTF bar updates intrabar (so you see live formation) and is clamped to the correct span.
	•	Horizontal anchoring uses bar index, and a hidden price plot binds the script to the main price scale for stable zoom/pan behavior.
⸻
Inputs
	•	High Timeframe (HTF): Default 1H (set any TF you like).
	•	Show High–Low Box: On/off.
	•	Show Body Box (Open–Close): On/off.
	•	Opacity for range/body boxes.
	•	Bull/Bear Colors and Outline + Width.
	•	Max HTF Candles to Keep: Auto-deletes older boxes to maintain performance.
⸻
Usage tips
	•	Popular combos: view 1H or 4H candles while trading 1–15m charts.
	•	Turn off the range box if you only want a clean HTF body overlay.
	•	Pair with your session/structure tools; this indicator is visual context only (no signals or alerts).
⸻
Notes & limitations
	•	Non-repainting for closed HTF bars: once an HTF candle closes, its boxes are fixed. The current/in-progress HTF bar updates until it closes (expected live behavior).
	•	Data alignment depends on your symbol’s feed and session settings. Heikin Ashi/renko/etc. may not match classic OHLC.
	•	Heavy history + many boxes can affect performance; reduce “Max HTF Candles to Keep” if needed.
⸻
Disclaimer
This script is for education and charting visualization only. It does not provide financial advice, trade signals, or performance guarantees. Always do your own research and manage risk.
FlowScape PredictorFlowScape Predictor is a non-repainting, regime-aware entry qualifier that turns complex market context into two readiness scores (Long & Short, each 0/25/50/75/100) and clean, confirmed-bar signals. It blends three orthogonal pillars so you act only when trend energy, momentum, and location agree:
Regime (energy): ATR-normalized linear-regression slope of a smooth HMA → EMA baseline, gated by ADX to confirm when pressure is meaningful.
Momentum (push): RSI slope alignment so price has directional follow-through, not just drift.
Structure (location): proximity to pivot-confirmed swings, scaled by ATR, so “ready” appears near constructive pullbacks—not mid-trend chases.
A soft ATR cloud wraps the baseline for context. A yellow Predictive Baseline extends beyond the last bar to visualize near-term trajectory. It is visual-only: scores/alerts never use it.
What you see
Baseline line that turns green/red when regime is strong in that direction; gray when weak.
ATR cloud around the baseline (context for stretch and pullbacks).
Scores (Long & Short, 0–100 in steps of 25) and optional “L/S” icons on bar close.
Yellow Predictive Baseline that extends to the right for a few bars (visual trajectory of the smoothed baseline).
The scoring system (simple and transparent)
Each side (Long/Short) sums four binary checks, 25 points each:
Regime aligned: trendStrong is true and LR slope sign favors that side.
Momentum aligned: RSI side (>50 for Long, <50 for Short) and RSI slope confirms direction.
Baseline side: price is above (Long) / below (Short) the baseline.
Location constructive: distance from the last confirmed pivot is healthy (ATR-scaled; not overstretched).
Valid totals are 0, 25, 50, 75, 100.
Best-quality signal: 100/0 (your side/opposite) on bar close.
Good, still valid: 75/0, especially when the missing block is only “location” right as price re-engages the cloud/baseline.
Avoid: 75/25 or any opposition > 0 in a weak (gray) regime.
The Predictive (Kalman) line — what it is and isn’t
The yellow line is a visual forward extension of the smoothed baseline to help you see the current trajectory and time pullback resumptions. It does not predict price and is excluded from scores and alerts.
How it’s built (plain English):
We maintain a one-dimensional Kalman state x as a smoothed estimate of the baseline. Each bar we observe the current baseline z.
The filter adjusts its trust using the Kalman gain K = P / (P + R) and updates:
x := x + K*(z − x), then P := (1 − K)*P + Q.
Q (process noise): Higher Q → expects faster change → tracks turns quicker (less smoothing).
R (measurement noise): Higher R → trusts raw baseline less → smoother, steadier projection.
What you control:
Lead (how many bars forward to draw).
Kalman Q/R (visual smoothness vs. responsiveness).
Toggle the line on/off if you prefer a minimal chart.
Important: The predictive line extends the baseline, not price. It’s a visual timing aid—don’t automate off it.
How to use (step-by-step)
Keep the chart clean and use a standard OHLC/candlestick chart.
Read the regime: Prefer trades with green/red baseline (trendStrong = true).
Check scores on bar close:
Take Long 100 / Short 0 or Long 75 / Short 0 when the chart shows a tidy pullback re-engaging the cloud/baseline.
Mirror the logic for shorts.
Confirm location: If price is > ~1.5 ATR from its reference pivot, let it come back—avoid chasing.
Set alerts: Add an alert on Long Ready or Short Ready; these fire on closed bars only.
Risk management: Use ATR-buffered stops beyond the recent pivot; target fixed-R multiples (e.g., 1.5–3.0R). Manage the trade with the baseline/cloud if you trail.
Best-practice playbook (quick rules)
Green light: 100/0 (best) or 75/0 (good) on bar close in a colored (non-gray) regime.
Location first: Prefer entries near the baseline/cloud right after a pullback, not far above/below it.
Avoid mixed signals: Skip 75/25 and anything with opposition while the baseline is gray.
Use the yellow line with discretion: It helps you see rhythm; it’s not a signal source.
Timeframes & tuning (practical defaults)
Intraday indices/FX (5m–15m): Demand 100/0 in chop; allow 75/0 when ADX is awake and pullback is clean.
Crypto intraday (15m–1h): Prefer 100/0; 75/0 on the first pullback after a regime turn.
Swing (1h–4h/D1): 75/0 is often sufficient; 100/0 is excellent (fewer but cleaner signals).
If choppy: raise ADX threshold, raise the readiness bar (insist on 100/0), or lengthen the RSI slope window.
What makes FlowScape different
Energy-first regime filter: ATR-normalized LR slope + ADX gate yields a consistent read of trend quality across symbols and timeframes.
Location-aware entries: ATR-scaled pivot proximity discourages mid-air chases, encouraging pullback timing.
Separation of concerns: The predictive line is visual-only, while scores/alerts are confirmed on close for non-repainting behavior.
One simple score per side: A single 0–100 readiness figure is easier to tune than juggling multiple indicators.
Transparency & limitations
Scores are coarse by design (25-point blocks). They’re a gatekeeper, not a promise of outcomes.
Pivots confirm after right-side bars, so structure signals appear after swings form (non-repainting by design).
Avoid using non-standard chart types (Heikin Ashi, Renko, Range, etc.) for signals; use a clean, standard chart.
No lookahead, no higher-timeframe requests; alerts fire on closed bars only.
MACD Liquidity Tracker Strategy [Quant Trading]MACD Liquidity Tracker Strategy 
 Overview 
The MACD Liquidity Tracker Strategy is an enhanced trading system that transforms the traditional MACD indicator into a comprehensive momentum-based strategy with advanced visual signals and risk management. This strategy builds upon the original MACD Liquidity Tracker System indicator by  TheNeWSystemLqtyTrckr , converting it into a fully automated trading strategy with improved parameters and additional features.
 What Makes This Strategy Original 
This strategy significantly enhances the basic MACD approach by introducing:
 
 Four distinct system types for different market conditions and trading styles
 Advanced color-coded histogram visualization with four dynamic colors showing momentum strength and direction
 Integrated trend filtering using 9 different moving average types
 Comprehensive risk management with customizable stop-loss and take-profit levels
 Multiple alert systems for entry signals, exits, and trend conditions
 Flexible signal display options with customizable entry markers
 
 How It Works 
 Core MACD Calculation 
The strategy uses a fully customizable MACD configuration with traditional default parameters:
 
 Fast MA : 12 periods (customizable, minimum 1, no maximum limit)
 Slow MA : 26 periods (customizable, minimum 1, no maximum limit) 
 Signal Line : 9 periods (customizable, now properly implemented and used)
 
 Cryptocurrency Optimization : The strategy's flexible parameter system allows for significant optimization across different crypto assets. Traditional MACD settings (12/26/9) often generate excessive noise and false signals in volatile crypto markets. By using slower, more smoothed parameters, traders can capture meaningful momentum shifts while filtering out market noise.
 Example - DOGE Optimization (45/80/290 settings) :
•  Performance : Optimized parameters yielding exceptional backtesting results with 29,800% PnL
•  Why it works : DOGE's high volatility and social sentiment-driven price action benefits from heavily smoothed indicators
•  Timeframes : Particularly effective on 30-minute and 4-hour charts for swing trading
•  Logic : The very slow parameters filter out noise and capture only the most significant trend changes 
 Other Optimizable Cryptocurrencies : This parameter flexibility makes the strategy highly effective for major altcoins including  SUI, SEI, LINK, Solana (SOL) , and many others. Each crypto asset can benefit from custom parameter tuning based on its unique volatility profile and trading characteristics.
 Four Trading System Types 
 1. Normal System (Default) 
 
 Long signals : When MACD line is above the signal line
 Short signals : When MACD line is below the signal line
 Best for : Swing trading and capturing longer-term trends in stable markets
 Logic : Traditional MACD crossover approach using the signal line
 
 2. Fast System 
 
 Long signals : Bright Blue OR Dark Magenta (transparent) histogram colors
 Short signals : Dark Blue (transparent) OR Bright Magenta histogram colors
 Best for : Scalping and high-volatility markets (crypto, forex)
 Logic : Leverages early momentum shifts based on histogram color changes
 
 3. Safe System 
 
 Long signals : Only Bright Blue histogram color (strongest bullish momentum)
 Short signals : All other colors (Dark Blue, Bright Magenta, Dark Magenta)
 Best for : Risk-averse traders and choppy markets
 Logic : Prioritizes only the strongest bullish signals while treating everything else as bearish
 
 4. Crossover System 
 
 Long signals : MACD line crosses above signal line
 Short signals : MACD line crosses below signal line
 Best for : Precise timing entries with traditional MACD methodology
 Logic : Pure crossover signals for more precise entry timing
 
 Color-Coded Histogram Logic 
The strategy uses four distinct colors to visualize momentum:
 
 🔹 Bright Blue : MACD > 0 and rising (strong bullish momentum)
 🔹 Dark Blue (Transparent) : MACD > 0 but falling (weakening bullish momentum)
 🔹 Bright Magenta : MACD < 0 and falling (strong bearish momentum)
 🔹 Dark Magenta (Transparent) : MACD < 0 but rising (weakening bearish momentum)
 
 Trend Filter Integration 
The strategy includes an advanced trend filter using 9 different moving average types:
 
 SMA  (Simple Moving Average)
 EMA  (Exponential Moving Average) - Default
 WMA  (Weighted Moving Average)
 HMA  (Hull Moving Average)
 RMA  (Running Moving Average)
 LSMA  (Least Squares Moving Average)
 DEMA  (Double Exponential Moving Average)
 TEMA  (Triple Exponential Moving Average)
 VIDYA  (Variable Index Dynamic Average)
 
 Default Settings : 50-period EMA for trend identification
 Visual Signal System 
 
 Entry Markers : Blue triangles (▲) below candles for long entries, Magenta triangles (▼) above candles for short entries
 Candle Coloring : Price candles change color based on active signals (Blue = Long, Magenta = Short)
 Signal Text : Optional "Long" or "Short" text inside entry triangles (toggleable)
 Trend MA : Gray line plotted on main chart for trend reference
 
 Parameter Optimization Examples 
 DOGE Trading Success (Optimized Parameters) :
Using 45/80/290 MACD settings with 50-period EMA trend filter has shown exceptional results on DOGE:
 
 Performance : Backtesting results showing 29,800% PnL demonstrate the power of proper parameter optimization
 Reasoning : DOGE's meme-driven volatility and social sentiment spikes create significant noise with traditional MACD settings
 Solution : Very slow parameters (45/80/290) filter out social media-driven price spikes while capturing only major momentum shifts
 Optimal Timeframes : 30-minute and 4-hour charts for swing trading opportunities
 Result : Exceptionally clean signals with minimal false entries during DOGE's characteristic pump-and-dump cycles
 
 Multi-Crypto Adaptability :
The same optimization principles apply to other major cryptocurrencies:
 
 SUI : Benefits from smoothed parameters due to newer coin volatility patterns
 SEI : Requires adjustment for its unique DeFi-related price movements  
 LINK : Oracle news events create price spikes that benefit from noise filtering
 Solana (SOL) : Network congestion events and ecosystem developments need smoothed detection
 General Rule : Higher volatility coins typically benefit from very slow MACD parameters (40-50 / 70-90 / 250-300 ranges)
 
 Key Input Parameters 
 
 System Type : Choose between Fast, Normal, Safe, or Crossover (Default: Normal)
 MACD Fast MA : 12 periods default (no maximum limit, consider 40-50 for crypto optimization)
 MACD Slow MA : 26 periods default (no maximum limit, consider 70-90 for crypto optimization)
 MACD Signal MA : 9 periods default (now properly utilized, consider 250-300 for crypto optimization)
 Trend MA Type : EMA default (9 options available)
 Trend MA Length : 50 periods default (no maximum limit)
 Signal Display : Both, Long Only, Short Only, or None
 Show Signal Text : True/False toggle for entry marker text
 
 Trading Applications 
 Recommended Use Cases 
 
 Momentum Trading : Capitalize on strong directional moves using the color-coded system
 Trend Following : Combine MACD signals with trend MA filter for higher probability trades
 Scalping : Use "Fast" system type for quick entries in volatile markets
 Swing Trading : Use "Normal" or "Safe" system types for longer-term positions
 Cryptocurrency Trading : Optimize parameters for individual crypto assets (e.g., 45/80/290 for DOGE, custom settings for SUI, SEI, LINK, SOL)
 
 Market Suitability 
 
 Volatile Markets : Forex, crypto, indices (recommend "Fast" system or smoothed parameters)
 Stable Markets : Stocks, ETFs (recommend "Normal" or "Safe" system)
 All Timeframes : Effective from 1-minute charts to daily charts
 Crypto Optimization : Each major cryptocurrency (DOGE, SUI, SEI, LINK, SOL, etc.) can benefit from custom parameter tuning. Consider slower MACD parameters for noise reduction in volatile crypto markets
 
 Alert System 
The strategy provides comprehensive alerts for:
 
 Entry Signals : Long and short entry triangle appearances
 Exit Signals : Position exit notifications
 Color Changes : Individual histogram color alerts
 Trend Conditions : Price above/below trend MA alerts
 
 Strategy Parameters 
 Default Settings 
 
 Initial Capital : $1,000
 Position Size : 100% of equity
 Commission : 0.1%
 Slippage : 3 points
 Date Range : January 1, 2018 to December 31, 2069
 
 Risk Management (Optional) 
 
 Stop Loss : Disabled by default (customizable percentage-based)
 Take Profit : Disabled by default (customizable percentage-based)
 Short Trades : Disabled by default (can be enabled)
 
 Important Notes and Limitations 
 Backtesting Considerations 
 
 Uses realistic commission (0.1%) and slippage (3 points)
 Default position sizing uses 100% equity -  adjust based on risk tolerance 
 Stop-loss and take-profit are disabled by default to show raw strategy performance
 Strategy does not use lookahead bias or future data
 
 Risk Warnings 
 
 Past performance does not guarantee future results 
 MACD-based strategies may produce false signals in ranging markets
 Consider combining with additional confluences like support/resistance levels
 Test thoroughly on demo accounts before live trading
 Adjust position sizing based on your risk management requirements
 
 Technical Limitations 
 
 Strategy does not work on non-standard chart types (Heikin Ashi, Renko, etc.)
 Signals are based on close prices and may not reflect intraday price action
 Multiple rapid signals in volatile conditions may result in overtrading
 
 Credits and Attribution 
This strategy is based on the original  "MACD Liquidity Tracker System"  indicator created by  TheNeWSystemLqtyTrckr . This strategy version includes significant enhancements:
 
 Complete strategy implementation with entry/exit logic
 Addition of the "Crossover" system type
 Proper implementation and utilization of the MACD signal line
 Enhanced risk management features
 Improved parameter flexibility with no artificial maximum limits
 Additional alert systems for comprehensive trade management
 
The original indicator's core color logic and visual system have been preserved while expanding functionality for automated trading applications.
PCR tableOverview 
This indicator displays a multi-period table of forward-looking price projections. It combines normalized directional momentum (Positive Change Ratio, PCR) with volatility (ATR) and presents a forecast for upcoming time intervals, adjusted for your local UTC offset.
 Concepts & Calculations 
 Positive Change Ratio (PCR): 
((total positive change)/(total change)-0.5)*2, producing a value between –100 and +100.
 Synthetic ATR:  Calculates average true range over the same lookbacks to capture volatility.
 PCR × ATR:  Forms a volatility-weighted directional forecast, indicating expected move magnitude.
 Future Price Projection:   Adds PCR × ATR value to current close to estimate future price at each lookahead interval.
 Table Layout 
There are 12 forecast horizons—1× to 12× the chart timeframe (e.g., minutes, hours, days). Each row displays:
1.  Future Time:  Timestamp of each projection (adjustable via UTC offset)
2.  PCR:  Directional bias per period (–1 to +1)
3.  PCR × ATR: E xpected move magnitude
4.  Future Price:  Close + (PCR × ATR)
High and low PCR×ATR rows are highlighted green for minimum value in the price forecast (buy signal) or red for maximum value in the price forecast (sell signal).
 How to Use 
1. Set UTC offset to your time zone for accurate future timestamps.
2. View PCR to assess bullish (positive) or bearish (negative) momentum.
3. Use PCR × ATR to estimate move strength and direction.
4. Reference Future Price for potential levels over upcoming intervals, and for buy and sell signals.
 Limitations & Disclaimers 
* This model uses  linear extrapolation  based on recent price behavior. It does  not guarantee  future prices.
* It uses only current bar data and no lookahead logic—compliant with Pine Script rules.
* Designed for analytical insight, not as an automated signal or trade executor.
* Best used on standard bar/candle charts (avoid non-standard types like Heikin‑Ashi or Renko).
Heikin RiderHeikin Rider  
Smoothed Heikin Ashi Breakout Signals with Flow Confirmation
by Ben Deharde, 2025
 Overview: 
Heikin Rider is a trend-following indicator that detects clean breakout signals using a custom smoothed Heikin Ashi wave (the H-Wave) with optional confirmation from a flow-based filter. It's designed for traders who want precise, momentum-aligned entries.
 What It Does: 
Plots dynamic high/low bands from smoothed Heikin Ashi candles.
 Triggers Buy/Sell signals  on full candle breakouts above/below the wave.
Colors bars based on price position and momentum relative to a custom flow line.
Optionally filters signals based on flow direction.
 How the H-Wave Works: 
The H-Wave is a two-stage smoothed Heikin Ashi construction:
Pre-smoothing: Price is smoothed using a short-length MA (SMA, EMA, or HMA).
HA Calculation: Heikin Ashi values are calculated from the smoothed data.
Post-smoothing: A second, longer MA is applied to the HA values.
Wave Envelope: The high and low wicks of the final smoothed HA candles form the H-Wave envelope.
Signals are generated when price fully breaks this envelope, with optional confirmation from the flow color.
 Inputs: 
Trend timeframe
Pre/Post smoothing type and length
Flow MA type and length
Toggle for bar coloring and signal filtering
 Notes: 
Built with original logic, using the open-source TAExt library (credited).
No repainting — all signals are confirmed at close.
For use on standard candles only (not HA or Renko).
 Alerts: 
Long Signal (Buy)
Short Signal (Sell)
Candle Count RSI📈  Candle Count RSI — A Dual-Perspective Momentum Engine 
The  Candle Count RSI  is a custom-built momentum oscillator that  expands on  the classic Relative Strength Index (RSI) by introducing a directional-only variant that tracks the frequency of bullish or bearish closes, rather than price magnitude. It gives traders a second lens through which to evaluate momentum, trend conviction, and subtle divergences—often invisible to traditional price-based RSI.
💡  What Makes It Unique? 
While the standard RSI is sensitive to the size of price changes, the  Candle Count RSI  is magnitude-blind. It  counts candle closes above/below open  over a lookback period, generating a purer signal of directional consistency. To enhance signal fidelity, it includes a streak amplifier,  dynamically weighting extended runs of green or red candles  to reflect intensity of market bias—without introducing artificial price sensitivity.
 This dual-RSI approach allows for: 
- Divergence detection between directional bias and price magnitude.
- Smoother trend confirmation in choppy markets.
- Cleaner visual cues using dynamic glow and background logic.
📐 How Standard RSI Actually Works (Not What You Think) 
RSI doesn’t just check if price went up or down over a span—it checks each individual candle and tracks whether it closed higher or lower than the one before. Here's how it works under the hood:
1.) For each bar, it calculates the change from the previous close.
2.) It separates those changes into gains (upward moves) and losses (downward moves).
3.) Then it computes a smoothed average of those gains and losses (usually using an RMA).
4.) It calculates the Relative Strength (RS) as: 
        RS = AvgGain / AvgLoss
5.) Finally, it plugs that into the RSI formula: 
        RSI = 100 - (100 / (1 + RS))
⚖️  What Does the 50 Line Mean? 
- The RSI scale runs from 0 to 100, but 50 is the true neutral zone:
    - RSI > 50 means average gains outweigh average losses over the period.
    - RSI < 50 means losses dominate.
    - RSI ≈ 50? The market is balanced—momentum is indecisive, no clear trend bias.
- This makes 50 a powerful midline for trend filters, directional bias tools, and divergence detection—especially when paired with alternative RSI logic like Candle Count RSI.
🔧  Inputs and Customization 
- Everything is fully modular and customizable:
🧠  Core Settings 
- RSI Length: Used for both the standard RSI and Candle Count RSI.
📉  Standard RSI 
- Classic RSI calculation based on price changes.
- Optional WMA smoothing to reduce noise.
- Glow effect toggle with custom intensity.
🕯  Candle Count RSI 
- Computes RSI using only the count of up/down candles.
- Optional smoothing for stability.
- Amplifies streaks (e.g., multiple consecutive bullish candles increase strength).
- Glow effect toggle with adjustable strength.
🎇  Glow Visuals 
- Background glow (subpane and/or main chart).
- Fades based on RSI distance from the 50 midpoint.
- Independent color settings for bull and bear bias.
🧬  Divergence Zones 
- Detects when Candle RSI and Standard RSI diverge.
- Highlights:
    - Bullish Divergence: Candle RSI > 50, Standard RSI < threshold.
    - Bearish Divergence: Candle RSI < 50, Standard RSI > threshold.
    - Background fill optionally shown in subpane and/or main chart.
📊  Directional Histogram 
- MACD-style histogram showing the difference between the two RSI lines.
- Color-coded based on directional agreement:
    - Both rising → green.
    - Both falling → red.
    - Conflict → yellow.
🧠  Under the Hood — How It Works 
🔹  Standard RSI 
- Classic ta.rsi() applied to close prices, optionally WMA-smoothed.
🔹  Candle Count RSI (CCR) 
- Counts how many candles closed up/down over the period.
- Computes a magnitude-free RSI from these counts.
- Applies a streak-based multiplier to exaggerate trend strength during consecutive green/red runs.
- Optionally smoothed with WMA to create a clean signal line.
- This makes CCR ideal for detecting true directional bias without being faked out by volatile price spikes.
🔹  Divergence Logic 
- When Candle RSI and Standard RSI disagree strongly across defined thresholds, background fills highlight early signs of momentum decay or hidden accumulation/distribution.
🔹  Glow Logic 
- Glow zones are controlled by a master toggle and drawn with dynamic transparency:
- Further from 50 = stronger conviction = darker glow.
- Shows up in subpane and/or main chart depending on user preference.
📷  Suggested Use Case / Visual Setup 
- Use in conjunction with your primary price action system.
- Watch for divergences between the Candle Count RSI and Standard RSI for early trend reversals.
- Use glow bias zones on the main chart to get subconscious directional cues during fast scalping.
- Histogram helps you confirm when both RSI variants agree—useful during strong trending conditions.
🛠️  Tip for Traders 
- This tool isn’t trying to “predict” price. It’s designed to visualize hidden market psychology—when buyers are showing up with consistent pressure, or when momentum has a disconnect between conviction and magnitude. Use this to filter entries, spot weak rallies, or sense when a trend is about to break down.
⚠️  WARNING 
- Not for use with Heikin Ashi, Renko, etc.).
🧠  Summary 
 Candle Count RSI  is not just another mashup—it's a precision-built, dual-perspective oscillator that captures directional conviction using real candle behavior. Whether you're scalping intraday or swing trading momentum, this script helps clarify trend integrity and exposes hidden weaknesses with elegance and clarity.
—
🛠️  Built by:   Sherlock_MacGyver 
Feel free to share feedback or reach out if you'd like to collaborate on custom features.
Ensemble Consensus System
The Ensemble Consensus System (ECS) brings a **Random Forest-style ensemble vote** to Pine Script: five orthogonal "expert" strategies each cast a bull/bear vote (+1/-1/0), and only high-confidence consensus moves become signals—dramatically reducing noise while capturing strong directional moves.
## What Makes This Original
ECS is the first Pine Script indicator to implement true machine learning-style ensemble voting. Rather than relying on a single methodology, five independent experts analyze different market dimensions:
• **Trend Expert**: Multi-timeframe EMA alignment analysis
• **Momentum Expert**: RSI/MACD/Stochastic confluence with consistency filters  
• **Volume Expert**: Proprietary volume pressure + OBV confirmation
• **Volatility Expert**: Bollinger Band mean reversion opportunities
• **Structure Expert**: Adaptive pivot-based support/resistance detection
## How It Works
The system requires consensus among experts, with an **adaptive threshold** based on market volatility:
| Volatility Regime | ATR/Close | Votes Required |
|-------------------|-----------|----------------|
| Low Volatility    | <1%       | 2+             |
| Normal Markets    | 1-2%      | 3+             |
| High Volatility   | >2%       | 4+             |
This dynamic adjustment prevents overtrading in choppy conditions while maintaining responsiveness during strong trends.
## Key Features
### Signals
• **Visual entry points** with strength percentage (60% = 3/5 experts agree)
• **Adaptive thresholds** that adjust to market conditions
• **Multi-expert consensus** reduces false signals
### Risk Control  
• **Dynamic stop-loss/take-profit** based on ATR
• **Regime-adjusted targets** (±50% in volatile markets)
• **Visual SL/TP lines** with exact price labels
### Analytics
• **Real-time vote panel** showing each expert's stance
• **Performance tracking** with win rate and P/L
• **Market regime indicator** (Trending/Ranging/Volatile)
• **Light Mode** for better performance on slower systems
## How to Use
1. **Apply ECS** to a liquid instrument on 15m-4H timeframe (best: 1H)
2. **Wait for signal** - green ▲ for long, red ▼ for short with strength %
3. **Verify votes** - check panel to see which experts agree
4. **Execute trade** using the displayed SL/TP levels
5. **Monitor regime** - be cautious if market regime changes
### Quick Start Settings
• **Standard Trading**: Use defaults (3 votes, adaptive mode ON)
• **Conservative**: Increase to 4 votes minimum
• **Aggressive**: Reduce to 2 votes, tighten stops
## Important Limitations
• **Chart Types**: Not compatible with Renko/Heikin-Ashi
• **Volume Data**: Requires reliable volume (forex pairs may underperform)
• **News Events**: Signals may lag during gaps/major announcements
• **Processing**: Heavy calculations - use Light Mode if needed
## Settings Guide
**Ensemble Controls**
• `Minimum Votes` (default: 3): Base threshold before volatility adjustment
• `Adaptive Mode` (default: ON): Auto-adjusts threshold by market volatility
**Visual Options**  
• `Vote Panel`: Live expert voting display
• `Performance Stats`: Win rate and trade tracking
• `Light Mode`: Disables heavy visuals for speed
**Risk Parameters**
• `Stop Multiplier` (default: 2.0): ATR multiple for stop-loss
• `TP Multiplier` (default: 3.0): ATR multiple for take-profit
• `Dynamic TP` (default: ON): Adjusts targets by market regime
## Troubleshooting
**Too few signals?**
→ Lower minimum votes or check if market is ranging
**Indicator running slow?**
→ Enable Light Mode, disable performance tracking
**Weird volume votes?**
→ Verify your symbol has accurate volume data
## Technical Concepts
The ensemble approach mimics **Random Forest algorithms** where multiple decision trees vote on outcomes. By requiring agreement among experts using orthogonal methodologies, ECS filters out signals that would fail under different market lenses. The adaptive threshold addresses fixed-parameter weakness by dynamically adjusting selectivity based on volatility.
• Adaptive pivot lookback for dynamic structure detection
• Safe volume pressure calculation preventing division errors  
• Momentum consistency filter reducing choppy false signals
• Unified dashboard merging vote panel + performance stats
• Regime-based dynamic take-profit adjustment
*Educational indicator demonstrating ensemble methods in Pine Script. No guarantee of future performance. Always use proper risk management and position sizing.*
Bollinger Bands ETSOverview 
 Bollinger Bands ETstyle (BB ETS)  is an advanced volatility and breakout detection indicator, building upon the classic Bollinger Bands. This script introduces adaptive ATR-based band width smoothing and clear squeeze detection, making it a versatile tool for traders seeking more responsive and actionable volatility analysis.
 Features 
 Dual Bollinger Bands:  Plots both standard and outer bands around a configurable moving average, allowing visualization of typical and extreme volatility ranges.
 ATR-Based Band Smoothing (Optional):  When enabled, the bands automatically widen during low-volatility periods using the Average True Range (ATR), reducing false signals and making the bands more adaptive.
 Squeeze Detection (Optional):  Highlights periods when the bands contract below a user-defined threshold, signaling potential breakout setups. Squeeze periods are visually marked with a background highlight for easy identification.
 Customizable Settings:  Users can adjust band length, standard deviation multipliers, ATR parameters, and squeeze thresholds. Both ATR smoothing and squeeze detection can be toggled on or off.
 Clean Chart Output:  The indicator overlays directly on price with clear, distinguishable visuals for all features.
 How It Works 
The indicator calculates a moving average (basis) and plots upper and lower bands at user-selected standard deviations.
If ATR smoothing is enabled, the band width expands by a multiple of the ATR, adapting to real-time volatility.
The script computes the relative band width ("bandwidth"). When this falls below your chosen threshold, the background is highlighted to indicate a "squeeze"-a period of reduced volatility that often precedes breakouts.
 How to Use 
 Trend & Volatility Analysis:  Use the bands to identify overbought/oversold conditions and current market volatility. Price touching or crossing the outer bands may signal trend exhaustion or continuation.
 Breakout Anticipation:  Watch for background highlights indicating a squeeze. These periods suggest the market is coiling for a potential significant move.
 Adaptive Sensitivity:  Enable ATR smoothing to keep bands relevant during both calm and volatile markets, reducing false signals in low-volatility conditions.
 Customization:  Adjust all parameters in the settings to match your trading style and the asset’s behavior.
 Limitations 
The indicator is designed for standard price charts and may not perform as intended on non-standard chart types (such as Renko or Heikin Ashi).
As with all technical tools, best results are achieved when used alongside other forms of analysis.
 Summary 
 Bollinger Bands ETstyle (BB ETS)  offers a modern, adaptive approach to volatility and breakout analysis by combining classic bands with ATR-based smoothing and clear squeeze visualization. It is suitable for trend-following and breakout strategies, and requires no additional scripts-simply apply to your chart and adjust the settings as needed.






















