PROTECTED SOURCE SCRIPT
更新済

Kalman Trend Sniper

930
# KALMAN TREND SNIPER

## ORIGINALITY STATEMENT

The Kalman Trend Sniper combines adaptive trend detection with precision entry validation to identify high-probability trading opportunities. Unlike static moving averages that use fixed parameters, this indicator adapts to changing market volatility through ATR-based gain adjustment and distinguishes trending from ranging markets using ADX regime detection.

The indicator's unique contribution is its three-phase entry validation system: signals must hold for three bars, undergo a pullback test to the signal level, and receive confirmation through price action before generating an entry. This structured approach helps traders enter established trends at favorable retracement levels rather than chasing momentum.

---

## TECHNICAL METHODOLOGY

### Kalman Filter Implementation

This indicator implements an Alpha-Beta variant of the Kalman filter, a recursive algorithm that estimates trend from noisy price data:

1. Prediction: kf = kf + velocity
2. Error calculation: error = price - kf
3. Correction: kf = kf + gain * error
4. Velocity update: velocity = velocity + (gain * error) / 2

The gain parameter determines filter responsiveness. Higher gain values track price more closely but increase noise sensitivity, while lower values provide smoother output but lag price changes.

### Adaptive Gain Mechanism

The indicator adjusts gain dynamically based on volatility:

Volatility Factor = Current ATR / Long-term ATR
Adaptive Gain = Base Gain * (0.7 + 0.6 * Volatility Factor)

This ATR ratio increases responsiveness during high-volatility periods and reduces sensitivity during consolidations, addressing the fixed-parameter limitation of traditional moving averages. The volatility factor is bounded between configurable minimum and maximum values to prevent extreme adjustments.

### Regime Detection

The indicator uses the Average Directional Index (ADX) to distinguish market conditions:

- Trending markets (ADX above threshold): Full gain applied, signals generated
- Ranging markets (ADX below threshold): Gain reduced 25%, fewer signals

This regime awareness helps reduce whipsaw signals during sideways consolidation periods.

### Signal Line Validation System

When the Kalman line changes direction in trending conditions, the indicator draws a horizontal signal line at the low (for long signals) or high (for short signals) of the signal candle. This line represents a potential support or resistance level.

The validation system then monitors three phases:

Phase 1 - Hold Period: Price must remain above (long) or below (short) the signal line for three consecutive bars. This requirement filters weak signals where price immediately violates the signal level.

Phase 2 - Test: After the hold period, the system waits for price to pull back and touch the signal line, with configurable tolerance for volatile instruments.

Phase 3 - Confirmation: Within eight bars of the test, a confirmation candle must close above (long) or below (short) the test candle's body, demonstrating renewed momentum. If confirmation does not occur within eight bars, the validation attempt expires.

Successful validation generates an R label at the entry point. This three-phase structure helps identify entries where trend direction and support/resistance validation align.

---

## USAGE INSTRUCTIONS

### Signal Interpretation

Triangle Signals:
- Upward triangle (teal): Kalman line turns bullish in trending market (ADX above threshold)
- Downward triangle (red): Kalman line turns bearish in trending market

Signal Lines (horizontal):
- Teal line: Potential long support level at signal candle low
- Red line: Potential short resistance level at signal candle high
- Gray line: First opposite-color candle after signal (initial reversal pressure)

R Labels (optional, disabled by default):
- Green R below price: Validation complete for long entry
- Red R above price: Validation complete for short entry

Stop Levels:
- Red dots: Long stop level (Kalman line minus ATR multiplier)
- Teal dots: Short stop level (Kalman line plus ATR multiplier)

### Dashboard Information

The dashboard displays real-time indicator state:

- Trend: Current Kalman direction (BULL/BEAR)
- Regime: Market classification (Trending when ADX exceeds threshold, Ranging otherwise)
- Gain: Current adaptive gain value
- Vol Factor: Volatility ratio (current ATR / long-term ATR)
- ADX: Trend strength (higher values indicate stronger trends)
- Z-Score: Standard deviation distance from Kalman line (when enabled)
- Stop Dist: Current ATR-based stop distance
- Lines: Number of active signal lines displayed
- R-Status: Validation system state (Idle / Waiting / Testing)

### Trading Applications

Trend Following Approach:
1. Wait for triangle signal in trending market (ADX above threshold)
2. Enter immediately at signal candle close or wait for pullback
3. Place stop at displayed stop level
4. Trail stop using Kalman line as dynamic support/resistance

