OPEN-SOURCE SCRIPT

Realtime Squeeze Box [CHE]

289
Realtime Squeeze Box [CHE] — Detects lowvolatility consolidation periods and draws trimmed price range boxes in realtime to highlight potential breakout setups without clutter from outliers.

Summary
This indicator identifies "squeeze" phases where recent price volatility falls below a dynamic baseline threshold, signaling potential energy buildup for directional moves. By requiring a minimum number of consecutive bars in squeeze, it reduces noise from fleeting dips, making signals more reliable than simple threshold crosses. The core innovation is realtime box visualization: during active squeezes, it builds and updates a box capturing the price range while ignoring extreme values via quantile trimming, providing a cleaner view of consolidation bounds. This differs from static volatility bands by focusing on trimmed ranges and suppressing overlapping boxes, which helps traders spot genuine setups amid choppy markets. Overall, it aids in anticipating breakouts by combining volatility filtering with visual containment of price action.

Motivation: Why this design?
Traders often face whipsaws during brief volatility lulls that mimic true consolidations, leading to premature entries, or miss setups because standard volatility measures lag in adapting to changing market regimes. This design addresses that by using a hold requirement on consecutive lowvolatility bars to denoise signals, ensuring only sustained squeezes trigger visuals. The core idea—comparing rolling standard deviation to a smoothed baseline—creates a responsive yet stable filter for lowenergy periods, while the trimmed box approach isolates the core price cluster, making it easier to gauge breakout potential without distortion from spikes.

What’s different vs. standard approaches?
Reference baseline: Traditional squeeze indicators like the Bollinger Band Squeeze or TTM Squeeze rely on fixed multiples of bands or momentum oscillators crossing zero, which can fire on isolated bars or ignore range compression nuances.
Architecture differences:
Realtime box construction that updates barbybar during squeezes, using arrays to track and trim price values.
Quantilebased outlier rejection to define box bounds, focusing on the bulk of prices rather than full range.
Overlap suppression logic that skips redundant boxes if the new range intersects heavily with the prior one.
Hold counter for consecutive bar validation, adding persistence before signaling.
Practical effect: Charts show fewer, more defined orange boxes encapsulating tight price action, with a horizontal line extension marking the midpoint postsqueeze—visibly reducing clutter in sideways markets and highlighting "coiled" ranges that standard plots might blur with full highs/lows. This matters for quicker visual scanning of multitimeframe setups, as boxes selflimit to recent history and avoid piling up.

How it works (technical)
The indicator starts by computing a rolling average and standard deviation over a userdefined length on the chosen source price series. This deviation measure is then smoothed into a baseline using either a simple or exponential average over a longer window, serving as a reference for normal volatility. A squeeze triggers when the current deviation dips below this baseline scaled by a multiplier less than one, but only after a minimum number of consecutive bars confirm it, which resets the counter on breaks.

Upon squeeze start, it clears a buffer and begins collecting source prices barbybar, limited to the first few bars to keep computation light. For visualization, if enabled, it sorts the buffer and finds a quantile threshold, then identifies the minimum value at or below that threshold to set upper and lower box bounds—effectively clamping the range to exclude tails above the quantile. The box draws from the start bar to the current one, updating its right edge and levels dynamically; if the new bounds overlap significantly with the last completed box, it suppresses drawing to avoid redundancy.

Once the hold limit or squeeze ends, the box freezes: its final bounds become the last reference, a midpoint line extends rightward from the end, and a tiny circle label marks the point. Buffers and states reset on new squeezes, with historical boxes and lines capped to prevent overload. All logic runs on every bar but uses confirmed historical data for calculations, with realtime updates only affecting the active box's position—no future peeking occurs. Initialization seeds with null values, building states progressively from the first bars.

Parameter Guide

Source: Selects the price series (e.g., close, hl2) for deviation and box building; influences sensitivity to wicks or bodies. Default: close. Tradeoffs/Tips: Use hl2 for balanced range view in volatile assets; stick to close for pure directional focus—test on your timeframe to avoid oversmoothing trends.

