TradingView indicator calculations

Nadaraya-Watson envelopes: causal vs repainting scripts

A Nadaraya-Watson envelope places error-based bands around a kernel-weighted estimate of price. The decisive choice is whether each estimate uses only information available at that bar or is recalculated with later observations. A causal endpoint estimate can support reproducible close-based rules. A retrospective, two-sided fit can redraw earlier bands and cannot justify trades at those earlier timestamps. LuxAlgo offers both modes; check the author, version and Repainting Smoothing setting before interpreting a chart.

See the decision guide

Define the kernel and the envelope error

For an auditable Gaussian example, let P[t] be the close, N the trailing window, h a positive bandwidth in bars, M the error window and k a nonnegative band multiplier. The definitions below specify our demonstration variant. They do not claim that every script bearing the Nadaraya-Watson name uses the same error window, initialization or kernel.

  • The Gaussian normalization constant cancels in the ratio. Larger h spreads relative weight across more lags; N remains a separate truncation limit.
  • A[t] averages residuals against the center that was available at each earlier bar. Averaging all prices against the current center, or refitting old centers before measuring errors, gives a different band.
  • Require N valid closes for the first center and M valid residuals for the first envelope: N + M − 1 observations in total. Missing data makes the affected output unavailable; do not substitute zero.
  • Reject h ≤ 0, nonpositive window lengths and k < 0. A constant finite input produces zero error and coincident bands. A very small positive h approaches the current price; a very large h approaches equal weighting within N.
QuantityDefinition
Lag weightw[i] = exp(−i² / (2h²)), for i = 0, …, N − 1
Causal centerC[t] = Σ w[i]P[t−i] / Σ w[i]
Endpoint residuale[t] = |P[t] − C[t]|
Trailing absolute errorA[t] = (e[t] + … + e[t−M+1]) / M
EnvelopeLower[t] = C[t] − kA[t]; Upper[t] = C[t] + kA[t]

Compare causal and centered smoothing side by side

A retrospective fit at historical bar t can use G[t;T] = Σ K(t−j)P[j] / Σ K(t−j), where j runs over the fitted window available at review time T and K(d) = exp(−d²/(2h²)). Once T exceeds t, observations with j > t can enter. The kernel is centered on t, but a rolling window boundary may leave unequal data on its two sides.

  • A strictly symmetric fit with R observations to the right becomes available only after those R bars. Plotting it back at t is acceptable for analysis if the delay is disclosed; a trading decision belongs at its later availability time.
  • LuxAlgo describes default repainting smoothing and an optional endpoint mode. Its publication says crossing triangles can remain at their original location even when the recalculated envelope no longer shows the crossing. A persistent marker is therefore not proof that the current historical curve was available then.
PropertyCausal endpointRetrospective two-sided fit
Information at tCurrent and earlier observations onlyMay include observations that arrived after t
An old center after a new barUnchanged with fixed inputs and unchanged source dataCan change when the fit window changes
Unfinished current barCan move until its source close is confirmedCan move now and revise older points later
Error bandsUse residuals computed causally at their own timestampsRefitted residuals can also change the historical width
Backtest usePossible after specifying event and execution rulesDo not treat redrawn historical crossings as contemporaneous entries

Reproduce a four-price example

Use hypothetical consecutive closes P[0…3] = 100, 102, 104, 110 with N = 3, h = 1, M = 2 and k = 2. The lag weights are 1, 0.606530660 and 0.135335283. Calculations use full precision; displayed values are rounded to six decimals. No market or performance data is involved.

  • Before the fourth price exists, the estimate at t = 2 is 102.992803. Adding the future price with weight exp(−1/2) raises its retrospective estimate to 104.802582. The original causal C[2] remains 102.992803.
  • The price at t = 2 is 104. It is above the original center and below the refitted center. Even a simple price-above-center classification can change without any change to that historical price.
  • At t = 3 the close of 110 is inside the causal envelope. This is a position relative to the band, not a crossing event: under the full-window startup rule the prior envelope at t = 2 is unavailable.