Validation Entry Approach (conservative):
1. After triangle signal, observe three-bar hold period
2. Wait for pullback to signal line (test phase)
3. Enter on R label confirmation
4. Place stop below/above signal line
5. Provides higher probability entries but reduces trade frequency

Z-Score Mean Reversion (when enabled):
1. Watch for Z-Score exceeding entry threshold (default +/-2.0)
2. Consider counter-trend entries when price touches Kalman line
3. Target return to Kalman line (Z-Score near zero)
4. Use Z-Score threshold as stop level for extreme continuation

### Optimal Conditions

The indicator performs optimally in clearly trending markets where ADX consistently exceeds the threshold. Performance degrades in sideways, choppy conditions.

Recommended timeframes:
- 1-5 minute charts: Use Crypto_1M preset (faster adaptation)
- 15-60 minute charts: Use Crypto_15M preset (balanced)
- Hourly charts: Use Forex preset (smoother)
- Daily charts: Use Stocks_Daily preset (long-term trends)

Market conditions:
- High volatility (Vol Factor above 1.5): Expect faster adaptation, wider stops needed
- Normal volatility (Vol Factor 0.7-1.5): Standard behavior
- Low volatility (Vol Factor below 0.7): Expect slower adaptation, tighter stops possible

---

## PARAMETER DOCUMENTATION

### Kalman Filter Settings

Preset Mode: Select optimized configuration for specific markets
- Custom: Manual parameter control
- Crypto_1M: Base Gain 0.05, ATR 7 (fast response for 1-5 minute crypto charts)
- Crypto_15M: Base Gain 0.03, ATR 14 (balanced for 15-60 minute crypto charts)
- Forex: Base Gain 0.02, ATR 14 (standard for forex pairs)
- Stocks_Daily: Base Gain 0.01, ATR 20 (smooth for daily stock charts)

Base Gain (0.001-0.2): Core Kalman filter responsiveness parameter. Higher values increase sensitivity to price changes. Low values (0.01-0.02) provide smooth output with fewer whipsaws but slower trend changes. High values (0.06-0.08) offer fast response with more signals but increased whipsaw risk.

Adaptive (checkbox): When enabled, automatically adjusts gain based on ATR ratio. Recommended to keep enabled for dynamic volatility adaptation.

ATR (5-50): Short-term Average True Range period for current volatility measurement. Default 14 is industry standard. Lower values respond faster to volatility changes.

Long ATR (20-200): Long-term ATR period for baseline volatility comparison. Default 50 provides stable reference. The ratio between ATR and Long ATR determines adaptive adjustment magnitude.

Regime Filter (checkbox): Enables ADX-based trending/ranging detection. When enabled, reduces gain by 25 percent during ranging markets to minimize false signals.

ADX Period (7-30): Period for ADX calculation. Default 14 is standard. Lower values respond faster to trend strength changes.

Threshold (15-40): ADX level distinguishing trending from ranging markets. Default 25. Above threshold: trending (generate signals normally). Below threshold: ranging (reduce sensitivity).

Min Vol / Max Vol (0.3-3.0): Bounds for volatility factor adjustment. Prevents extreme gain changes during unusual volatility spikes or quiet periods. Default minimum 0.5, maximum 2.0.

Stop ATR x (1.0-3.0): Multiplier for ATR-based stop loss distance. Default 2.0 places stops two ATRs from Kalman line. Use 1.5 for tight stops (intraday), 2.5-3.0 for wide stops (swing trading).

Show Signals (checkbox): Displays triangle signals when Kalman changes direction in trending markets. Disable to use indicator purely as dynamic support/resistance without signals.

Z-Score (checkbox): Enables mean-reversion signal generation based on statistical deviation from Kalman line.

Period (10-100): Lookback period for Z-Score standard deviation calculation. Default 20 bars. Longer periods produce smoother, less sensitive readings.

Entry (1.5-3.5): Standard deviation threshold for Z-Score signals. Default 2.0 generates signals at plus/minus two standard deviations (approximately 95th percentile moves).

Bull / Bear Colors: Customize Kalman line colors for uptrend (default teal) and downtrend (default red).

Fill (checkbox): Shows semi-transparent fill between price and Kalman line for visual trend emphasis.

### Signal Line System Settings

Signal Lines (checkbox): Displays horizontal signal lines at low (long) or high (short) of signal candles. These function as dynamic support/resistance levels.

Reverse Lines (checkbox): Shows gray horizontal lines at first opposite-colored candle after signal. Helps identify initial resistance points in new trends.

