PROTECTED SOURCE SCRIPT

MTF Target Radar [Rulph]

51
MTF Target Radar - Multi-Timeframe Target Clustering with Machine Learning

MTF Target Radar is an advanced target projection system that analyzes trendline breakouts across multiple timeframes (Daily to Biweekly) and clusters projected targets into high-probability zones. It dynamically calculates targets from actual breakout patterns and validates them through multi-timeframe confluence and machine learning, instead of using static support/resistance or fixed Fibonacci ratios.

The system continuously tracks cluster performance (Reached / Lost / Timeout) and uses this history to improve future predictions through a transparent k-Nearest Neighbors (k-NN) logic, providing explainable adjustments to cluster quality rather than black-box scores.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
WHY COMBINE MULTI-TIMEFRAME TARGETS?
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Most target projection methods rely on a single timeframe or on arbitrary geometric ratios. MTF Target Radar is designed around three core ideas:

1. Cross-timeframe validation: A target zone where multiple higher timeframes converge (e.g., 1D, 2D, 3D, 4D, 5D, 6D, 1W, 2W) indicates a structural price magnet, where several independent trend cycles agree on a probable area of exhaustion, continuation, or reversal.

2. Dynamic projection from real patterns: Targets are computed from the geometry of each breakout (distance from the trendline to the extreme of the pattern) instead of being fixed percentages from arbitrary swing points. This makes projected levels adaptive to the actual volatility and structure of each pattern.

3. Adaptive learning: The system learns which cluster characteristics (density, strength, distance, momentum, market regime, etc.) historically lead to successful outcomes and then gently adjusts future cluster qualities in that direction.

The result is a "target radar" where the most important zones stand out because they combine: multiple timeframes, favorable structure, and a positive historical profile with similar setups.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
COMPONENT 1: TRENDLINE BREAKOUT DETECTION
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

For each enabled higher timeframe (up to 8), the indicator performs the same deterministic process:

1. Swing pivot detection
It finds swing highs and lows using a configurable pivot length (default 3 bars left and right), which defines local extremes for trendline construction.

2. Trendline construction
- For bullish breakout setups (upward target clusters), it connects two descending swing highs to form a bearish trendline.
- For bearish breakout setups (downward target clusters), it connects two ascending swing lows to form a bullish trendline.

3. Breakout detection
A breakout is confirmed when the close crosses and holds beyond the trendline in the opposite direction of the preceding trend (close above a descending line for long setups, or below an ascending line for short setups), which indicates that the previous trend structure has failed.

4. Target projection
The target is measured from the internal structure of the pattern, not guessed:

For bullish (upward) targets:
- The algorithm finds the lowest low between the second pivot and the breakout.
- It computes the vertical distance from the trendline value at that bar to this lowest low.
- This distance is then projected above the breakout level to obtain an initial target.

For bearish (downward) targets, the logic is mirrored using the highest high within the pattern range.

This makes each target a direct function of how "compressed" price was before breaking out, creating geometry-driven objectives that adapt to each pattern.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
COMPONENT 2: TARGET CLUSTERING
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

All individual targets from active timeframes are merged into clusters, which represent zones where multiple projected levels overlap or lie very close to each other.

Clustering logic:
- All targets are sorted by price.
- Targets within a maximum distance (MAX_CLUSTER_DISTANCE, default 1.5% of price) are merged into a single cluster.
- A cluster must contain at least MIN_CLUSTER_SIZE targets (default 2) to be considered valid and plotted.

Cluster properties include:
- Center: the average target price within the cluster.
- Size: number of contributing targets; more targets imply stronger structural agreement.
- Spread: the price width between the lowest and highest targets in the cluster.
- Timeframe composition: which timeframes contributed (e.g., "1D, 2D, 3D, 1W").

A tight cluster where many timeframes converge is treated as a stronger and more precise target than scattered levels spread widely in price.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
COMPONENT 3: QUALITY SCORING SYSTEM
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Each cluster receives a base quality score from 0 to 1, computed as a weighted combination of four dimensions:

1. Density score (weight: 0.35)
- Based on how narrow the cluster is relative to volatility.
- Uses normalized spread: cluster_spread / ATR(14).
- A smaller normalized spread leads to a higher density score.

2. Strength score (weight: 0.35)
- Depends on the number of targets and their distribution across timeframes.
- Uses a log-scaled function of cluster size and a density factor so that adding more confluences yields diminishing but still meaningful improvements.

3. Reachability score (weight: 0.20)
- Based on the distance from current price to cluster center in percent terms.
- Closer clusters are easier to reach; very distant ones are penalized unless the market and trend strongly support extended moves.

4. Momentum score (weight: 0.10)
- Analyzes the last few candles (e.g., 5 bars) using candle bodies, wicks, and short-term rate of change to determine whether current price action supports moving into the cluster.

Base quality formula:
The base quality is a convex combination:
Q_base = 0.35 × Density + 0.35 × Strength + 0.20 × Reachability + 0.10 × Momentum, with additional multiplicative penalties when reachability is too low or the overall market regime contradicts the direction of the cluster.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
COMPONENT 4: MACHINE LEARNING ADJUSTMENT
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

When the ML enhancement is enabled and there is enough history, the script uses an internal k-Nearest Neighbors approach to adjust cluster quality based on what worked or failed in the past.

Feature extraction:
For each cluster, the system extracts a feature vector including:
- Base quality, distance to target, volatility, trend strength (ADX), RSI value, volume ratio, recent momentum, cluster size, density, market regime, volume trend, timeframe consistency, and price acceleration.

Neighbor search:
- Only clusters with the same direction (up or down) and with finalized outcomes (reached, lost, or timeout) are considered.
- A Lorentzian distance metric is used: sum over all features of log(1 + |difference|) multiplied by per-feature weights, so that extreme outliers do not dominate.