CalculationResult
C[2] = (104 + 0.606530660×102 + 0.135335283×100) / 1.741865943102.992803
C[3] from prices 110, 104 and 102107.289191
e[2] and e[3]1.007197 and 2.710809
A[3] = (e[2] + e[3]) / 21.859003
Lower[3] and Upper[3]103.571184 and 111.007197
Refit t = 2 using all four prices, including future P[3] = 110G[2;3] = 104.802582

Record whether historical signals change

Use a screen recording to preserve what was visible before later bars arrived. This is a reproducible audit procedure, not a claim that a live recording was performed for this page. Run two copies of the same public indicator on one standard candlestick chart: repainting off in one, on in the other. Keep source, bandwidth and multiplier identical.

  • Start the recording by showing the exchange-qualified symbol, timeframe, session, script author/version and both settings panels. Record the timezone and visible bar timestamps.
  • At a completed bar, capture the close, center, upper and lower values wherever the script exposes numeric plots. Save the Data Window values in a timestamped ledger; some scripts draw lines without exposing every value there.
  • Keep the recording running across several new bars. Revisit the same closed timestamp and compare both modes. Track changes to the band separately from marker movement, disappearance or persistence.
  • Reload the chart and inspect the recorded timestamps again. Preserve the before and after images plus the alert log if an alert existed. An unchanged screenshot from one interval cannot prove that a script never repaints.
  • Bar Replay helps inspect bar-by-bar changes but does not reconstruct every live tick. Use forward recordings for claims about intrabar behavior. If source prices also changed after reload, investigate data revisions before attributing the difference to the kernel.
Record fieldWhat to preserve
IdentityScript version, mode, parameters, symbol, timeframe and session
Original observationBar timestamp, capture time, close, center, bands and marker state
Later observationSame bar timestamp, new capture time, values before and after reload
Event evidenceActual alert timestamp and condition; a reconstructed marker alone is insufficient

Separate band events from trading rules

For a causal close-based upper breakout, require the current close to exceed the current upper band and the previous close to be at or below the previous upper band, with both bands available. Returning inside from above uses the opposite inequalities. Those are different events; neither is a forecast of a reversal.

  • Evaluate the chosen condition at the chart bar close. Confirmation addresses the unfinished chart bar, but it cannot remove later observations from a retrospective fit.
  • Use a matching close frequency when creating a TradingView alert. TradingView saves the script and settings when the alert is created; recreate it after changing the mode or inputs.
  • A larger multiplier widens this defined envelope. It does not establish 95% coverage, a loss bound or a profitable mean-reversion rule. Strong trends can continue beyond a band.
  • Only test orders from values that were available at the decision time. Define fill timing, fees, slippage, exits and position sizing separately; a centered historical curve cannot supply missing live decisions.

Specify an inspectable Pineify implementation

Give the Pine Script AI Coding Agent the Gaussian equations, N/M/h/k inputs, full-window startup rule and missing-data behavior above. Ask it to draft a causal indicator with numeric center, residual and envelope outputs, then add the chosen confirmed-close event. Include the four-price fixture so the output can be checked before market use.

  • Review the generated source and syntax diagnostics. Compare each intermediate value against the fixture and then against the intended public TradingView implementation, using matching source and settings.
  • If the public script uses another error definition or initialization, document that difference instead of forcing its numbers to match this example. Enable alerts only after the values and timestamps agree with the intended specification.
  • Provide public formulas or code you have permission to use. The workflow does not recover protected source, and a successful syntax check does not establish causal behavior or trading performance.
Where Pineify fits

Pine Script AI Coding Agent

Draft or revise a causal kernel envelope from explicit formulas, startup rules and close conditions. Inspect the generated Pine source and compare numerical outputs in TradingView before creating alerts.

Draft a causal envelope

Frequently asked questions

Educational information, not investment advice. The numerical example is synthetic and is not a backtest or live result. An envelope crossing does not guarantee a reversal, profitable trade or limited loss.

Sources and verification

Published by Pineify. Pineify is an independent product and is not affiliated with TradingView. Sources support the technical explanations; examples do not establish trading performance.