OPEN-SOURCE SCRIPT

Zero Lag Kalman Structure [BOSWaves]

20 087
Zero Lag Kalman Structure [BOSWaves] - Adaptive Trend Filtering with Deviation-Based Structure Detection

Overview

Zero Lag Kalman Structure [BOSWaves] is a precision trend identification system that tracks directional price movement through a zero-lag-compensated Kalman filter ribbon, where deviation-based structural levels dynamically form at volatility-normalized extremes and persist as active support and resistance zones until price invalidates them.

スナップショット

Instead of relying on fixed moving average crossovers or static support/resistance lookbacks, trend state, level formation, and break detection are determined through Kalman velocity tracking, ATR-normalized deviation measurement, and swing-based structure identification.

This creates adaptive trend boundaries and structural zones that reflect actual price conviction rather than arbitrary historical levels - contracting the ribbon during trending conditions when directional certainty is high, forming fresh levels during deviation extremes when price has meaningfully separated from the Kalman baseline, and incorporating BOS/CHoCH detection to reveal whether market structure is continuing or reversing.

Price is therefore evaluated relative to a filter that adapts to momentum velocity rather than conventional lagging averages.

Conceptual Framework

Zero Lag Kalman Structure is founded on the principle that meaningful structural zones emerge when price deviates from its statistically optimal estimated path by a volatility-significant margin, and that trend context is best captured by a filter engineered to eliminate the lag inherent to traditional smoothing methods.

Conventional support/resistance tools identify levels through historical pivot lookbacks, which ignore the dynamic nature of price conviction and the statistical state of the current trend. This framework replaces static pivot logic with Kalman-anchored deviation measurement informed by actual filter velocity and error covariance state.

Three core principles guide the design:
  1. Trend direction should be captured by a velocity-aware Kalman filter with active lag compensation, not by lagging moving averages.
  2. Structural levels must form at statistically significant deviation extremes, normalized to current volatility rather than fixed price distances.
  3. Market structure breaks and character changes should be identified through swing-based logic tied to the same price data the filter operates on.

This shifts trend and structure analysis from static indicator crossovers into adaptive, filter-anchored confidence zones.

Theoretical Foundation

The indicator combines Kalman filter estimation theory, zero-lag error compensation, ATR-normalized deviation measurement, deviation zone persistence modeling, and swing pivot structure detection.

A Kalman filter baseline provides statistically optimal price estimation by balancing process noise and measurement noise parameters, while a velocity tracker within the filter captures directional momentum. Zero-lag compensation applies the residual error between current price and the filter estimate back onto the output, reducing phase delay. Deviation measurement identifies when price has separated from the filter by an ATR-scaled threshold, triggering level creation at the extreme point once price snaps back. BOS/CHoCH detection uses pivot highs and lows to identify structural breaks and character changes.

Four internal systems operate in tandem:
  • Kalman Filter Engine: Computes error-covariance-weighted price estimates with integrated velocity tracking, Kalman gain adaptation, and zero-lag correction applied to each bar.
  • Ribbon Construction System: Runs six parallel Kalman instances with incrementally increasing process noise to produce a multi-layered trend ribbon whose spread and color reflect directional strength.
  • Deviation Level Formation Logic: Monitors ATR-normalized distance from the Kalman estimate, records extreme highs and lows during deviation events, and creates persistent zone boxes upon mean reversion.
  • Market Structure Detection: Tracks swing pivot highs and lows using configurable lookback, identifies crossovers of those pivots, and classifies each break as either a BOS continuation or a CHoCH reversal depending on prior structural trend.

This design allows the trend filter, structural zones, and structure labels to operate as a unified system rather than independent overlapping indicators.

How It Works

Zero Lag Kalman Structure evaluates price through a sequence of filter-aware and deviation-driven processes:
  1. Kalman State Initialization: On the first bar, filter state initializes with estimate equal to source price, zero velocity, and unit error covariance to establish a clean starting condition.
  2. Prediction Step: Each bar predicts the next estimate by advancing the prior estimate by the velocity component weighted by the velocity weight parameter.
  3. Velocity Tracking: A separate exponential tracker computes price-change velocity using a 95/5 blend of decayed prior velocity and current bar price change.
  4. Kalman Gain Calculation: Gain is computed from current error covariance and measurement noise, controlling the balance between trusting the filter model versus reacting to new price data.
  5. Estimate Update: The filtered estimate updates using the Kalman gain applied to the innovation - the difference between current price and the predicted estimate.
  6. Zero-Lag Correction: Residual lag error between price and estimate is computed, then multiplied by the zero lag factor and current Kalman gain, and added back to the estimate to compress phase delay.
  7. Ribbon Smoothing: The zero-lag estimate passes through a 0.8/0.2 exponential blend each bar to produce the final ribbon line, providing continuity without reintroducing significant lag.
  8. Ribbon Color Gradient: The spread between the fastest and slowest ribbon lines is normalized by ATR to produce a ribbon strength value, which drives a color gradient between the configured bullish and bearish colors.
  9. Deviation Monitoring: Each bar, the distance between close and the main Kalman line is measured in ATR units. When this exceeds the deviation threshold, the system begins tracking the extreme high or low of that deviation event.
  10. Level Creation on Snap-Back: Once price returns inside 50% of the deviation threshold after an extended move, a new zone box is created centered on the tracked extreme, with width scaled to the level width ATR parameter.
  11. Level Management: Active levels extend forward each bar. Broken levels - where price closes beyond the zone boundary - are deleted. When the level count reaches the configured maximum, the oldest level is removed to make space.
  12. Retest Detection: Depending on the selected retest method, the system either monitors price interaction with zone boundaries or price proximity to the main Kalman line, applying cooldown periods to prevent signal clustering.
  13. BOS/CHoCH Detection: Pivot highs and lows are tracked using the swing lookback parameter. Crossovers of the most recent pivot high trigger bullish structural breaks, and crossunders of the most recent pivot low trigger bearish structural breaks. The prior structural trend determines whether each break is classified as continuation (BOS) or reversal (CHoCH).