Max Lines (0-20): Maximum number of signal lines to display simultaneously. Older lines are removed as new signals appear. Use 1-2 for clean charts, 3-5 for recent support/resistance history.

Style (Solid/Dotted/Dashed): Visual style for signal and reverse lines. Dotted provides subtle appearance, solid is most prominent.

Line % / Label % (0-100): Transparency percentage for lines and labels. Zero is fully opaque, 100 is invisible.

R Labels (checkbox): Shows R labels when validation confirmation occurs. Default disabled. Enable if you want visual confirmation of successful pullback entries.

Tolerance % (0-1.0): Price deviation tolerance for test candle detection. Zero requires exact touch. 0.5 allows 0.5 percent deviation for volatile instruments.

### Dashboard Settings

Show Dashboard (checkbox): Toggles visibility of information panel. Disable for clean chart presentation.

Position: Choose dashboard location from nine positions (Top/Middle/Bottom combined with Left/Center/Right).

---

## LIMITATIONS AND WARNINGS

This indicator is a technical analysis tool that processes historical price data. It does not predict future price movements.

Inherent limitations:

1. Lagging nature: Like all trend indicators, the Kalman filter lags price. Signals occur after trend changes begin, not before.

2. Ranging markets: Generates fewer signals and reduced performance when ADX falls below threshold. Not optimized for sideways consolidation.

3. Whipsaw risk: In choppy, indecisive markets near ADX threshold, signals may reverse quickly despite regime filtering.

4. Parameter sensitivity: Inappropriate Base Gain settings can cause over-trading (too high) or missed trends (too low).

5. Validation requirement: The three-phase confirmation system provides higher accuracy but significantly reduces trade frequency. Not all trends produce valid pullback entries.

Not suitable for:

- Scalping strategies requiring instant signals (Kalman filter has intentional smoothing)
- Ultra-high frequency trading (indicator updates once per bar close)
- Markets with extreme overnight gaps (stops may be exceeded)
- Strategies requiring signals on Heikin Ashi, Renko, Kagi, Point and Figure, or Range charts

Risk management requirements:

This indicator provides trend direction and signal levels but does not incorporate position sizing, risk management, or account balance considerations. Users must implement appropriate position sizing, maximum daily loss limits, and portfolio diversification. Past performance does not indicate future results.

Optimal usage:

- Works optimally in clearly trending markets where ADX consistently exceeds threshold
- Performance degrades in sideways, choppy conditions
- Designed for swing trading and position trading timeframes (15-minute and above)
- Requires confirmation from price action or additional technical analysis

---

## NO REPAINT GUARANTEE

This indicator operates on bar close confirmation only. All signals, signal lines, and validation labels appear exclusively when candles close. Historical signals remain exactly where they appeared. This makes the indicator suitable for automated trading and reliable backtesting. What you see in historical data matches what appeared in real-time.

---

## ALERTS

The indicator provides eight alert conditions:

1. Kalman Buy Signal: Fires when upward triangle appears (bullish trend change in trending market)
2. Kalman Sell Signal: Fires when downward triangle appears (bearish trend change in trending market)
3. Trend Change to Bullish: Fires whenever Kalman line changes to bullish (regardless of ADX)
4. Trend Change to Bearish: Fires whenever Kalman line changes to bearish (regardless of ADX)
5. SCT-R Long Retest Confirmed: Fires when green R label appears for long validation
6. SCT-R Short Retest Confirmed: Fires when red R label appears for short validation
7. SCT Test Long Detected: Fires when test candle appears for long signal (before confirmation)
8. SCT Test Short Detected: Fires when test candle appears for short signal (before confirmation)

Alert messages include context about bar close confirmation and current price levels.

---

## CALCULATION TRANSPARENCY

While complete proprietary optimization methodology is not disclosed, the core technical approach is fully explained: Alpha-Beta Kalman filter with ATR-based adaptive gain adjustment and ADX regime detection. The signal line validation system uses a three-phase structure (hold, test, confirmation) with configurable parameters. Users can understand indicator functionality and make informed decisions about application.

---

## DISCLAIMER

This indicator is provided as a technical analysis tool. It does not constitute financial advice, trading recommendations, or performance guarantees. All trading decisions carry risk. Users are responsible for their own trading decisions and risk management. Past results do not indicate future performance.
リリースノート
v1.1 - R Labels enabled by default

免責事項

この情報および投稿は、TradingViewが提供または推奨する金融、投資、トレード、その他のアドバイスや推奨を意図するものではなく、それらを構成するものでもありません。詳細は利用規約をご覧ください。