OPEN-SOURCE SCRIPT
Обновлено

[Quadapt] Machine Learning Trader

35 499
[Quadapt] Machine Learning Trader

A multi-component Pine Script v6 trading assistant combining a kernel-regression MLMA trend model, dual-length signal envelopes, order block context, retest scoring, adaptive Fibonacci targets, stop loss projection, signal quality filtering, and optional webhook automation.

## Description

[Quadapt] Machine Learning Trader is a full-featured market structure and signal confluence indicator built around a Machine Learning Moving Average (MLMA) trend model. It is designed to help traders analyze trend direction, signal quality, order block context, potential retest areas, and adaptive take-profit / stop-loss levels from one chart overlay.

The script is not a black-box strategy or a guaranteed signal generator. It is a discretionary analysis tool that combines several independent market-context modules into one workflow so traders can compare trend, volatility, structure, momentum, and risk levels before making a decision.

### What Makes This Script Different

The core of the indicator is a kernel-regression MLMA engine. Instead of using only a classic moving average, the script builds a regression-style trend estimate using configurable kernel functions and regression modes. This produces a smoothed adaptive trend line and cloud that can be used as a directional context filter.

The MLMA is combined with:

- dual-length nonlinear signal envelopes,
- market structure and order block detection,
- intelligent retest scoring,
- adaptive Fibonacci take-profit projection,
- stop-loss projection,
- multi-timeframe MLMA trend alignment,
- signal quality filtering,
- clustering prevention,
- market regime adaptation,
- optional webhook payload generation.

The result is a confluence-focused indicator: a buy or sell marker is not treated as useful by itself. It is evaluated against the MLMA trend, recent order blocks, volatility regime, momentum, volume, cloud position, and multi-timeframe alignment.

### MLMA Trend Engine

The MLMA module calculates a machine-learning-inspired moving average using kernel methods. The script supports several kernel types, including:

- RBF,
- Linear,
- Polynomial,
- Sigmoid,
- Laplacian,
- Matern,
- Periodic,
- Trigo.

The regression mode can be configured as:

- GPR,
- KRR,
- KPCR,
- SVR,
- Kernel Smoothing,
- Adaptive RQ.

The MLMA output forms the main trend reference. The script also builds upper and lower MLMA bands using an error envelope derived from average absolute deviation around the MLMA output. These bands are used for the cloud, trend state, signal validation, and context scoring.

When the MLMA state is bullish, the script treats price behavior above or near the bullish support side of the cloud as more constructive. When the MLMA state is bearish, the script treats price behavior below or near the resistance side of the cloud as more defensive.

### Instrument-Agnostic Envelope Logic

The signal envelope section is designed to work across instruments with very different price scales, including forex pairs, JPY pairs, metals, oil, gas, indices, and crypto. The nonlinear envelope transform keeps the original algorithmic shape, but price distance is normalized relative to the instrument's local price level before the transform and restored back into price units afterward.

This matters because a raw price move on EURUSD, GBPJPY, XAUUSD, or XNGUSD has a very different numerical size. Normalizing the envelope distance helps the signal engine behave more consistently across instruments instead of being tuned only for one price scale.

### Dual-Length Signal Engine

The script calculates two separate signal envelopes:

- Primary Length: the slower, broader signal model.
- Secondary Length: the faster signal model.

The dual-length system can run in three modes:

- Independent: either length can produce a signal.
- Consensus: both lengths must agree.
- Primary Priority: only the primary length drives the final signal.

This allows traders to choose between sensitivity and confirmation. Independent mode produces more signals, consensus mode is stricter, and primary priority keeps the chart focused on the slower model.

Signal labels can show regular and stronger buy/sell conditions. When both lengths align in Independent mode, the script can also mark BOTH signals.

### Order Block Detection

The order block module searches for volatility-based bullish and bearish blocks using candle direction, volatility expansion, momentum, optional volume confirmation, and trend alignment. Blocks can be displayed as chart boxes with volume and quality information.

Order block detection includes configurable controls for:

- volatility method,
- volatility length,
- smoothing length,
- minimum separation between blocks,
- maximum blocks per direction,
- consolidation filtering,
- trend filtering,
- volume filtering,
- momentum filtering,
- block display style.

The script assigns order block quality using factors such as block size, directional pressure, displacement, market structure, MLMA trend context, and volume. Higher-quality blocks can be emphasized while weaker blocks can be faded.

### Retest Detection

The retest engine evaluates whether price has returned to a recent order block in a meaningful way. Retests can be scored using:

- block strength,
- clean movement away from the block,
- volume confirmation,
- MLMA trend alignment,
- volatility regime,
- reaction quality near the block.

Retest labels can be displayed as simple `R` markers. Strong and weak retests can be controlled separately, and optional percentage display can show the retest confidence score.

### Adaptive Fibonacci Take Profit Levels

