OPEN-SOURCE SCRIPT
Aktualisiert

BayesStack RSI [CHE]

330
BayesStack RSI [CHE] — 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.
Versionshinweise
delete command

Haftungsausschluss

Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.