OPEN-SOURCE SCRIPT
Mis à jour

Strata - Regime Segments & Volume Profile

362
This indicator segments price with a model-based online change detector, classifies every segment into a six-cell regime grid, and renders for each segment an exact regression line, a sigma channel, and a slanted volume profile. One standard runs everything: the segment is the state — there is no second bar-by-bar machine, no smoothing triggers, no dwell locks. The CUSUM cut threshold is the only persistence mechanism.

Detection. A Kalman local linear trend filter estimates a drifting level and a drifting slope, so a steady trend is what the model expects and trend drift is not mistaken for structural change. Each bar the filter emits the one-step innovation, standardized by its own recursively estimated variance. A two-sided CUSUM watches the standardized innovation mean; when it crosses the threshold the trend has structurally changed and a segment is cut, backdated to where the winning CUSUM run started, so the boundary lands where the change began rather than where it was detected. Cuts that would close a segment shorter than the minimum length are discarded and merged, so tiny fragments cannot exist. After an accepted cut the Kalman covariance is briefly inflated for faster re-adaptation. A second CUSUM on the innovation dispersion always runs and fires an alert on volatility shifts; a switch lets it cut segments too. The threshold h is derived from the data by default: you state the average segment length you want, and a feedback controller nudges h bar by bar until the realized average matches it — the panel shows the current h and the realized length so you can watch it converge. A fixed-h mode remains available; with the standard allowance k = 0.5, h = 4 corresponds to an average false-alarm interval of roughly 168 bars and h = 5 to roughly 465.

Classification. Direction is the segment's OLS slope per bar in units of the segment's mean daily sigma; below the dead zone in magnitude the segment is flat, so a violent sideways stretch is not forced into a bullish or bearish color. Tempo is the segment's mean volatility percentile against one threshold. The grid is direction times tempo: Up, Flat, Down crossed with Calm and Hot, six cells. Finalized segments get their one-shot call at the cut; the active segment is classified from its own tentative regression from birth, and the call may drift while the segment is young — that is accepted by design, since tentative regressions are tentative. A dashed vertical divider is drawn at every backdated cut and is the one authoritative boundary marker: between two dividers there is exactly one segment — one regression line, one profile, one state label. Labels and flat-state strokes adapt to the chart theme so they stay visible on light and dark backgrounds.

Volume profile. Volume is binned in residual space — by distance from the segment's regression line — and drawn as parallelogram bars running parallel to the channel, anchored to the segment's right edge and growing leftward, so a profile always butts against its own boundary. Bin width follows the Freedman–Diaconis rule with volume-weighted quantiles and the Kish effective sample size, with a fixed-bin fallback. The point of control and a seventy percent value area are drawn parallel to the fit. Profile bars use a direction-only palette, green up, red down, grey flat, with adjustable opacity. Segments too short to support a meaningful distribution simply skip the profile, and older segments are demoted to line plus POC to respect drawing limits.

Gauges. Pressure reads how close the active segment's readings sit to their classification boundaries, plus CUSUM cut progress when it opposes the current direction, normalized to a percentage with the implied target state. It is a gauge, not a calibrated probability — it catches gradual drifts only, and a cut can fire and reclassify from zero pressure. Hist. next reports the empirical next-state distribution from this chart's own transition history; the sample count is shown and should be read. Hidden data-window plots expose State, Direction, Tempo, and state age for use in the Pine Screener, and alerts cover segment cuts, volatility shifts, state changes, and every direction or tempo transition.

Scope. All decisions run on confirmed bars only: nothing repaints, finalized drawings are created once and never moved, and the active segment is the only mutable object. This is an online, causal detector — detection delay is irreducible for any causal method, and globally optimal offline methods such as PELT place breakpoints more accurately in hindsight. Treat segments, states, and gauges as context, not trade signals. The detection core is shared with the companion indicator "Strata Core"; keep the constants in sync if you run both. The presentation concept — per-segment regression channels and a trend-slanted volume profile — is inspired by "Dual Log Regression Channels" by BigBeluga and "Volume Cluster Profile (VCP)" by Zeiierman; the detection, classification, and estimation pipeline is an independent implementation of the methods below. Methods follow standard results in filtering, change-point detection, and density estimation (Kalman 1960; Harvey 1989; Page 1954; Moustakides 1986; Hinkley 1971; Lorden 1971; Mehra and Peschon 1971; Severo and Gama 2010; RiskMetrics 1996; Freedman and Diaconis 1981; Kish 1965; Maheu and McCurdy 2000; Ang and Timmermann 2012; Pagan and Sossounov 2003).
Notes de version
This indicator segments price with a model-based online change detector, classifies every segment into a six-cell regime grid, and renders for each segment an exact regression line, a sigma channel, and a slanted volume profile. One standard runs everything: the segment is the state — there is no second bar-by-bar machine, no smoothing triggers, no dwell locks. The CUSUM cut threshold is the only persistence mechanism.