The script can project take-profit levels after valid buy or sell signals. The TP engine supports several methods:

- Dynamic ATR,
- Swing-Based,
- Adaptive Swing,
- Heuristic.

It can display multiple Fibonacci extension targets, optional confluence zones, and TP hit status. The TP table shows the current trade direction, entry reference, target levels, stop loss, and active status.

The TP logic is filtered through MLMA and order block context. For example, a buy signal is considered valid when MLMA context supports the buy, or when price is near a supportive bullish order block. This helps reduce target plotting during low-quality or conflicting conditions.

### Stop Loss Projection

The stop-loss module supports:

- ATR-based stops,
- swing-based stops,
- order-block-based stops,
- percentage-based stops.

Stop levels are plotted only after a valid trade setup is detected. The script also tracks whether price has reached the projected stop or take-profit levels.

### Signal Quality Engine

The signal quality engine scores buy and sell setups before final display. The quality score considers:

- MLMA trend context,
- price position relative to the MLMA,
- multi-timeframe alignment,
- order block support or opposition,
- volume quality,
- volatility regime,
- candle body behavior,
- momentum,
- choppy or no-trade conditions,
- cloud width and MLMA slope,
- recent loss-streak penalty logic.

Signals below the configured minimum score can be filtered out. If desired, rejected signals can also be displayed for research and tuning.

### Advanced Signal Filtering

The script includes adaptive clustering prevention and regime-aware filtering.

Clustering prevention reduces repeated signals in the same area by using a time window, ATR-based price window, decay factor, and maximum cluster count.

Regime-aware filtering adjusts confidence behavior using recent market context, including price movement, volatility trend, and volume trend. This helps the script respond differently in ranging, trending, quiet, and volatile periods.

### Multi-Timeframe Trend Table

The MLMA trend table summarizes the current trend state and several higher/lower timeframe states:

- current chart,
- 15m,
- 30m,
- 1H,
- 4H,
- 1D,
- 1W.

This table is useful for quickly checking whether the current signal is aligned with broader market direction.

### Market Exhaustion

The exhaustion module uses RSI, price extension, momentum change, and volume behavior to identify possible bullish or bearish exhaustion. Exhaustion markers are intended as context warnings, not standalone reversal signals.

### Webhook Automation

Optional webhook alerts can send structured payloads for external automation or journaling. The payload can include:

- symbol,
- ticker ID,
- timeframe,
- event type,
- action,
- account tag,
- risk percent,
- order type,
- entry,
- stop loss,
- TP levels,
- quality score,
- MLMA trend,
- bar time.

Webhook use is optional and should be tested privately before live use.

### Alerts Included

The script includes alert conditions for:

- ML Strong Buy Signal,
- ML Strong Sell Signal,
- ML Buy Signal,
- ML Sell Signal,
- rejected quality signals,
- wedge pattern,
- BOTH length signal,
- bullish order block,
- bearish order block,
- bullish exhaustion,
- bearish exhaustion,
- valid enhanced Fibonacci buy/sell signals,
- invalid buy/sell signals,
- Fibonacci TP hit,
- TP/SL levels set,
- order block retest,
- signal clustering,
- market regime change,
- advanced filtering active.

### How To Use

1. Add the indicator to a clean chart.
2. Start with the default settings.
3. Use the MLMA cloud and trend table to understand directional context.
4. Watch for buy/sell labels only when they align with trend, order block, and quality context.
5. Use order block boxes and retest markers to identify possible reaction zones.
6. Use TP/SL projections as planning references, not as automatic trade instructions.
7. Tune Primary Length, Secondary Length, Signal Mode, and Signal Quality settings for the instrument and timeframe you trade.
8. If using alerts or webhooks, test them on paper or in a private environment first.

### Practical Notes

- Lower lengths are more responsive but can produce more noise.
- Higher lengths are smoother but react later.
- Consensus mode is stricter than Independent mode.
- The Signal Quality Engine can remove many low-context signals.
- The Order Block module is most useful when combined with MLMA trend context.
- TP and SL levels are projections based on the selected method; they are not guarantees that price will reach those levels.
- Exhaustion markers are context warnings and should be confirmed with structure, trend, and volatility.

### Limitations

This indicator does not predict the future. It organizes market context using mathematical filters, kernel regression, volatility logic, order block heuristics, and signal-quality rules. It can still produce false signals, especially during news events, illiquid periods, low-volume sessions, strong trend exhaustion, sudden reversals, or choppy markets.

No indicator should be used alone. Traders should combine this tool with their own risk management, market understanding, and independent confirmation. Past chart behavior does not guarantee future results.
Информация о релизе
**Bug fix** - Runtime stability / drawing-coordinate compatibility fix.

It fixes a TradingView runtime error that could stop the indicator from running on long chart histories.

**Update: Runtime Stability Fix**

This update fixes a potential TradingView runtime error, `RE10026`, that could occur on long chart histories when confluence zones were drawn from an older signal bar using bar-index coordinates.

