OPEN-SOURCE SCRIPT
Aggiornato Daily Deviation Range and Gap Stats - NikaQuant

## What It Does
This indicator projects six pairs of deviation levels above and below a defined session range, draws a daily gap line at a configurable time, and shows a live stats panel with historical hit rates, mean-revert rates, gap fill statistics, and trade-decision suggestions.
The range itself is captured as the high and low of 5-minute closes during a configurable New York time window (default 19:30 to 20:30 NY). Once the window closes, the range is locked and six fibonacci-style deviation levels at multiples 1, 2.5, 5, 8, 13, and 19 of the range size are projected forward both upward and downward across the next trading day until a configurable cutoff (default 16:00 NY next day).
A separate gap line is captured at a configurable time (default 15:55 NY) using the close of that 5-minute bar. The gap line extends visually across the overnight session and is monitored for fill during the next session's open-to-close window (default 09:30 to 16:00 NY). When price crosses the gap level inside that window, the line is locked at the fill bar.
A live statistics table aggregates historical performance per day for the lookback period, showing per-level touch frequencies, mean-revert frequencies, close-inside-level frequencies, and gap fill statistics, then turns these into actionable trade-setup suggestions.
## Why It Is Original
Unlike a standard pivots or fibonacci-retracement indicator, this script is not a static price-level projection. It is a session-range deviation framework combined with an integrated gap tracker and a per-level historical statistics engine.
This script combines three distinct functional modules because each one addresses a different question about session structure:
(1) The range-multiple deviation levels answer "how far has price moved from session balance, in units of session range?" — analogous to standard-deviation channels but anchored to a user-defined range window rather than a rolling average.
(2) The daily gap line answers "is there an unfilled overnight reference price and what is the historical edge of trading toward it?" — different from standard gap detectors that only flag open-to-close gaps because it captures a specific price (the close at gap-time) and tracks fill behaviour inside a defined session window.
(3) The historical statistics engine answers "given today's structure, what has actually happened on past days when price reached the same levels or when a gap was open at this distance?" — turning the visual levels into probability-weighted decision inputs rather than just lines on a chart.
Together, the three modules produce something none of them would alone: a session-relative deviation map with quantified historical edge per level, plus a context-aware trade decision suggestion that combines current position, time remaining in the session, and historical revert behaviour.
The script also enforces a strict 5-minute internal data resolution regardless of chart timeframe (1-minute through 1-hour), so the levels and gap stay consistent whether the user is on a 5m chart or a 1H chart. This is accomplished via a dual-path data fetch that adapts to the chart's timeframe — pulling individual 5-minute samples on lower-timeframe charts and aggregating 5-minute closes per chart bar on higher-timeframe charts.
## How It Works
On each chart bar the script collects the 5-minute bars that have closed since the last update. For each 5-minute bar it checks whether the bar falls inside the range window, the extension window, the gap trigger time, or the gap fill window, and updates the relevant state.
When a 5-minute bar marks the end of the range window, the script locks in the highest and lowest 5-minute closes of the window, computes the range size and midline, and draws the deviation levels at multiples of the range above the high and below the low, projected forward to the configured extension-end time. A range-outline box is drawn over the range window for visual reference.
When a 5-minute bar matches the gap-trigger time, the script captures that bar's close as the gap price and starts drawing a horizontal line. On every subsequent 5-minute bar inside the next session's gap-fill window, the script checks whether the bar's high-low straddles the gap price. If so, the line is locked and the gap is recorded as filled.
Every time a deviation level is touched intraday — the 5-minute high reaches an upper level or the 5-minute low reaches a lower level — the script records that touch for the day. If price subsequently revisits the midline before the extension window ends, all touched levels for that day are also recorded as having reverted. When the extension window ends, the day's data is appended to a rolling history.
Each day's gap statistics (occurred, filled, minutes from fill-window open to fill) are appended at the next gap trigger, which ensures the gap is paired with its complete fill outcome before the next gap overwrites the live tracking state.
The stats table reads the history and renders per-level touch frequency, per-level revert frequency, close-inside-level frequency, gap fill rate, gap fill-time distribution (average, median, percent filled within 1 hour, percent filled within 4 hours), daily directional bias, range expansion vs contraction regime, day-type classification, time-elapsed in the active extension, and a context-aware trade-setup suggestion with stop and target prices for active fade setups.
The setup engine includes a time-remaining guard: when fewer minutes remain in the extension than the configured threshold, time-sensitive setups (fades and gap targets) are suppressed and the panel shows a "late session" status instead.
## How To Use It
- A range outline box appears over the range window once the window closes — this is the visual reference for the session range.
- Six pairs of lines extend forward from range-end to extension-end at multiples 1, 2.5, 5, 8, 13, and 19 of the range above and below the range high and low.
- Numerical labels at each level show the multiple — labels can be placed at the left or right end of the line via the "Level Label Side" setting.
- The gap line appears horizontally at the gap price after the configured gap time and extends until either price crosses through it during the fill window or the next day's gap is set.
- The live stats panel shows current price location vs midline (in range-multiples), today's range vs historical average, the current zone between two adjacent levels, the furthest level tagged today, per-level historical touch and revert rates, gap fill statistics, and a live setup suggestion.
Recommended timeframes: 1-minute through 1-hour. The script always uses 5-minute data internally, so behavior is consistent across chart timeframes.
Recommended markets: 24-hour markets such as index futures (ES, NQ), major FX pairs, and crypto majors, where overnight session structure matters and the configured NY-time windows align with meaningful session boundaries.
Avoid using when: less than 30 sessions of chart history are loaded (statistics will be unreliable) or on instruments that close before the configured range window (the range simply will not populate).
## Settings
- Max Deviation Days (default 11): how many past days to keep deviation levels visible. Older days are removed automatically.
- Show Deviation Levels: toggle the level lines.
- Normalize Range Size: when on, the range box and level distances use the average range over N past days instead of today's actual range.
- Normalize over N Days (default 500): number of past days to average for the normalization.
- Range Start and End Hour and Minute (default 19:30 to 20:30 NY): the window during which the range is captured.
- Extension Start and End Hour and Minute (default 20:30 to 16:00 NY next day): the window during which the deviation levels are drawn forward.
- Show Gap Level: toggle the gap line.
- Max Gap Days (default 11): number of past gap lines to keep visible.
- Gap Time Hour and Minute (default 15:55 NY): the 5-minute bar whose close becomes the gap price.
- Gap Close Start and End Hour and Minute (default 09:30 to 16:00 NY next day): the window during which gap fill is detected.
- Show Range Outline (default on): toggle the range outline box.
- Range Outline Color, Width, Style, Fill Transparency: visual settings for the box.
- Gap Width, Style, Color: visual settings for the gap line.
- Levels Width, Style: visual settings for the deviation lines.
- Level 1 through Level 6 (defaults 1, 2.5, 5, 8, 13, 19): numeric multiples of the range used for each level pair.
- Level 1 to 6 Color: per-level color.
- Level Label Side (default Left): place the level number labels at the left or right end of each line.
- Font Size (default 9): label font size.
- Show Stats Table (default on): toggle the live statistics panel.
- Stats Lookback in Days (default 5000): number of past completed days to include in historical statistics. Higher means more reliable percentages but requires more chart history loaded.
- Min Revert Percent for Fade Setup (default 55): a FADE setup is suggested only if the historical mean-revert rate at the touched level is at or above this threshold and the level was tagged at least 3 times in the lookback.
- Min Remaining Minutes for Setup (default 60): suppresses time-sensitive setups when fewer than this many minutes remain in the extension. Set to 0 to disable.
- Table Position (default Top Right): where the stats table is anchored.
- Table Size (default Normal): text size inside the stats table.
- Bull / Setup Color, Bear / Warning Color, Table Background, Table Text, Table Border: color settings for the panel.
## Alerts
Five alert conditions are exposed and can be selected from TradingView's "Add Alert" dialog:
- Range Locked: fires when the range window closes and the levels are projected.
- Level Tagged: fires the first time price reaches any deviation level on either side.
- Gap Set: fires when the daily gap level is captured.
- Gap Filled: fires when price crosses through an open gap during the fill window.
- Session End: fires when the extension window ends and stats are finalized.
## Notes
The script does not repaint after a 5-minute bar closes. The range, deviation levels, and gap line are drawn from confirmed data only. The live distance-from-midline and live setup suggestions update intrabar based on current price.
Future bar-index positions for projected lines and labels are estimated based on the chart timeframe's bar duration. On charts with weekend gaps the projected end positions may visually diverge from the configured extension-end time by a small amount, but the underlying logical end time is correct.
Note di rilascio
Version 1.10 — Line extension fixFixed
Deviation levels and range extension lines now project fully to the extension-end time (default 16:00 NY next day) the moment the range window closes, instead of slowly growing across the session.
What you would have seen before:
When the range window closed at 20:30 NY, the six pairs of deviation levels appeared only as a tiny stub right at the edge of the range box. Over the next ~19 hours the lines gradually extended forward one chart bar at a time, only reaching their intended 16:00 NY termination point right before the extension window ended. This made the levels visually useless for most of the session — you couldn't see where a level would sit later in the day until much later in the day.
What you will see now:
The moment the range closes, all twelve deviation levels and the midline are drawn in full — extending immediately to the configured extension-end time (default 16:00 NY the next day). The levels are usable as forward-looking reference prices from the second the range locks.
Under the hood (for the technically curious):
The line-end position was being overwritten on every bar with the current bar index, clipping the forward projection to "now" instead of anchoring it at the extension-end time. Every bar now re-projects the line end based on remaining time until extension-end, so the lines stay pinned to the correct future chart bar across the full session — including across weekend gaps where applicable.
No input changes. No behavior changes to the gap line, the range box, the statistics table, the alerts, or the trade decision engine. This is a pure visual correctness fix for the deviation levels.
Script open-source
Nello spirito di TradingView, l'autore di questo script lo ha reso open source, in modo che i trader possano esaminarne e verificarne la funzionalità. Complimenti all'autore! Sebbene sia possibile utilizzarlo gratuitamente, ricordiamo che la ripubblicazione del codice è soggetta al nostro Regolamento.
Declinazione di responsabilità
Le informazioni e le pubblicazioni non sono intese come, e non costituiscono, consulenza o raccomandazioni finanziarie, di investimento, di trading o di altro tipo fornite o approvate da TradingView. Per ulteriori informazioni, consultare i Termini di utilizzo.
Script open-source
Nello spirito di TradingView, l'autore di questo script lo ha reso open source, in modo che i trader possano esaminarne e verificarne la funzionalità. Complimenti all'autore! Sebbene sia possibile utilizzarlo gratuitamente, ricordiamo che la ripubblicazione del codice è soggetta al nostro Regolamento.
Declinazione di responsabilità
Le informazioni e le pubblicazioni non sono intese come, e non costituiscono, consulenza o raccomandazioni finanziarie, di investimento, di trading o di altro tipo fornite o approvate da TradingView. Per ulteriori informazioni, consultare i Termini di utilizzo.