Detection. A Kalman local linear trend filter estimates a drifting level and a drifting slope, so a steady trend is what the model expects and trend drift is not mistaken for structural change. Each bar the filter emits the one-step innovation, standardized by its own recursively estimated variance. A two-sided CUSUM watches the standardized innovation mean; when it crosses the threshold the trend has structurally changed and a segment is cut, backdated to where the winning CUSUM run started, so the boundary lands where the change began rather than where it was detected. Cuts that would close a segment shorter than the minimum length are discarded and merged, so tiny fragments cannot exist. After an accepted cut the Kalman covariance is briefly inflated for faster re-adaptation. A second CUSUM on the innovation dispersion always runs and fires an alert on volatility shifts; a switch lets it cut segments too. The threshold h is derived from the data by default: you state the average segment length you want, and a feedback controller nudges h bar by bar until the realized average matches it — the panel shows the current h and the realized length so you can watch it converge. A fixed-h mode remains available; with the standard allowance k = 0.5, h = 4 corresponds to an average false-alarm interval of roughly 168 bars and h = 5 to roughly 465.

Classification. Direction is the segment's OLS slope per bar in units of the segment's mean daily sigma; below the dead zone in magnitude the segment is flat, so a violent sideways stretch is not forced into a bullish or bearish color. Tempo is the segment's mean volatility percentile against one threshold. The grid is direction times tempo: Up, Flat, Down crossed with Calm and Hot, six cells. Finalized segments get their one-shot call at the cut; the active segment is classified from its own tentative regression from birth, and the call may drift while the segment is young — that is accepted by design, since tentative regressions are tentative. A dashed vertical divider is drawn at every backdated cut and is the one authoritative boundary marker: between two dividers there is exactly one segment — one regression line, one profile, one state label. Labels and flat-state strokes adapt to the chart theme so they stay visible on light and dark backgrounds.

Volume profile. Volume is binned in residual space — by distance from the segment's regression line — and drawn as parallelogram bars running parallel to the channel, anchored to the segment's right edge and growing leftward, so a profile always butts against its own boundary. Bin width follows the Freedman–Diaconis rule with volume-weighted quantiles and the Kish effective sample size, with a fixed-bin fallback. The point of control and a value area are drawn parallel to the fit, with the value area shaded between its edges; coverage defaults to the seventy percent Market Profile convention — itself a rounding of the Gaussian one-sigma 68.27% — and is configurable. Profile bars use a direction-only palette, green up, red down, grey flat, with adjustable opacity. Segments too short to support a meaningful distribution simply skip the profile, and older segments are demoted to line plus POC to respect drawing limits. The active segment carries tentative versions of all three — profile, point of control, and value area — rebuilt at each close and rendered one shade lighter until the segment is finalized.

Gauges. Pressure reads how close the active segment's readings sit to their classification boundaries, plus CUSUM cut progress when it opposes the current direction, normalized to a percentage with the implied target state. It is a gauge, not a calibrated probability — it catches gradual drifts only, and a cut can fire and reclassify from zero pressure. Hist. next reports the empirical next-state distribution from this chart's own transition history; the sample count is shown and should be read. Hidden data-window plots expose State, Direction, Tempo, and state age for use in the Pine Screener, and alerts cover segment cuts, volatility shifts, state changes, and every direction or tempo transition.

Scope. All decisions run on confirmed bars only: nothing repaints, finalized drawings are created once and never moved, and the active segment is the only mutable object. This is an online, causal detector — detection delay is irreducible for any causal method, and globally optimal offline methods such as PELT place breakpoints more accurately in hindsight. Treat segments, states, and gauges as context, not trade signals. The detection core is shared with the companion indicator "Strata Core"; keep the constants in sync if you run both. The presentation concept — per-segment regression channels and a trend-slanted volume profile — is inspired by "Dual Log Regression Channels" by BigBeluga and "Volume Cluster Profile (VCP)" by Zeiierman; the detection, classification, and estimation pipeline is an independent implementation of the methods below. Methods follow standard results in filtering, change-point detection, and density estimation (Kalman 1960; Harvey 1989; Page 1954; Moustakides 1986; Hinkley 1971; Lorden 1971; Mehra and Peschon 1971; Severo and Gama 2010; RiskMetrics 1996; Freedman and Diaconis 1981; Kish 1965; Maheu and McCurdy 2000; Ang and Timmermann 2012; Pagan and Sossounov 2003).
Notes de version
This indicator segments price with a model-based online change detector, classifies every segment into a six-cell regime grid, and renders for each segment an exact regression line, a sigma channel, and a slanted volume profile. One standard runs everything: the segment is the state — there is no second bar-by-bar machine, no smoothing triggers, no dwell locks. The CUSUM cut threshold is the only persistence mechanism.