Length (Mean/SD): Sets window for average and deviation calculation; shorter values make detection quicker but noisier. Default: 20. Tradeoffs/Tips: Increase to 30+ for stability in higher timeframes, reducing false starts; below 10 risks overreacting to singlebar noise.

Baseline Length: Defines smoothing window for the deviation baseline; longer periods create a steadier reference, filtering regime shifts. Default: 50. Tradeoffs/Tips: Pair with Length at 1:2 ratio for calm markets; shorten to 30 if baselines lag during fast volatility drops, but watch for added whips.

Squeeze Multiplier (<1.0): Scales the baseline downward to set the squeeze threshold; lower values tighten criteria for rarer, stronger signals. Default: 0.8. Tradeoffs/Tips: Tighten to 0.6 for highvol assets like crypto to cut noise; loosen to 0.9 in forex for more frequent but shallower setups—balances hit rate vs. depth.

Baseline via EMA (instead of SMA): Switches baseline smoothing to exponential for faster adaptation to recent changes vs. equalweighted simple average. Default: false. Tradeoffs/Tips: Enable in trending markets for quicker baseline drops; disable for uniform history weighting in rangebound conditions to avoid overreacting.

SD: Sample (len1) instead of Population (len): Adjusts deviation formula to divide by length minus one for smallsample bias correction, slightly inflating values. Default: false. Tradeoffs/Tips: Use sample in short windows (<20) for more conservative thresholds; population suits long looks where bias is negligible, keeping signals tighter.

Min. Hold Bars in Squeeze: Requires this many consecutive squeeze bars before confirming; higher denoise but may clip early setups. Default: 1. Tradeoffs/Tips: Bump to 35 for intraday to filter ticks; keep at 1 for swings where quick consolidations matter—trades off timeliness for reliability.

Debug: Plot SD & Threshold: Toggles lines showing raw deviation and threshold for visual backtesting of squeeze logic. Default: false. Tradeoffs/Tips: Enable during tuning to eyeball crossovers; disable live to declutter—great for verifying multiplier impact without alerts.

Tint Bars when Squeeze Active: Overlays semitransparent color on bars during open box phases for quick squeeze spotting. Default: false. Tradeoffs/Tips: Pair with low opacity for subtlety; turn off if using boxes alone, as tint can obscure candlesticks in dense charts.

Tint Opacity (0..100): Controls background tint strength during active squeezes; higher values darken for emphasis. Default: 85. Tradeoffs/Tips: Dial to 60 for light touch; max at 100 risks hiding price action—adjust per chart theme for visibility.

Stored Price (during Squeeze): Price series captured in the buffer for box bounds; defaults to source but allows customization. Default: close. Tradeoffs/Tips: Switch to high/low for wider boxes in gappy markets; keep close for midline focus—impacts trim effectiveness on outliers.

Quantile q (0..1): Fraction of sorted prices below which tails are cut; higher q keeps more data but risks including spikes. Default: 0.718. Tradeoffs/Tips: Lower to 0.5 for aggressive trim in noisy assets; raise to 0.8 for fuller ranges—tune via debug to match your consolidation depth.

Box Fill Color: Sets interior shade of squeeze boxes; semitransparent for layering. Default: orange (80% trans.). Tradeoffs/Tips: Soften with more transparency in multiindicator setups; bold for standalone use—ensures boxes pop without overwhelming.

Box Border Color: Defines outline hue and solidity for box edges. Default: orange (0% trans.). Tradeoffs/Tips: Match fill for cohesion or contrast for edges; thin width keeps it clean—helps delineate bounds in zoomed views.

Keep Last N Boxes: Limits historical boxes/lines/labels to this count, deleting oldest for performance. Default: 10. Tradeoffs/Tips: Increase to 50 for weekly reviews; set to 0 for unlimited (risks lag)—balances history vs. speed on long charts.

Draw Box in Realtime (build/update): Enables live extension of boxes during squeezes vs. waiting for end. Default: true. Tradeoffs/Tips: Disable for confirmedonly views to mimic backtests; enable for proactive trading—adds minor repaint on live bars.