The confluence zone visualization now tracks the signal timestamp and uses time-based drawing coordinates for its boxes, lines, and labels. This keeps the visual projection compatible with TradingView's drawing limits across deeper chart histories and different instruments.

This is a drawing-stability fix only. It does not change the MLMA calculation, signal generation logic, order block logic, TP/SL logic, signal quality engine, or alert conditions.

## Short Version

Bug fix: resolved a potential `RE10026` runtime error in confluence zone rendering on long histories by switching the confluence drawings from old bar-index coordinates to time-based coordinates. No signal or calculation logic was changed.

## What Changed

  • Fixed a runtime error that could occur when confluence drawings referenced a bar too far back in history.
  • Changed confluence zone boxes, lines, and labels to use time-based coordinates.
  • Added timestamp tracking for the active signal used by the confluence projection.
  • Improved compatibility on symbols and timeframes with long loaded histories.


## What Did Not Change

  • MLMA algorithm logic.
  • Buy and sell signal conditions.
  • Signal quality scoring.
  • Take-profit and stop-loss logic.
  • Order block detection.
  • Alert conditions.
  • Any trading or market-direction calculation.

Информация о релизе
Bug fix - Runtime stability / drawing-coordinate compatibility fix.

It addresses the same class of TradingView drawing-limit risk in the active TP/SL visuals.

Update: Additional Runtime Stability Fix

This update changes the active take-profit and stop-loss visuals to use time-based drawing coordinates instead of old bar-index anchors. This should improve stability on long chart histories while keeping the projected TP/SL levels visually aligned with the active signal.

This is a visual drawing-stability fix only. It does not change the MLMA calculation, buy/sell signal logic, TP/SL price calculation, order block logic, signal quality engine, or alert conditions.

## What Changed

  • Converted active TP projection lines to time-based coordinates.
  • Converted active TP labels to time-based coordinates.
  • Converted active stop-loss lines and labels to time-based coordinates.
  • Added shared future-time projection logic for TP/SL drawings.
  • Reduced the risk of TradingView drawing-limit errors on long loaded chart histories.


## What Did Not Change
  • MLMA algorithm logic.
  • Buy and sell signal conditions.
  • TP and SL price calculations.
  • Signal quality scoring.
  • Order block detection.
  • Alert conditions.
  • Any market-direction or trade-entry calculation.

Информация о релизе
Update: Stability And Logic Hardening

This update addresses several technical issues found during a deeper audit of the script. The focus of this release is stability, cleaner internal state handling, and more accurate automation behavior.

Key improvements:
  • Fixed volume baseline updating so average volume no longer freezes after initialization.
  • Improved regime/adaptive threshold logic so learning state can update correctly.
  • Separated bullish and bearish retest tracking to prevent state cross-contamination.
  • Hardened Kernel Smoothing with forecast values.
  • Added protection against
    Pine Script®
    NaN
    values in multiplicative multi-kernel mode.
  • Improved order block overlap detection.
  • Improved the Order Block stop-loss method so it references recent OB zones instead of using a simple placeholder distance.
  • Added unique
    Pine Script®
    signal_id
    values to webhook payloads.
  • Changed partial TP webhook action to
    Pine Script®
    PARTIAL_CLOSE
    , while final TP remains
    Pine Script®
    CLOSE
    .
  • Prevented new signals from silently replacing an active unresolved trade.
  • Reduced realtime HTF/MTF repaint risk by using confirmed higher-timeframe values.
  • Removed or wired up several previously inactive inputs and helper paths.


This is primarily a bug fix and stability update. It does not change the core MLMA concept, but it improves the reliability of the surrounding signal, retest, TP/SL, and automation systems.
Информация о релизе
Update: Signal Replacement And Webhook Reliability

This update improves how ML Trader handles new signals while an existing trade setup is still active.

Previously, when a fresh buy or sell signal appeared before the prior TP/SL setup had fully completed, the script could replace the active setup without making that replacement explicit in webhook automation. This update makes that behavior clearer and safer while preserving the original chart behavior where new valid signals refresh the TP/SL levels.

Key improvements:

  • Added unique `signal_id` values to webhook payloads so each signal can be tracked more reliably.
  • Added an explicit `SIGNAL_REPLACED` / `CANCEL_REPLACE` webhook event when a new signal replaces an unfinished active setup.
  • Preserved the existing TP/SL refresh behavior, so a new valid buy or sell signal can still redraw its own TP and SL levels.
  • Kept the TP/SL drawing logic responsive to fresh chart signals instead of blocking updates while a previous setup is active.


This is a webhook and signal-lifecycle bug fix reported privately. It does not change the core MLMA logic or the way signals are generated. It simply makes signal replacement clearer for automation users while keeping the visual TP/SL behavior consistent with previous versions.

Отказ от ответственности

Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.