Detection. A Kalman local linear trend filter estimates a drifting level and a drifting slope, so a steady trend is what the model expects and trend drift is not mistaken for structural change. Each bar the filter emits the one-step innovation, standardized by its own recursively estimated variance. A two-sided CUSUM watches the standardized innovation mean; when it crosses the threshold the trend has structurally changed and a segment is cut, backdated to where the winning CUSUM run started, so the boundary lands where the change began rather than where it was detected. Cuts that would close a segment shorter than the minimum length are discarded and merged, so tiny fragments cannot exist. After an accepted cut the Kalman covariance is briefly inflated for faster re-adaptation. A second CUSUM on the innovation dispersion always runs and fires an alert on volatility shifts; a switch lets it cut segments too. The threshold h is derived from the data by default: you state the average segment length you want, and a feedback controller nudges h bar by bar until the realized average matches it — the panel shows the current h and the realized length so you can watch it converge. A fixed-h mode remains available; with the standard allowance k = 0.5, h = 4 corresponds to an average false-alarm interval of roughly 168 bars and h = 5 to roughly 465.

Classification. Direction is the segment's OLS slope per bar in units of the segment's mean daily sigma; below the dead zone in magnitude the segment is flat, so a violent sideways stretch is not forced into a bullish or bearish color. Tempo is the segment's mean volatility percentile against one threshold. The grid is direction times tempo: Up, Flat, Down crossed with Calm and Hot, six cells. Finalized segments get their one-shot call at the cut; the active segment is classified from its own tentative regression from birth, and the call may drift while the segment is young — that is accepted by design, since tentative regressions are tentative. A dashed vertical divider is drawn at every backdated cut and is the one authoritative boundary marker: between two dividers there is exactly one segment — one regression line, one profile, one state label. Labels and flat-state strokes adapt to the chart theme so they stay visible on light and dark backgrounds.

Volume profile. Volume is binned in residual space — by distance from the segment's regression line — and drawn as parallelogram bars running parallel to the channel, anchored to the segment's right edge and growing leftward, so a profile always butts against its own boundary. Bin width follows the Freedman–Diaconis rule with volume-weighted quantiles and the Kish effective sample size, with a fixed-bin fallback. The point of control and a value area are drawn parallel to the fit, with the value area shaded between its edges; coverage defaults to the seventy percent Market Profile convention — itself a rounding of the Gaussian one-sigma 68.27% — and is configurable. Profile bars use a direction-only palette, green up, red down, grey flat, with adjustable opacity. Segments too short to support a meaningful distribution simply skip the profile, and older segments are demoted to line plus POC to respect drawing limits. The active segment carries tentative versions of all three — profile, point of control, and value area — rebuilt at each close and rendered one shade lighter until the segment is finalized. Grey dashed extensions project the tentative POC and value-area bounds forward to the estimated next cut: extrapolated from the CUSUM's recent climb when evidence is accumulating, and set to the realized mean segment length — the memoryless benchmark of geometric regime durations — when it is not. The projection is a gauge, not a promise; cuts can arrive without warning and are backdated when they do.

Gauges. Pressure reads how close the active segment's readings sit to their classification boundaries, plus CUSUM cut progress when it opposes the current direction, normalized to a percentage with the implied target state. It is a gauge, not a calibrated probability — it catches gradual drifts only, and a cut can fire and reclassify from zero pressure. Hist. next reports the empirical next-state distribution from this chart's own transition history; the sample count is shown and should be read. Hidden data-window plots expose State, Direction, Tempo, and state age for use in the Pine Screener, and alerts cover segment cuts, volatility shifts, state changes, and every direction or tempo transition.