Together, these elements form a continuously updating trend and structure framework anchored in Kalman estimation theory.

Interpretation

Zero Lag Kalman Structure should be interpreted as a filter-anchored trend state with deviation-driven structural memory:
  • Ribbon Direction: The relative positioning and color of the six-line ribbon communicates directional trend bias. Bullish gradient color with spread above zero reflects upward trend conviction; bearish gradient with inverted spread reflects downward conviction.
  • Ribbon Spread Width: A widening spread between the fastest and slowest Kalman lines indicates strong directional momentum. A compressing spread suggests trend deceleration or potential transition.
  • Resistance Zones (Red): Created at extreme highs where price deviated significantly above the Kalman line before snapping back, marking areas where price showed unsustainable separation to the upside.
  • Support Zones (Green): Created at extreme lows where price deviated significantly below the Kalman line before recovering, marking areas where price showed unsustainable separation to the downside.
  • Zone Persistence: Active zones extend forward until broken by a close beyond the zone boundary, treating them as live structural reference until price demonstrably invalidates them.
  • BOS Labels: Dashed lines with "BOS" text mark continuation breaks of prior swing structure in the direction of the established trend.
  • CHoCH Labels: Dotted lines with "CHoCH" text mark counter-trend breaks of prior swing structure, signaling potential trend character changes.
  • ▲ / ▼ Retest Signals: Small directional arrows identify price retesting either a deviation zone boundary or the main Kalman line, depending on the selected retest method.
  • Colored Candles: Bar coloring reflects the current ribbon gradient state for immediate directional reference across the entire chart history. Note: The original chart candles must be disabled in chart settings for the trend-colored candles to display properly.

Ribbon gradient strength, zone validity, and structural trend classification outweigh isolated price movements or individual bar reactions.

Signal Logic & Visual Cues

Zero Lag Kalman Structure presents two categories of structural interaction signals:
  1. BOS / CHoCH Events: Labeled lines appear when price crosses a tracked swing pivot. BOS signals continuation of existing structure; CHoCH signals the first counter-trend structural break, indicating potential trend change.
  2. Retest Signals (▲ / ▼): Arrows appear when price interacts with an active deviation zone boundary (Levels mode) or touches the main Kalman line after sufficient separation (Kalman Line mode), confirmed by cooldown period to prevent rapid repeat signals.

Alert generation covers deviation level creation, BOS and CHoCH events, Kalman line retests, and support/resistance level retests for systematic monitoring across instruments and timeframes.

Strategy Integration

Zero Lag Kalman Structure fits within structure-aware and trend-following analytical frameworks:
  • Filter-Confirmed Directional Bias: Use ribbon color and spread direction as the primary trend filter before evaluating entries, favoring positions aligned with ribbon gradient.
  • Deviation Zone Re-entries: Use active support and resistance zones as high-probability re-entry reference areas when price returns to a level from the correct side.
  • BOS/CHoCH Context Alignment: Treat BOS events as continuation confirmation within established trends; treat CHoCH events as early warning of structural regime change requiring reassessment.
  • Retest-Based Entries: Use Kalman line or zone retests as lower-risk entry points within an established trend after initial separation has confirmed directional conviction.
  • Zone Invalidation as Exit Logic: Use level deletion events - where price closes beyond a zone boundary - as structural evidence that the prior support or resistance thesis is no longer valid.
  • Multi-Timeframe Structure Layering: Apply higher-timeframe deviation zones and BOS/CHoCH context to filter lower-timeframe entry signals for improved precision.

Technical Implementation Details
  • Core Engine: Kalman filter with error covariance tracking, Kalman gain adaptation, and integrated velocity model
  • Lag Correction: Zero-lag factor applied multiplicatively with current Kalman gain to preserve filter responsiveness at the correction stage
  • Ribbon System: Six parallel Kalman instances with linearly incremented process noise, blended via gradient fill
  • Level Formation: ATR-normalized deviation threshold with extreme tracking, snap-back detection, and box-based zone persistence
  • Structure Detection: Pivot high/low crossover logic with trend state tracking for BOS/CHoCH classification
  • Retest Logic: Dual-mode detection supporting zone boundary interaction and Kalman proximity, each with configurable cooldown
  • Visualization: Gradient ribbon fills, persistent zone boxes, labeled structure lines, and signal arrows
  • Performance Profile: Optimized for real-time execution with per-bar level management across all timeframes