Box: Max First N Bars: Caps buffer collection to initial squeeze bars, freezing after for efficiency. Default: 15. Tradeoffs/Tips: Shorten to 510 for fast intraday; extend to 20 in dailies—prevents bloated arrays but may truncate long squeezes.

Reading & Interpretation
Squeeze phases appear as orange boxes encapsulating the trimmed price cluster during lowvolatility holds—narrow boxes signal tight consolidations, while wider ones indicate looser ranges within the threshold. The box's top and bottom represent the quantilecapped high and low of collected prices, with the interior fill shading the containment zone; ignore extremes outside for "true" bounds. Postsqueeze, a solid horizontal line extends right from the box's midpoint, acting as a reference level for potential breakout tests—drifting prices toward or away from it can hint at building momentum. Tiny orange circles at the line's start mark completion points for easy scanning. Debug lines (if on) show deviation hugging or crossing the threshold, confirming hold logic; a persistent hug below suggests prolonged calm, while spikes above reset counters.

Practical Workflows & Combinations
Trend following: Enter long on squeezeend close above the box top (or midpoint line) confirmed by higher high in structure; filter with rising 50period average to avoid countertrend traps. Use boxes as support/resistance proxies—short below bottom in downtrends.
Exits/Stops: Trail stops to the box midpoint during postsqueeze runs for conservative holds; go aggressive by exiting on retest of opposite box side. If debug shows repeated threshold grazes, tighten stops to curb drawdowns in ranging followups.
Multiasset/MultiTF: Defaults work across stocks, forex, and crypto on 15min+ frames; scale Length proportionally (e.g., x2 on hourly). Layer with highertimeframe boxes for confluence—e.g., daily squeeze + 1H box for entry timing. (Unknown/Optional: Specific multiTF scaling recipes beyond proportional adjustment.)

Behavior, Constraints & Performance
Repaint/confirmation: Core calculations use historical closes, confirming on bar close; active boxes repaint their right edge and levels live during squeezes if enabled, but freeze irrevocably on hold limit or end—mitigates via barbybar buffer adds without future leaks. No lookahead indexes.
security()/HTF: None used, so no external timeframe repaints; all native to chart resolution.
Resources: Caps at 300 boxes/lines/labels total; small arrays (up to 20 elements) and short loops in sorting/minfinding keep it light—suitable for 10k+ bar charts without throttling. Persistent variables track state across bars efficiently.
Known limits: May lag on ultrasharp volatility spikes due to baseline smoothing; gaps or thin markets can skew trims if buffer hits cap early; overlaps suppress visuals but might hide chained squeezes—(Unknown/Optional: Edge cases in nonstandard sessions).

Sensible Defaults & Quick Tuning
Start with defaults for most liquid assets on 1Hdaily: Length 20, Multiplier 0.8, Hold 1, Quantile 0.718—yields balanced detection without excess noise. For too many false starts (choppy charts), increase Hold to 3 and Baseline Length to 70 for stricter confirmation, reducing signals by 3050%. If squeezes feel sluggish or miss quick coils, shorten Length to 14 and enable EMA baseline for snappier adaptation, but monitor for added flips. In highvol environments like options, tighten Multiplier to 0.6 and Quantile to 0.6 to focus on core ranges; reverse for calm pairs by loosening to 0.95. Always backtest tweaks on your asset's history.

What this indicator is—and isn’t
This is a volatilityfiltered visualization tool for spotting and bounding consolidation phases, best as a signal layer atop price action and trend filters—not a standalone predictor of direction or strength. It highlights setups but ignores volume, momentum, or news context, so pair with discreteness rules like higher highs/lows. Never use it alone for entries; always layer risk management, such as 12% stops beyond box extremes, and position sizing based on account drawdown tolerance.

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 HeikinAshi, Renko, Kagi, PointandFigure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.

Best regards and happy trading

Chervolino

Aviso legal

As informações e publicações não devem ser e não constituem conselhos ou recomendações financeiras, de investimento, de negociação ou de qualquer outro tipo, fornecidas ou endossadas pela TradingView. Leia mais em Termos de uso.