Scope. All decisions run on confirmed bars only: nothing repaints, finalized drawings are created once and never moved, and the active segment is the only mutable object. This is an online, causal detector — detection delay is irreducible for any causal method, and globally optimal offline methods such as PELT place breakpoints more accurately in hindsight. Treat segments, states, and gauges as context, not trade signals. The detection core is shared with the companion indicator "Strata Core"; keep the constants in sync if you run both. The presentation concept — per-segment regression channels and a trend-slanted volume profile — is inspired by "Dual Log Regression Channels" by BigBeluga and "Volume Cluster Profile (VCP)" by Zeiierman; the detection, classification, and estimation pipeline is an independent implementation of the methods below. Methods follow standard results in filtering, change-point detection, and density estimation (Kalman 1960; Harvey 1989; Page 1954; Moustakides 1986; Hinkley 1971; Lorden 1971; Mehra and Peschon 1971; Severo and Gama 2010; RiskMetrics 1996; Freedman and Diaconis 1981; Kish 1965; Maheu and McCurdy 2000; Ang and Timmermann 2012; Pagan and Sossounov 2003).
Notes de version
Pine Screener support overhaul. Detection, classification, and all drawings are unchanged; this release expands and reorders the script's outputs for screener use, since the screener auto-adds a script's first ten plots as its default filter and column set and the first two alert conditions as ready-made filters.

The default ten columns now read: State, Dir, Tempo, State age, Segment length, Slope in sigma per bar, Slope annualized in percent, Vol percentile, Pressure, and Pressure target. This is enough to scan for fresh regime turns, for example State equals 4 with State age at most 5, or for imminent flips, for example Pressure at least 70 with its target state. Beyond the default ten, new manually addable columns cover cut and volatility-shift events with bars-since versions for recency filters, plus the historical next-state readings. Alert conditions were reordered so the two auto-added filters are Regime changed and Segment cut, and the diagnostic Kalman plot no longer occupies the first column slot.

One caveat: the screener computes on the last 500 bars only, while this script is path-dependent from its first bar, so the screener's State can differ from a chart loaded with longer history and the transition-matrix columns will be near empty there. For closer chart and screener agreement prefer fixed h with auto mode off. Delete and recreate existing chart alerts after updating.
Notes de version
Trend significance layer. Detection, classification, and all drawings are unchanged; this release adds a statistical significance reading for each segment's regression slope and marks it on the chart, in the status table, and in the Pine Screener.

The statistic. The slope's standard error is computed against random-walk noise rather than the classical iid-residual OLS formula, because regressing a random walk on time makes the classical t grow with sample size and declare trends on pure noise, the spurious-regression problem documented by Granger and Newbold 1974 and Phillips 1986. The reading is roughly the slope over sigma times the square root of bars over 1.2, with an absolute t of 2 as the approximate 95 percent two-sided line. A segment of length n can only clear it when its slope reading exceeds about 2.2 over the square root of n, so short segments will usually not qualify; that reflects how hard drift is to estimate, following Merton 1980, not a defect of the fit.

On the chart. A new toggle, on by default, marks directional segments that fail the test: their state label gets an ns suffix, their regression line renders dotted instead of solid, and the active segment's tentative line switches between dotted and solid live as its own t crosses the threshold. Hovering any state label shows the segment's exact t with a one-line interpretation. Flat segments are never marked, since a flat call claims no trend. Read dotted as trend and noise indistinguishable at this length, not as no trend.

In the Pine Screener. A Trend t-stat column joins the default ten, and the annualized-slope column moves beyond the ten where it remains manually addable, so you can scan for statistically clean trends, for example t at least 2 with Dir equal to 1. Two caveats: segment boundaries are CUSUM-selected exactly where movement happened, so absolute t levels read optimistic and cross-sectional ranking is the safer use; and volatility clustering makes the 2 threshold approximate.

Delete and recreate existing chart alerts after updating, since alerts are snapshots of the code and inputs at creation time.
Notes de version
Significance test hardened with a bar-count floor. Detection, classification, and all drawings are unchanged. A directional segment is now significant only when its slope clears an absolute t of 2 AND the segment spans at least twenty bars; previously only the t threshold applied.Why. The t standard error is a large-sample approximation, so a short but steep segment could clear t of 2 on what is really three or four points fitting a line by chance, with almost no residual degrees of freedom. Such segments were being marked significant and were passing screener scans for t at or above 2. The floor removes them. It is set to the larger of the minimum segment length and twenty, so lowering the segment-length input for finer detection can never drag the significance test below twenty bars.What changed. On the chart, directional segments below the floor now get the ns suffix and a dotted regression line even when their t reads above 2, and a hovered state label reports the segment's bar count and whether it failed on significance or on too few bars. In the Pine Screener, the Trend t-stat column is blank for segments below the floor, so a scan for t at or above 2 no longer returns short steep segments. Flat segments remain unmarked, and segments already longer than twenty bars are unaffected.Delete and recreate existing chart alerts after updating, since alerts are snapshots of the code and inputs at creation time.
Notes de version
Trend-reality tests replace the slope-t significance rule. The previous release judged a segment's trend with a single random-walk-adjusted slope t-statistic. This release replaces that with two independent statistical tests that must BOTH pass for a segment to count as a real trend, directly testing "trend versus random walk" rather than "is the slope non-zero".