Optimal Application Parameters

Timeframe Guidance:
  • 1 - 5 min: Short-term structure tracking with responsive deviation settings for intraday scalping
  • 15 - 60 min: Intraday trend context with balanced deviation threshold and level persistence
  • 4H - Daily: Swing-level structure identification with ATR-normalized zones carrying multi-session significance

Suggested Baseline Configuration:
  • Process Noise (Q): 0.01
  • Measurement Noise (R): 0.5
  • Zero Lag Factor: 1.0
  • Velocity Weight: 0.5
  • Ribbon Spread: 0.003
  • Deviation Threshold (ATR): 1.5
  • Level Width (ATR): 0.25
  • Maximum Levels: 6
  • Level Extend Bars: 50
  • Swing Lookback: 5
  • Retest Method: Kalman Line
  • Retest Cooldown: 50
  • Show Ribbon: Enabled
  • Show Deviation Levels: Enabled
  • Show BOS / CHoCH: Enabled

These suggested parameters should be used as a baseline; their effectiveness depends on the asset's volatility profile, structural characteristics, and preferred signal frequency, so fine-tuning is expected for optimal performance.

Parameter Calibration Notes

Use the following adjustments to refine behavior without altering the core logic:
  • Filter too reactive to noise: Increase Measurement Noise (R) to make the Kalman gain more conservative and smooth the estimate more aggressively.
  • Filter too slow to respond: Increase Process Noise (Q) to allow faster adaptation to genuine price movements, or increase Zero Lag Factor to strengthen lag correction.
  • Levels forming too frequently: Increase Deviation Threshold to require greater ATR-normalized separation before a level is created.
  • Levels forming too rarely: Decrease Deviation Threshold to trigger level creation at more moderate deviations.
  • Zones too wide or too narrow: Adjust Level Width multiplier to scale zone thickness proportionally to current ATR.
  • Too many active levels cluttering the chart: Reduce Maximum Levels so older zones are removed sooner, keeping only the most recent structural reference.
  • BOS/CHoCH signals too frequent: Increase Swing Lookback to require more significant pivot formations before a structural break is recognized.
  • BOS/CHoCH signals too infrequent: Decrease Swing Lookback for faster swing detection and more responsive structural classification.
  • Retest signals clustering: Increase Retest Cooldown to enforce greater bar separation between consecutive retest events.

Adjustments should be incremental and evaluated across multiple session types rather than isolated market conditions.

Performance Characteristics

High Effectiveness:
  • Trending markets with clear directional phases where Kalman velocity remains consistently signed
  • Instruments with regular mean-reversion behavior where deviation extremes produce reliable structural zones
  • Swing and position trading approaches where BOS/CHoCH context informs multi-bar directional bias
  • Structure-based strategies that benefit from ATR-normalized level placement over fixed-point lookback methods

Reduced Effectiveness:
  • Choppy, range-bound markets with frequent shallow deviations that trigger premature level creation
  • Extremely low volatility environments where ATR normalization compresses zones to negligible significance
  • News-driven or gapped markets with discontinuous price behavior that bypasses zone boundaries without interaction
  • Markets with highly irregular volatility profiles where ATR scaling produces inconsistently sized zones
  • Consolidation and sideways price action where trend-following and structure-based methodologies inherently struggle due to lack of sustained directional conviction

Integration Guidelines
  • Confluence: Combine with volume analysis, higher-timeframe trend context, or momentum oscillators to confirm deviation zone significance
  • Ribbon Alignment: Trust structural breaks and retest signals occurring in the direction of the current ribbon color gradient
  • Zone Side Discipline: Treat deviation zones as directional only - approach support zones from above for bullish entries, resistance zones from below for bearish entries
  • CHoCH Awareness: Reduce directional exposure when CHoCH events occur against the prior established structural trend until a confirming BOS in the new direction appears
  • Velocity Respect: During periods of high Kalman velocity as reflected by wide ribbon spread, expect price to sustain moves further from the filter before meaningful retests occur
  • Level Invalidation Response: When a zone is broken, treat the break as structural confirmation of the new directional move rather than a retest opportunity

Disclaimer

Zero Lag Kalman Structure [BOSWaves] is a professional-grade trend filtering and structure analysis tool. It uses Kalman estimation theory with zero-lag compensation and ATR-normalized deviation measurement but does not predict future price movements. Results depend on market conditions, volatility characteristics, parameter selection, and disciplined execution. BOSWaves recommends deploying this indicator within a broader analytical framework that incorporates volume context, higher-timeframe bias, and comprehensive risk management.

免責事項

これらの情報および投稿は、TradingViewが提供または承認する金融、投資、取引、またはその他の種類の助言もしくは推奨であることを意図したものではなく、またこれらに該当するものでもありません。詳細は利用規約をご覧ください。