Graduated success scoring:
Each historical cluster stores a continuous success_score, not just 0 or 1:
- Full success when the target zone is actually reached with reasonable timing.
- Partial credit when price comes very close but slightly misses the cluster or reaches only part of it.
- Penalties when the cluster times out or price moves away strongly.

ML adjustment of quality:
The script computes an ML_probability for the active cluster by aggregating neighbors' success_score values weighted by similarity and recency. This ML-derived probability is then mixed with the base quality:

Q_adjusted = Q_base × (1 − ML_weight) + ML_probability × ML_weight,

where ML_weight increases gradually with the amount and reliability of historical data and is capped so that ML cannot completely override the base structural logic.

Additionally, performance metrics such as recent accuracy, false positives, false negatives, and total predictions are tracked to adapt how much trust is placed in ML adjustments over time.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
COMPONENT 5: TIME-TO-TARGET PREDICTION
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

When time prediction is enabled, the indicator estimates how many bars it may take for price to reach the cluster. This is an experimental feature designed for context, not as a hard promise.

Base estimate:
- Uses distance to cluster and current volatility as primary inputs.
- Time is scaled differently for various asset classes (e.g., crypto vs. equities), so that fast markets do not get unrealistic long estimates and slow markets do not get unrealistically short ones.

ML refinement:
If enough successful historical clusters with similar features are available, the script:
- Filters neighbors that actually reached their targets.
- Uses their real bars_to_reach values.
- Computes a weighted average to refine the time estimate.

The final time prediction is a blend of base estimate and ML-derived value, with a confidence measure derived from the number, similarity, and recency of matching examples.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CLUSTER STATE MACHINE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Each cluster goes through a simple and explicit state machine:

forming → active
Once cluster quality rises above the minimum threshold, it becomes active and is displayed on the chart.

active → reached
The cluster is marked as reached when price touches at least the first target in its internal list (TP1), using direction-sensitive logic (high >= TP1 for long clusters, low <= TP1 for short clusters).

active → lost
If the underlying targets are structurally invalidated (e.g., fewer than MIN_CLUSTER_SIZE remain due to market movement), the cluster becomes lost.

active → timeout
If age exceeds MAX_CLUSTER_AGE (default 40 bars) without reaching the target, the cluster is marked as timeout, so stale setups do not stay active indefinitely.

Final states (reached, lost, timeout) are recorded with snapshots of cluster features, bars_alive, bars_to_reach, and realized P&L percentage. These records feed back into the ML history.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
HOW TO USE MTF TARGET RADAR
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Basic workflow:

1. Enable the higher timeframes that are relevant to your trading style (e.g., 1D–6D + 1W for intraday or swing trading).
2. Set Min Quality Score (MIN_QUALITY) according to your risk tolerance:
- 0.3–0.4 for aggressive,
- 0.5–0.6 for balanced,
- 0.7+ for conservative setups.
3. Optionally enable ML and time prediction once enough history is accumulated.
4. Use the trend context block (if enabled) to see whether clusters align with the dominant trend or go against it.

Reading the chart:
- Green boxes above price = upward target clusters (long objectives).
- Red boxes below price = downward target clusters (short objectives).
- Box width shows the price range of the cluster; box position shows where price is expected to gravitate.
- Labels can include: contributing timeframes, cluster center, base quality, ML-adjusted quality, distance to target, and estimated time to target when enabled.

Example entry logic:
- For a long: price is below a strong green cluster, quality > 0.6, direction aligned with the current trend, and ML-adjusted quality is not significantly lower than base quality.
- Entry can be timed using your own triggers (breakouts, pullbacks, candlestick patterns), while the cluster defines the target area rather than the exact entry.

Example exit logic:
- Take profit as price enters the cluster zone.
- Scale out around cluster center or when realized move covers your planned R-multiple.
- Exit early if the cluster flips to "lost" or if an opposite-direction high-quality cluster appears and is closer than the current one.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
WHAT MAKES MTF TARGET RADAR ORIGINAL
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

MTF Target Radar is not a simple overlay of trendlines and support/resistance; it implements a full pipeline: pattern-based target projection, cross-timeframe clustering, quality scoring, and machine learning feedback.

Key aspects of originality include:

- Multi-timeframe target clustering where zones are built from many independent breakouts instead of a single pattern.
- Quantified cluster quality combining density, strength, reachability, and momentum in a transparent scoring model.
- Graduated ML learning that uses continuous success scores and explainable k-NN, rather than opaque models.
- State machine tracking of each cluster's lifecycle with explicit rules for success, failure, and timeout.
- Optional time-to-target estimation that reuses the same ML history instead of guessing fixed time windows.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CHART LEGEND
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

- Green box above current price: bullish target cluster.
- Red box below current price: bearish target cluster.
- Historical clusters can be marked with symbols:
- ✓ for reached,
- ✗ for lost,
- ⏱ for timeout,
often accompanied by a diagonal line showing entry-to-target path and final P&L%.

- Optional trend context (LazyTrend/SuperTrend-style block):
- Green background: bullish regime.
- Red background: bearish regime.
- Neutral colors: sideways or mixed regime.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Additional Resources (Optional):
This description is complete and self-contained; no external materials are required to understand how the script works or how to use it. Any separate educational ideas or examples are optional and serve only as additional illustration.

Disclaimer: MTF Target Radar is a decision-support tool, not a standalone trading system. All trading involves risk, and past cluster performance does not guarantee future results. Always backtest and apply proper risk management.

免责声明

这些信息和出版物并非旨在提供,也不构成TradingView提供或认可的任何形式的财务、投资、交易或其他类型的建议或推荐。请阅读使用条款了解更多信息。