The two tests. First, the Lo-MacKinlay variance ratio (1988), heteroskedasticity-robust z: under a random walk the variance of q-period returns equals q times the one-period variance, so a significant z means genuine directional persistence rather than noise. Second, a constant-plus-trend Augmented Dickey-Fuller unit-root test (Dickey and Fuller 1979; MacKinnon 1996): rejecting the unit root means the segment is trend-stationary rather than a random walk. The ADF regression, including its lagged-difference terms, is solved by the normal equations via matrix inversion, with critical values from MacKinnon's response surface adjusted for each segment's length. A segment is a confirmed real trend only when both tests pass.

On the chart. Directional state labels now carry a two-letter badge: V for the variance ratio, A for ADF, each followed by plus for pass, minus for fail, or question mark when the segment is too short to test. Only a V-plus-A-plus segment is a confirmed real trend, drawn with a solid regression line; everything else is drawn dotted. The active, still-forming segment now shows its own live badge with a trailing asterisk, updated each close, which is tentative and can change as the segment grows. Hover any state label for the exact test values.

In the Pine Screener. Two new columns join the defaults: the variance-ratio z, and ADF-minus-critical (negative means trend-stationary). To scan for real uptrends, combine Dir equal to 1 with variance-ratio z at or above 1.96 and ADF-minus-critical at or below 0. Because these statistics are measured on CUSUM-selected segments and read optimistic, cross-sectional ranking is the safer use: filter Dir equal to 1, then sort by variance-ratio z, rather than trusting an absolute threshold. Expect few matches under the strict double filter, that is the point.

Also in this release. The auto-h watchdog has been removed, restoring the CUSUM threshold as the one and only persistence mechanism, with no time-based or dwell-based intervention. On a chart that never cuts, auto-h now stays at its starting value; use a lower fixed h there. No changes to detection, classification, volume profiles, or existing alerts. Delete and recreate existing chart alerts after updating, since alerts are snapshots of the code and inputs at creation time.
Notes de version
Major update: the segmentation engine is now Bayesian Online Changepoint Detection (BOCPD).
What changed. The engine that splits price into regime segments was a two-sided CUSUM on the Kalman innovation. It is now Bayesian Online Changepoint Detection (Adams and MacKay 2007). Each bar updates a truncated run-length posterior with a Normal-Inverse-Gamma, Student-t predictive over the standardized innovation. A changepoint is declared when the most-probable run length collapses -- it climbed above a floor, then dropped back toward zero. This is the reliable BOCPD signal; the raw changepoint probability is not used, because it is structurally pinned near the hazard rate and does not respond to real changes. Cuts are backdated by the run length, short segments still merge, and every downstream layer -- per-segment regression, the six-cell classification, volume profiles, the variance-ratio and ADF trend tests, and all drawings -- is unchanged. Only where the segment boundaries come from has changed.
Tuning. The main dial is the hazard, the prior mean regime length (default 100): lower it to segment more finely, raise it to segment more conservatively. Two thresholds define the changepoint (MAP run length climbs above the first, then drops below the second); the defaults are self-consistent with the minimum segment length and are best left alone unless you observe a specific problem. What to expect: BOCPD responds sharply to direction reversals but is, by design, less sensitive to gentle trend-to-range transitions, so its segment boundaries can differ from the old CUSUM ones.
New: active-segment confidence. The forming segment's label now carries a 0-100 confidence score, with a matching Pine Screener column. It combines two readings from the run-length posterior: concentration (how sure the model is which regime the current bar belongs to) and distance from a changepoint (the score is discounted if the most-probable run length has slipped toward the collapse threshold, meaning a change may be near). Read it as a slowly varying gauge, not an on/off signal -- what matters is its level and, especially, when it falls, which flags that confidence in the current segmentation is weakening. Active segment only.
Removed with the CUSUM engine. The variance-shift CUSUM (and its volatility-shift alerts), the auto-h controller and all h-threshold inputs, and the segmentation-robustness shadow CUSUMs are gone. The pressure gauge no longer includes a cut-progress term. Delete and recreate existing chart alerts after updating, since alerts are snapshots of the code and inputs at creation time.

Clause de non-responsabilité

Les informations et publications ne sont pas destinées à être, et ne constituent pas, des conseils ou recommandations financiers, d'investissement, de trading ou autres fournis ou approuvés par TradingView. Pour en savoir plus, consultez les Conditions d'utilisation.