KF_AIKF-AI™ is a deterministic Pine Script v6 library providing a constitutional foundation for AI-oriented services.
The library is organized into ten modules covering identity, constants, enumerations, runtime contracts, utility functions, manifest governance, AI standards, health monitoring, diagnostics, and operational summaries.
KF-AI™ currently provides deterministic contracts, validation, state management, utilities, health classification, diagnostics, and summary services. It does not perform machine-learning inference, prediction, scoring, automated trading, or trade execution.
The architecture is designed as a reusable foundation for future AI-oriented Pine Script services while maintaining explicit separation between identity, runtime contracts, governance, health, diagnostics, and summary layers.
Version: 1.0.0
Build: 0001
Modules: AI-0001 through AI-0010
Constitution: Constitution v1.0 Library

ORB AI [PickMyTrade]ORB AI asks a question most opening-range tools skip: does this
breakout resemble the chart's own past breakouts that worked, or the ones that didn't?
Instead of firing on a single range-break condition, every qualified breakout is scored
across seven independent structural factors, then cross-checked against an on-chart
K-nearest-neighbour library built exclusively from this symbol's own resolved breakout
outcomes. Both numbers are shown — the rule score and the KNN vote — without either one
silently deciding the trade for you.
----------------------------------------------------------------------------------------------------------------
🔷 WHAT IT MEASURES
🔸 Opening Range
The range locks from a configurable session anchor — Exchange Session (the symbol's own
listed timezone), New York 09:30, New York 08:30 (data), London 08:00, Tokyo 09:00, or a
Custom session/timezone pair — over a configurable window (1–120 minutes). If the chart
timeframe is coarser than the chosen window, the range automatically expands to one full
bar and the dashboard notes the effective duration rather than silently misrepresenting
it.
🔸 Rule Confidence (7-factor score)
Every qualified breakout candidate is scored 0–100 across Trend, Momentum, Volume,
Volatility, Structure, Breakout Quality and Liquidity. Trend itself is a blend (35% EMA
alignment, 25% ADX, 25% higher-timeframe read, 15% slope) — the dashboard breaks out all
seven components individually so the score is never a black box.
🔸 Flow Marks — BO / RT / FBO / Sweep
BO tags the confirmed breakout bar. RT tags a retest of the broken range edge that holds
(with a running count). FBO tags a breakout that closed back inside the range — a false
breakout, not a win or loss judgement. Sweep tags a wick that pierced the range edge and
closed back inside — liquidity taken without a directional close.
----------------------------------------------------------------------------------------------------------------
🔷 THE KNN ENGINE (LORENTZIAN DISTANCE)
🔸 How the library is built
Every rule-qualified breakout gets a 6-feature fingerprint (trend, momentum, volume,
volatility, structure, breakout quality). Its outcome is then resolved forward, stop
checked first: 1R target reached before the stop = win, stop first = loss, neither
within the configurable outcome window (15–600 minutes) = discarded as undecided —
drifts are never counted as losses, so the base rate reflects only decisive breakouts.
Every qualified candidate is recorded regardless of outcome, so the library grows
without selection bias.
🔸 How a new candidate is voted
A new candidate is compared to the stored library (up to 300 records) by Lorentzian
distance. The K nearest historical analogues (3–15, default 5) vote, and the vote share
is shown on the signal label and dashboard.
🔸 Advisory vs. Gate
Advisory mode (default) displays the vote as context; it never blocks a signal, so the
set of signalling bars stays fully deterministic regardless of library state. Gate mode
(opt-in) also requires the vote to clear a minimum share before a signal fires — this
trades determinism for selectivity and is only meaningful once the library has grown
past a configurable minimum size.
🔸 Read honestly
With a 6-feature fingerprint, the nearest neighbours of a few-hundred-record library
span roughly half of each feature's range — the vote is a coarse regional tendency, not
a precise analogue match. Loading a different amount of chart history can change the
displayed vote (Advisory) or which candidates pass (Gate); this is inherent to on-chart
instance-based learning and is disclosed rather than hidden. The indicator requires a
symbol with volume data — volume-less feeds (some cash indices / spot FX) cannot render
the KNN engine.
----------------------------------------------------------------------------------------------------------------
🔷 SIGNALS AND DISPLAY
🔸 Dashboard
A compact table shows Session, Regime, ML Engine status (library size / warm-up state),
locked Range, Bias, the 7-factor Rule Confidence bar, Risk-per-Unit, the active Trade
Plan, and a Flow Marks legend. An optional Full mode expands all seven score components.
🔸 Trade Plan overlay
On a qualified signal the indicator draws an entry, stop, and take-profit levels using
one of three configurable methods: a fixed R ladder, an opening-range-width measured-move
projection, or an ATR-scaled EMA-dynamic trail. This is a reference overlay describing
one rules-based way to structure the trade *if* you choose to take it — it is not a
recommendation, and the levels are not a performance claim.
🔸 Non-repainting
Signals evaluate on confirmed closes only. Locked range levels never change once set.
Higher-timeframe reads use ` ` plus `lookahead_off`. The KNN library is built strictly
from already-resolved past outcomes — no future data is read at any point.
🔸 Alerts
19 `alertcondition()` calls cover long/short entries, false breakouts (combined and
per-direction), confidence-threshold crosses, range completion, trend-context changes,
take-profit and stop touches (combined and per-level), reversals, session-end exits,
approaching-breakout warnings, retests, and sweeps above/below the range. Recommended
alert setting: *Once Per Bar Close*.
----------------------------------------------------------------------------------------------------------------
🔷 INPUTS
🔸 Opening Range — Session anchor, custom session/timezone, range length (minutes).
🔸 Signal Engine — Minimum Rule Confidence threshold, TP method (R Ladder / OR Width
Projection / Dynamic EMA), R-ladder multiples, wide-range-OR filter.
🔸 KNN · ML Engine — Mode (Advisory / Gate / Off), K neighbours, history length,
minimum ML vote (Gate only), outcome window (minutes), Gate minimum library size.
🔸 Filters — Signal Blackout window (session-anchor timezone), max signals per
session, news filter.
🔸 Visual — Bull/bear colours, dashboard position and detail level, Zen mode (hides
text labels, keeps shapes/zones only).
----------------------------------------------------------------------------------------------------------------
🔷 REQUIREMENTS AND LIMITATIONS
Requires a symbol with volume data — the KNN engine cannot render on volume-less feeds
(some cash indices, spot FX). The KNN vote is a coarse regional tendency drawn from a
finite on-chart library, not a precise analogue match or a probability estimate; it is
advisory by default for that reason. Loading a different amount of chart history changes
the displayed vote in Advisory mode, and can change which candidates pass in Gate mode —
this is inherent to on-chart instance-based learning and is disclosed rather than hidden.
This is a decision-support toolkit: it does not place trades, and no element of the
dashboard, score, or trade-plan overlay is a claim about future performance. Always
apply independent risk management.
----------------------------------------------------------------------------------------------------------------
Built natively in Pine Script® v6. Seven-factor rule-based confluence scoring with an
on-chart, self-learning KNN engine using Lorentzian distance over resolved breakout
outcomes — no external libraries, no repainting, no lookahead.
Open source — Mozilla Public License 2.0. Indicator

Adaptive SuperTrend AI - Regime-Tuned [Dots3Red]📈 ADAPTIVE SUPERTREND AI — REGIME-TUNED
Classic SuperTrend uses one fixed ATR multiplier forever. That single number is a compromise: tight enough to track trends closely, it whipsaws during ranges; wide enough to survive ranges, it lags badly once a real trend starts. This script replaces the fixed multiplier with one that changes based on what kind of market is actually happening, using the same regime-detection engine shared across the Dots3Red catalog.
🧠 THE REGIME ENGINE
Every bar is classified into one of four states using ADX and the Choppiness Index together:
• 📈 TRENDING — ADX confirms directional strength and Choppiness confirms low chop
• 🔁 RANGING — the opposite: weak directional strength, high chop
• ⚡ VOLATILE — current ATR has expanded well beyond its baseline, regardless of direction or chop
• ❔ UNCERTAIN — none of the above conditions are clearly met
The raw regime reading is smoothed by taking the most frequent classification over a short lookback window, so a single noisy bar can't flip the regime label back and forth.
🤔 WHY RANGING GETS THE WIDEST BAND, NOT TRENDING
This is the part that looks backwards at first glance, so it's worth explaining directly. A ranging market chops back and forth around a mean — if the band were narrow here, ordinary noise would cross it constantly, causing false flips. So RANGING gets the widest multiplier (default 3.5×), letting normal chop stay inside the band. A TRENDING market is moving with genuine conviction, so a moderate multiplier (default 2.5×) tracks the move closely without giving back excessive profit before flipping on an actual reversal. VOLATILE conditions get the widest multiplier of all (default 4.5×) as a purely defensive setting, since sudden expansion is unpredictable by nature.
When the regime changes, the active multiplier doesn't jump to its new value instantly — it glides toward it over a configurable number of bars. This prevents the band from visibly teleporting on a regime transition, which would otherwise look jarring and could itself trigger a false flip right at the transition point.
The underlying band mechanics — the ratcheting upper/lower band logic, and a flip only when price closes beyond the active band — are the same as classic SuperTrend. Only the multiplier driving the band width is dynamic.
✅ THE CONFIDENCE LAYER
A SuperTrend flip is a single binary event: price crossed the band, direction changed. This script adds a secondary read on how convincing that flip actually is, using 8 independent checks against the new direction:
1. Close vs. a trend moving average
2. MACD histogram sign
3. Recent higher-high / lower-low structure
4. Close vs. the SuperTrend's own midline (hl2)
5. RSI side of 50
6. +DI vs. -DI dominance
7. Volume above its moving average on a trend-direction bar
8. Whether the regime is currently TRENDING
Every confirmed flip shows this count directly on its label — "▲ 6/8" means 6 of the 8 checks currently agree with the new uptrend. A flip with 7/8 agreement and one with 3/8 are treated identically by the raw band mechanics, but this layer gives a way to distinguish a well-supported flip from a marginal one at a glance.
🎯 FLIP WIN-RATE TRACKING
Each flip is graded once the following flip occurs: did price actually finish above the flip price (for an up-flip) or below it (for a down-flip) by the time direction changed again? This produces a running win rate — for example "58% (n=34)" — shown in the dashboard. It is a simple, honest measure of how the flips on this specific chart have actually played out, not a backtest or a promise about future flips.
🔒 NON-REPAINTING
Flips, confidence readings, and labels are all evaluated only on confirmed (closed) bars. A flip that appears on the chart will not later disappear or move to a different bar as new price data arrives.
🎨 VISUALS AND CUSTOMIZATION
The SuperTrend line and gradient fill are colored by current direction. Flip labels appear directly on confirmed flip bars with their confidence count. An optional background tint can shade the chart by current regime. All four core colors (bullish, bearish, volatile/warning, and uncertain/neutral) are fully customizable in settings, independent of the script's default palette.
The dashboard (position configurable) shows: current direction, current regime, the active ATR multiplier, the confidence count with a progress bar, the running flip win rate, and the raw ADX, Choppiness, and ATR ratio readings behind the regime classification.
🧭 HOW TO USE
👀 Reading the line and fill — the colored line and gradient fill show current direction at a glance. This is the same information classic SuperTrend gives you; the difference here is in how the band width behind that line was chosen.
🧠 Check the regime before trusting the band width — the dashboard's Regime row tells you why the band is currently as wide (or narrow) as it is. A band that looks unusually wide isn't a bug — it likely means the engine has classified the market as RANGING or VOLATILE and widened defensively. Knowing the current regime helps set expectations for how the band will behave if conditions stay the same.
✅ Use the confidence count to gauge flip quality, not to filter flips — every flip is real and non-repainting regardless of its confidence count. The count is a lens for judging how broadly supported a given flip is, not a gate that decides whether one occurs. A "▲ 7/8" flip and a "▲ 3/8" flip both mean the band was crossed; the number tells you how much independent agreement existed at that moment, which is useful context when deciding how much weight to put on that particular signal versus your own analysis.
🎯 Watch the flip win rate as a running self-check on this chart — because it only starts once flips have accumulated and been graded, treat an early or low-sample win rate as inconclusive rather than a verdict. It becomes more informative the longer the script runs on a given symbol and timeframe.
🔔 Regime changes are themselves informative — the alert for a regime change fires independently of any flip. A shift from RANGING to TRENDING, for example, can be useful context on its own, since it signals the band is about to glide toward a different multiplier even before any flip occurs.
🚫 This script describes band behavior, not entries or exits — it does not tell you when to open or close a position. Use it as one input alongside price action, structure, and whatever other analysis you already rely on.
⚙️ SETTINGS
📈 SuperTrend Core
• ATR Length
• Factor — Trending / Ranging / Volatile / Uncertain — the four regime-driven multipliers
• Factor Transition (bars) — how gradually the multiplier glides between regimes
🧠 Regime Engine
• ADX Length, Choppiness Length, ATR Baseline Period
• Trending / Ranging Thresholds — where the combined ADX+Choppiness score is classified
• Volatile ATR Multiple — how far above baseline ATR counts as volatility expansion
• Regime Smoothing — lookback window for the majority-vote smoothing
✅ Confidence Layer
• Trend MA Length, RSI Length, Structure Lookback — parameters for the 8 confidence checks
🎨 Visualization
• Gradient Fill, Flip Labels, Regime Background Tint — each toggleable independently
• Full color customization for all four regime/direction colors
🖥️ Dashboard
• Show/hide, position
📝 NOTES
The regime engine needs a short warm-up period before its smoothing window is fully populated; early bars on a fresh chart may show less stable regime labels than bars further along. The flip win rate starts empty and only becomes meaningful after several flips have occurred and been graded.
⚠️ DISCLAIMER
This is an analytical and visualization tool. It does not generate trade signals and does not constitute financial advice. Historical flip win rate does not guarantee future performance. Indicator

IQ Trend Beams [TradingIQ]🔹 OVERVIEW
IQ Trend Beams is a trend assistant that draws your trendlines the way a disciplined chartist would - and then holds them accountable. It maintains two channels, support and resistance , each always showing one working line. A line is born forming : it moves and re-shapes freely, polished every bar by a perceptual score toward the line a skilled trader would actually draw. When its geometry settles and it has earned enough tangency credit, it locks - and from that moment the ink is frozen forever; it never moves again. Locked ink extends until break evidence fires, then it is broken : restyled but never relocated, holding the screen as history until its successor locks.
Riding each live beam is its own forecast ; a calibration band, a reach profile, and ghost levels, all built from the volume that has actually traded around that line.
This is an honest visualization and modeling tool , not a signal service. It draws structure clearly and states its own confidence out loud; it is not a validated edge or a promise of profit. Read the limitations section - it is not window dressing.
🔹 THE TWO CHANNELS - AN AUDITED PROMISE
Most trendline tools quietly redraw the past so the line always looks right in hindsight. Trend Beams refuses to. A line lives through three visible states:
• Forming (dotted) - the assistant sketching. It is free to move and re-fit while it hunts for the right geometry. This is the only state in which a support/resistance line moves, and it is dotted precisely so you can tell a guess from a commitment.
• Locked (solid) - the geometry has stilled and earned its tangency credit, so the line is frozen . It will never move again. A locked beam is a promise the tool has to keep in public.
• Broken (restyled) - break evidence fired. The ink is re-styled to show it failed, but it is never relocated ; it holds its original slope as an honest record and, if you keep history on, dims into the background once its successor locks.
Because a locked line cannot move, what you saw at lock time is what you keep. This is the core design commitment of the tool.
Two rails, either direction by design. Support is the lower rail, fit to the swing lows on the underside of price; resistance is the upper rail, fit to the swing highs above it. Neither is locked to a single slope: in a falling market the support rail angles down with the lows (the floor of the down-channel), and in a rally the resistance rail angles up with the highs (the ceiling of the up-channel). That is deliberate. A tool that forces support to only ever point up would go blind to the lower boundary of a downtrend - and miss exactly the moves that matter. Trend Beams instead always draws both boundaries of the channel price is actually in , so a strong move is framed on both sides rather than half-missed. If you prefer to read it the classical way, follow the rail that agrees with the trend and treat the other as the opposite wall of the same channel.
🔸 HOW A LINE EARNS ITS LOCK
While forming, each line is scored every bar by a perceptual fit , a running measure of how well its geometry matches what a careful trader would draw against the recent swing structure, blended with a one-pole toward its fitted slope so it settles rather than twitches. A lock is granted only when the geometry has gone still for long enough, the line has accumulated real tangency credit (genuine touches, not a single graze), and it spans a minimum bar count - and it is refused outright if it would invert the channel. The Mode dial sets how much evidence this takes.
🔹 THE AUDIT BADGE
Locked ink can carry a small measurement badge that reports, in plain terms, how the line is actually holding up:
• Wick-through - recent piercing of the line, exponentially weighted, measured against the tool's 10% design target . A well-behaved line lets price kiss it, not knife through it.
• Survival probability - the current modeled odds that the line is still valid.
• Maturity - how far through its estimated total run the move is, so a young trend reads differently from an exhausted one.
The badge is the tool grading its own work on the chart, not a trade instruction.
🔸 THE FORECAST - EACH BEAM READS ITS OWN VOLUME
Every live beam carries its own forecast, built entirely from the volume that has traded around that line. Trend Beams bins the intrabar volume by its distance from the beam, smooths it into a continuous density (a kernel-density estimate), and renders three things that ride the line:
• Calibration band - translucent ribbons hugging the beam, one per density bin, showing where the trend has held its volume. Strength is encoded as colour vibrancy at a constant perceptual lightness (the Oklab principle - a dense core reads vivid, the thin tails fade), so nothing is made brighter or darker than its weight warrants.
• Reach profile - a smooth filled contour fanning into the future margin, where each level's forward extent is its density times the trend's estimated remaining length . It answers, at a glance: if this trend keeps going, how far - and around which prices - does its own volume say it reaches?
• Ghost levels - dashed lines at the distribution's densest peaks, riding parallel to the beam, marking the prices this trend keeps returning to.
The forecast attaches only to a beam's currently-visible live element - its forming sketch, or its locked ink - and keeps no history . It is a read of the present trend, refreshed at the live edge, not a replay of the past.
🔸 THE ENGINE DIALS
• Mode - the tempo. Fast locks, breaks and re-forms sooner (short swings); Slow demands more evidence and holds through more noise (long moves); Medium is the balanced reference.
• Precision - how much data the engine reads: the perceptual fit window and the intrabar sample rate. Higher tiers resolve finer structure at more load. Sampling is timeframe-aware and never drops below one minute.
🔹 LAYERS, COLOUR & LEGIBILITY
Every layer is a toggle - forming lines, broken history, audit badges, and the forecast - so you can run it as a bare two-line channel or a fully dressed read. Colours come from three clean anchors: Support , Resistance , and Chrome (badges and neutral furniture). The whole translucent forecast - band, profile, and ghost levels - is coloured in the Oklab perceptual space, so strength shows up as vibrancy at a constant lightness rather than as glare, and a single Contrast dial scales the entire forecast from a whisper to bold.
🔸 HOW TO READ IT
• Treat a forming (dotted) line as a hypothesis and a locked (solid) line as a committed level - the tool is telling you which is which on purpose.
• Watch the audit badge : rising wick-through and falling survival probability say a locked line is wearing out.
• Read a broken line as a failed level that still marks where the structure gave way.
• Use each beam's band to see where its trend has held its volume, its reach profile for how far the trend's own volume says it can run, and its ghost levels for the prices it keeps returning to.
🔹 INPUTS
• Trend Engine - Mode (tempo) and Precision (data depth).
• Layers - show forming lines, broken history, audit badges, and the forecast.
• Colors - Support, Resistance, and Chrome anchors, plus a Contrast control for the translucent forecast.
• Channels - enable the support and/or resistance side independently.
🔸 LIMITATIONS AND HONEST NOTES
• This is a drawing and modeling assistant , not a validated strategy. It makes no performance claim and no edge claim . Nothing here is financial, investment or trading advice.
• Locked and broken lines do not repaint - once a line locks, its geometry is frozen. Forming lines move by design (they are the live sketch, and are dotted to say so), and each beam's forecast (band, profile, ghost levels) refreshes at the live edge as new volume arrives and attaches only to the current live element. These are live reads, on purpose; none of them rewrites confirmed history.
• Survival probability, maturity, remaining length and the reach profile are model estimates from the trend's own statistics - projections, not guarantees, and not forecasts of price.
• Intrabar sampling is subject to your plan's intrabar data limits ; higher Precision tiers read more intrabar data.
• Drawing budgets are finite. The tool caps its lines, labels and polylines internally, but very long histories with everything enabled push against PulseWire's per-script drawing limits - trim the layers you don't need.
Indicator

AI K-Means Clustering [TradingFinder] Machine Learning Zones🔵 Introduction
K-Means clustering is an unsupervised machine learning algorithm that groups similar data points around repeatedly updated cluster centers. Each observation is assigned to its nearest center, the centers are recalculated, and the process continues until the clusters converge. In financial market analysis, this structure can separate recurring patterns in price movement, trend direction, volume pressure, and volatility without depending entirely on fixed thresholds. As a result, the same candle may be interpreted differently in a quiet market, a directional trend, or a volatility shock, because its meaning is evaluated in relation to the surrounding market data.
This PulseWire indicator applies K-Means machine learning through several connected analysis modules. The Market State engine studies trend bias, price slope, and relative volume pressure to classify the current market regime as an active bullish trend, active bearish trend, soft bullish trend, soft bearish trend, neutral range, or low-volume range. It also compares the current cluster with the dominant cluster across recent candles, helping the trend classification remain more stable when a single large candle, temporary spike, or short-lived price reversal appears.
The Price Zones engine clusters pivot points, historical highs, and historical lows to create dynamic K-Means support and resistance zones. Traders can display all price cluster centers, the nearest K-Means zone, or separate support and resistance lines. Raw, Smooth, and Locked Steps modes control how quickly the zones respond to new price data, while the nearest line changes color according to the detected bullish, bearish, or ranging market state. A Stochastic moving average heatmap is also plotted between the outer zones, adding a visual layer for momentum, overbought and oversold conditions, trend strength, and changing market pressure.
The indicator also combines volatility analysis, price action recognition, cluster quality scoring, and alert conditions. The volatility engine uses normalized ATR, candle range, and return volatility to identify low-volatility compression, normal volatility, high volatility, and volatility shock. The Price Action module evaluates the latest closed candle for bullish and bearish zone breakouts, rejection patterns, momentum candles, and indecision near a clustered price level. A dedicated Quality and Reliability section then measures zone strength, cluster fit, zone width, price distance, and RMSE, helping traders understand whether the current machine learning calculations are strong enough for practical analysis or should be treated only as additional market context.
🔵 How to Use
The easiest way to read this indicator is not to search for one isolated green or red message. Its main value comes from combining several layers of market information: K-Means market state classification, adaptive price zones, price action, volatility conditions, and calculation quality. Each module answers a different question, and the strongest setups usually appear when several modules point in the same direction.
Start with the Market State row in the analysis table. This module applies multidimensional K-Means clustering to trend bias, trend slope, and relative volume pressure. The current cluster shows where the latest market data has been assigned, while the dominant cluster represents the most frequent cluster across the selected state window. The Strength value shows how dominant that cluster is within the recent sample.
The Market State analysis can return the following conditions :
Active Bullish Trend : Positive trend structure supported by stronger relative volume.
Soft Bullish Trend : Positive directional structure, but with weaker participation or less convincing momentum.
Active Bearish Trend : Negative trend structure supported by stronger relative volume.
Soft Bearish Trend : Bearish directional structure that still requires confirmation.
Neutral Range : Trend bias and slope are not strong enough to define a clear direction.
Low-Volume Range : Sideways structure accompanied by relatively weak volume participation.
The distinction between the current and dominant cluster is important. A single large candle can move the current data point into another cluster, but the dominant state may remain unchanged if the broader recent structure still belongs to the previous market regime. This can help prevent every temporary spike, pullback, or abnormal candle from being interpreted as a complete trend reversal.
The next section is Price Zones. Here, K-Means clustering is applied to historical pivot levels, sampled highs, and sampled lows. Instead of drawing a level from only one swing point, the algorithm groups similar historical prices and calculates a center for each price cluster. These cluster centers become adaptive K-Means price zones that may act as support, resistance, breakout references, or reaction areas.
The table displays :
Near : The cluster currently closest to price.
Strength : The percentage of sampled price levels assigned to the nearest cluster.
Nearest : The closest stabilized K-Means zone.
Support : The nearest valid cluster center below the market.
Resistance : The nearest valid cluster center above the market.
A higher Zone Strength means a larger share of the sampled levels belongs to that cluster. However, this should not be interpreted as a guaranteed support or resistance level. It simply shows that more historical observations were grouped around the same price area.
On the chart, users can choose between three visual approaches. Show All K-Means Zone Centers plots the complete set of clustered price levels. Show Nearest Zone displays only the closest stabilized level, while Show K-Means Support/Resistance plots the nearest support and resistance separately.
The nearest line changes color with the detected market state :
Green indicates a bullish market state.
Red indicates a bearish market state.
Blue indicates a neutral or ranging market state.
The zone lines can also be displayed in Raw, Smooth, or Locked Steps mode. Raw mode follows newly calculated cluster centers directly. Smooth mode gradually moves the plotted level toward the new center, creating a more stable visual structure. Locked Steps mode keeps the previous level in place until the new cluster center has moved by a meaningful ATR-based distance.
Between the outer K-Means zones, the indicator draws a Stochastic Moving Average Heatmap. This heatmap is based on a 100-period Stochastic value smoothed with a 50-period exponential moving average. Lower smoothed Stochastic values appear toward the blue and purple side of the color range, middle values move through cyan and green, and higher values progress toward yellow, orange, and red. The heatmap should be read as a visual momentum layer rather than as a standalone buy or sell signal.
The Price Action row studies candle structure in relation to the nearest K-Means zone and recent price behavior. It uses the candle body, upper wick, lower wick, previous high, previous low, and the location of the nearest zone to identify several possible conditions:
Bullish or bearish zone breakout.
Bullish or bearish rejection from a zone.
Bullish or bearish momentum candle.
Indecision at a K-Means zone.
General indecision.
No clear price action.
The Body, Upper Wick Ratio, and Lower Wick Ratio values represent the relative size of the candle body, upper wick, and lower wick compared with the candle’s total range. These values help explain why the indicator classified a candle as momentum, rejection, or indecision. Price Action should always be read together with Market State and Volatility. For example, a bullish momentum candle inside a bearish market state does not automatically create a bullish setup.
The Volatility module runs a separate K-Means model using normalized ATR, candle range percentage, and return volatility. The clustered volatility data is then used to identify four practical market conditions:
Low Volatility Compression : Market movement has contracted and a future expansion may develop;
Normal Volatility : Current movement is close to its recent reference level;
High Volatility : Price movement is elevated and may require smaller position size or wider risk parameters;
Volatility Shock : Abnormal expansion is present, making immediate entries more sensitive to slippage, unstable movement, and rapid reversals.
Volatility acts as a risk filter for the rest of the analysis. Even when Market State and Price Action point in the same direction, a High Volatility or Volatility Shock reading should reduce the confidence placed on an immediate entry.
Finally, review the Quality row. This section provides an internal assessment of how compact, representative, and consistent the current K-Means calculations are. It does not measure future profitability or win rate. Instead, it evaluates the statistical structure of the active price clusters.
The main values include :
Price Q : A combined score based on zone strength, width, fit, and price distance;
Trust : A weighted score combining price-zone quality, market-state dominance, and volatility-cluster dominance;
Fit RMSE : The normalized root mean squared error of the price clusters;
Width : The average dispersion of the nearest cluster around its center;
Reliability : A descriptive grade derived from the internal Trust score.
A narrow cluster with reasonable strength and lower fitting error will usually receive a better score than a wide, weak, or poorly fitted cluster. Use this section to decide how much weight should be given to the current analysis. A weak Quality score does not make the chart unusable, but it suggests that the levels and classifications should be treated as secondary context.
🟣 Bullish Market Reading
A bullish setup becomes more meaningful when the market state, K-Means zones, candle behavior, volatility, and quality readings support the same interpretation.
Check the Market State first : An Active Bullish Trend indicates stronger bullish structure and relative participation. A Soft Bullish Trend still favors the upside, but entries should normally wait for additional confirmation.
Locate price relative to the nearest zone : When price is above the nearest K-Means zone, that level may become an adaptive support reference. A pullback toward the green nearest-zone line can be watched for continuation or rejection behavior.
Look for bullish price action : A Bullish Rejection From Zone suggests that price tested a clustered level and closed with a stronger lower-wick reaction. A Bullish Zone Breakout shows that the candle crossed above the zone with a sufficiently large body. A Bullish Momentum Candle confirms upward pressure, but it is more useful when the Market State is already bullish.
Use the support line as a reference, not an automatic entry : The K-Means support level can help define the area where bullish structure remains valid. A decisive move below it may weaken the long scenario, especially if the Market State also changes.
Confirm volatility conditions : Normal Volatility is generally easier to manage than High Volatility or Volatility Shock. During compression, traders may wait for a confirmed breakout rather than entering before expansion begins.
Review Quality and Reliability : Stronger Quality, Trust, and Zone Strength readings increase the internal consistency of the analysis. Weak scores suggest that the zone may be broad, poorly fitted, or based on a less concentrated cluster.
A practical bullish sequence may therefore look like this: the table shows a Soft or Active Bullish Trend, price remains above or retests a green K-Means zone, a bullish rejection or breakout appears, volatility is not classified as a shock, and Quality remains acceptable. None of these elements guarantees continuation, but their alignment creates a clearer bullish context than any single reading alone.
🟣 Bearish Market Reading
Bearish analysis follows the same process in reverse. The objective is to identify whether downward market structure, clustered resistance, candle behavior, and volatility are supporting the same scenario.
Begin with the Market State : An Active Bearish Trend represents stronger negative bias, slope, and relative volume pressure. A Soft Bearish Trend favors short-side analysis but still requires confirmation before treating the move as established.
Observe price relative to the nearest zone : When price is below the nearest K-Means zone, that level may act as an adaptive resistance reference. A return toward the red nearest-zone line can be monitored for rejection or continuation.
Wait for bearish price action : A Bearish Rejection From Zone appears when price tests a clustered area and forms a stronger upper-wick reaction. A Bearish Zone Breakout indicates that price has crossed below the zone with a sufficiently large bearish body. A Bearish Momentum Candle carries more weight when the broader Market State is already bearish.
Use the resistance line to define context : The K-Means resistance level can help identify where bearish continuation remains structurally reasonable. A sustained break above it may weaken the short scenario, particularly if Market State also shifts toward bullish or neutral conditions.
Do not ignore volatility warnings : A bearish candle during Volatility Shock may be followed by a sharp continuation, but it can also produce rapid retracement and unstable execution. In this condition, the indicator explicitly favors additional confirmation or reduced risk.
Check cluster quality before relying on the level : A weak or wide price cluster may produce a less precise resistance reference. Higher Quality and Reliability readings indicate a more compact and internally consistent zone, not a guaranteed bearish outcome.
A clearer bearish sequence may include a Soft or Active Bearish Trend, price trading below or retesting a red K-Means zone, bearish rejection or breakout behavior, manageable volatility, and an acceptable Quality score. When these components disagree, for example, a bullish momentum candle inside a bearish trend, the table should be read as a warning that momentum alone is not enough to confirm a reversal.
The built-in alert conditions can be used to monitor bullish and bearish K-Means zone breakouts and rejections. Alerts are most useful as notifications that a specific price-action condition has appeared; the final interpretation should still include Market State, Volatility, zone position, and Quality before any trading decision is made.
🔵 Settings
🟣 K-Means Engine Settings
Market State Lookback : Number of recent bars used to cluster trend bias, slope, and relative volume for market-state classification.
Price Zone Lookback : Number of recent bars used to build K-Means price zones from pivots, highs, and lows.
Volatility Lookback : Number of recent bars used to cluster ATR percentage, candle range, and return volatility.
Market State Clusters : Number of clusters used by the Market State model.
Price Zone Clusters : Number of price clusters used to calculate adaptive zone centers.
Volatility Clusters : Number of clusters used by the Volatility model.
Max K-Means Iterations : Maximum number of center-update cycles allowed during each clustering calculation.
Dominant State Window : Number of recent cluster assignments used to determine the dominant market state.
Fast Volatility State Window : Number of recent volatility assignments used to determine the dominant short-term volatility cluster.
Convergence Tolerance : Minimum center movement required to continue the K-Means iteration; lower values increase precision but may require more processing.
🟣 Price Zone Settings
Pivot Length : Number of bars used on each side of a candle to confirm pivot highs and pivot lows.
High/Low Sampling Step : Controls how frequently historical highs and lows are added to the price-zone dataset; lower values use more samples.
Minimum Near-Zone Distance (%) : Minimum percentage distance used to classify price as testing a K-Means zone.
🟣 Execution Control Settings
Historical Calculation Bars : Number of recent historical bars on which calculations and visual outputs are processed.
Refresh Every N Bars : Runs the main K-Means modules once every selected number of bars and always updates them on the latest bar.
🟣 Zone Stabilizer Settings
Zone Plot Mode : Selects how zone lines are displayed: Raw follows new centers directly, Smooth moves gradually, and Locked Steps updates only after a meaningful price shift.
Zone Smooth Length : Controls the smoothing speed in Smooth mode; higher values produce slower and more stable zone movement.
Zone Lock ATR Multiplier : Defines the minimum ATR-based movement required before a zone updates in Locked Steps mode.
Nearest Zone Switch Margin ATR : Prevents frequent switching between nearby zones by requiring the new zone to be closer by an ATR-based margin.
🟣 Display Settings
Show Analysis Table : Shows or hides the market analysis table.
Table Text Size : Sets the size used inside the table.
Table Position : Selects the table location on the chart.
Show All K-Means Zone Centers : Displays all calculated K-Means price-zone centers.
Show Nearest Zone : Displays the stabilized zone closest to the current price, colored by the detected market state.
Show K-Means Support/Resistance : Displays the nearest clustered support below price and resistance above price.
🔵 Conclusion
This indicator brings K-Means clustering, market state analysis, adaptive price zones, volatility classification, and price action context into one structured workflow. Instead of reducing the chart to a single signal, it separates the market into several readable layers: directional behavior, clustered support and resistance areas, candle reactions, volatility conditions, and the internal quality of the current calculations. This makes it easier to understand whether price is trending, ranging, testing a K-Means zone, reacting to a clustered level, or moving through an unstable volatility phase.
Its strongest use comes from confirmation rather than prediction. A bullish or bearish reading becomes more meaningful when the Market State, nearest K-Means zone, Price Action module, Volatility analysis, and Quality score support the same scenario. When these components disagree, the table highlights that uncertainty instead of hiding it. Used this way, the tool works as a machine learning market analysis framework that helps organize recent price data, compare changing market regimes, and identify areas where further confirmation is still required. Indicator

Strong Tech Stocks Screener | ProjectSyndicateStrong Tech Stocks Screener turns dozens of charts into a single institutional-style dashboard, ranking a curated universe of 40 leading tech, AI, and semiconductor names by performance across six timeframes and scoring each one on professional-grade risk metrics — Beta, Sharpe, Sortino, Omega, Z-Score, and Kelly — so you can find the leaders and weigh their risk-adjusted quality at a glance, all on one clean, sortable panel. Every figure is computed live on the daily timeframe from real price history, not hard-coded, so the board reflects the market as it actually is right now.
📊 Curated 40-Name Tech Universe — the screener watches a hand-picked list of 40 high-momentum tech, AI, and semiconductor stocks in one place. Instead of flipping through forty charts, you see every name's performance and risk profile side by side and immediately spot who is leading and who is rolling over.
🗓️ Six-Timeframe Performance — each stock is tracked across Week, Month, Quarter, 6-Month, 12-Month, and Year-to-Date returns, so you can separate a one-week pop from a genuine long-run trend and see momentum building or fading across horizons in a single row.
🧮 Institutional Risk Metrics, Done Properly — beyond raw returns, every name is scored on Sharpe (excess return per unit of total volatility), Sortino (return per unit of downside risk only), Omega (probability-weighted gains versus losses above the risk-free threshold), Z-Score (how stretched the recent move is in standard deviations), and the Kelly fraction (a theoretical optimal-sizing read from return and variance). The stats are annualized from daily returns over a rolling window with a configurable risk-free rate, so the risk picture is consistent and comparable across the whole list.
🎯 Basket-Relative Beta — Beta is measured against an equal-weight basket of the 40 names in the screener, so it tells you how a stock moves relative to this specific tech/AI cohort rather than a broad index. Beta above 1 swings harder than the group; below 1 is steadier. You control the lookback length used for the beta and correlation calculation.
🌡️ Annualized Weekly Volatility — a dedicated Wk Vol column annualizes the standard deviation of recent weekly returns, giving you a fast read on how violent each name's price action is before you size into it.
🔀 Dynamic Sorting — sort the entire board by any of the six performance columns with a single setting. Rank by YTD to find the year's leaders, by Week to catch what is moving now, or by any horizon in between — the table re-ranks instantly.
🎨 Bloomberg-Amber Theme with Color-Coded Strength — a clean amber-on-black dashboard with a multi-level gradient that runs from bright amber on the strongest gains through to deep red on the steepest losses, so strength and weakness jump out the moment you look at the panel.
🧩 Fully Customizable Dashboard — place the table anywhere on the chart (Top / Middle / Bottom paired with Left / Center / Right), choose your text size (Tiny / Small / Normal / Large), set the sort column, the beta length, and the risk-free rate and periods — all from the settings menu, no code editing required.
🔒 Daily-Timeframe Lock — the screener is built for daily data and will prompt you to switch if you load it on a lower timeframe, so the returns, volatility, and ratios are always calculated on the basis they are designed for.
⚡ Lightweight and Efficient — the whole 40-name board is built from a tight, well-organized script that runs smoothly on PulseWire, with a clean merged title heading and an alternating-row layout for easy reading.
🎯 Why this is different — most watchlists show you price and maybe a percentage move. This screener puts performance and a full institutional risk stack — Sharpe, Sortino, Omega, Z-Score, Kelly, Beta, and annualized volatility — for forty leading tech names on one sortable, color-coded panel, so you are ranking opportunities by risk-adjusted quality, not just chasing the biggest green number.
🚀 Where to use it — apply it to any daily chart to monitor the tech/AI/semiconductor leadership group as a whole. Use it for top-down scanning, rotation ideas, and risk screening before you drill into an individual name's chart for entry timing.
⚠️ Important — this is a research and decision-support dashboard, not a buy/sell system, and it makes no performance guarantees. All figures are historical and descriptive, computed from past price data, and say nothing certain about the future. Risk metrics like Sharpe, Sortino, Omega, Z-Score, and Kelly are simplified, assumption-based estimates and should inform your judgment, not replace it. Always pair the screener with your own analysis and risk management. Indicator

Adaptive Lorentzian Classification [Quantum Algo]Quantum ML Engine — Adaptive Lorentzian Classification
█ OVERVIEW
Quantum ML Engine is a machine-learning classifier that predicts the direction of price over a configurable horizon using an Approximate Nearest Neighbors (ANN) search across historical feature vectors. Instead of relying on a single oscillator, it compares the current bar's "fingerprint" — a vector of up to six normalized features — against thousands of past bars, finds the most similar market conditions, and lets those historical outcomes vote on what is likely to happen next.
By default the engine measures similarity with Lorentzian distance, log(1 + |Δ|), rather than Euclidean distance. Market data is heavily distorted around major events (CPI prints, FOMC, black swans), and Lorentzian distance naturally compresses these outliers — analogous to how mass warps space-time — so a single extreme bar cannot dominate the neighbor selection.
This is an original, fully self-contained implementation written from scratch with zero library imports. The concept of applying Lorentzian distance to kNN classification on charts was pioneered in the open-source work of @jdehorty (Machine Learning: Lorentzian Classification), building on earlier kNN studies by @capissimo. Full credit to both for the foundational research. This script does not reuse their code; it re-derives the approach independently and extends it in the ways described below.
█ WHAT IS DIFFERENT IN THIS IMPLEMENTATION
1 — Time-aligned training set
Each training sample pairs the feature vector recorded AT a given bar with the realized outcome over the following H bars. Features and labels are stored on the same time axis, so the classifier learns from correctly matched cause-and-effect pairs. There is no lookahead: a sample only enters the training set once its outcome is fully realized.
2 — ATR neutral-zone labeling
Historical moves smaller than a configurable multiple of ATR are labeled NEUTRAL instead of long/short. Sideways noise therefore never teaches the model a false directional lesson. Set the multiplier to 0 to disable.
3 — Six engineered features with importance weights
RSI, WaveTrend, CCI, ADX, MFI (volume flow) and Fisher Transform, each normalized to a common 0–1 scale. Every feature slot has its own weight input, so you can tell the engine which dimensions matter more for your market without removing features entirely.
4 — Four selectable distance metrics
Lorentzian (default), Manhattan, Euclidean, and a 50/50 Lorentzian-Manhattan Hybrid. Switching metrics changes the geometry of the neighborhood and is a powerful tuning lever per asset class.
5 — Distance-weighted voting with a confidence score
Closer neighbors vote louder (weight = 1 / (1 + distance)). The agreement between neighbors is expressed as a 0–100% confidence value printed on every bar, and a minimum-confidence gate suppresses low-conviction signals entirely.
6 — Adaptive K
The neighbor count automatically shrinks (up to 40%) when volatility ranks high over the last 100 bars, making the model more reactive in fast markets, and expands back in quiet regimes for stability. Can be disabled for a fixed K.
7 — Sliding training window
The engine always trains on the most recent N bars rather than the oldest bars in chart history, so the model reflects current market structure.
8 — Configurable prediction horizon
The training/holding horizon is an input (1–20 bars) instead of a hardcoded constant.
9 — Three exit modes
Fixed-horizon exits, dynamic kernel-slope exits, and an optional ATR trailing stop with the stop level plotted on the chart.
10 — Higher-timeframe confluence filter
Optionally require price to be above (longs) or below (shorts) an EMA on a higher timeframe of your choice.
█ HOW IT WORKS
1. On every bar, six features are computed and normalized.
2. The bar's feature vector is compared against samples inside the sliding training window, sampled with a minimum chronological spacing (default 4 bars) so neighbors come from distinct market episodes rather than one cluster.
3. A monotonic distance threshold maintains a stable pool of approximate nearest neighbors; when the pool exceeds K, the threshold resets to the 75th-percentile distance, allowing genuinely closer samples to rotate in over time.
4. Neighbors vote long / short / neutral, weighted by proximity. The weighted sum becomes the prediction; the degree of agreement becomes the confidence.
5. The raw signal is then passed through optional filters: volatility regime (recent ATR vs long-run ATR), trend regime (EMA separation normalized by ATR), ADX, EMA/SMA trend, higher-timeframe trend, and a Nadaraya-Watson kernel regression filter (rational quadratic estimate with a Gaussian crossover mode for smoother color transitions).
6. Entries print only when the ML signal, the confidence gate, and all enabled filters agree.
█ SETTINGS GUIDE
General — source, training window size, prediction horizon, neutral-zone width.
ML Engine — K, adaptive K toggle, chronological spacing, distance metric, distance weighting, minimum confidence.
Feature Engineering — feature type, parameters and weight for each of the six slots.
Filters — volatility, regime, ADX, EMA/SMA, higher-timeframe confluence.
Kernel — lookback, relative weighting, regression level, lag, smoothing mode.
Exits — fixed vs dynamic exits, ATR trailing stop and multiplier.
Display — bar colors, prediction labels (value + confidence), dashboard, color compression.
█ DASHBOARD
The on-chart panel shows the live signal, prediction confidence, current adaptive K, volatility and trend regime states, kernel bias, and a calibration win-rate. The calibration statistic simply checks whether price moved in the predicted direction over the horizon after each signal. It exists ONLY to give feedback while tuning features — it is not a backtest, includes no costs or risk management, and must not be treated as a performance claim.
█ USAGE NOTES
— Works on any symbol and timeframe; intraday (15m–4H) and daily charts are typical starting points. Crypto, FX, indices and equities all behave differently — retune the features and metric per market.
— Higher minimum confidence = fewer but more selective signals. Raising chronological spacing diversifies neighbors on lower timeframes.
— Signals are evaluated on bar close. Like any bar-close logic, the in-progress bar can change until it closes.
— Best used as a confluence layer inside a complete trading plan with your own risk management, not as a standalone buy/sell system.
█ CREDITS
Concept inspiration: @jdehorty (Machine Learning: Lorentzian Classification) and @capissimo (kNN implementations). This script is an independent, original implementation with the extensions listed above.
█ DISCLAIMER
This script is provided for educational and informational purposes only. It is not financial advice, and past behavior — including the on-chart calibration statistics — does not guarantee future results. Trading involves substantial risk of loss. Always do your own research and manage risk responsibly. Indicator

AI Trend Detector | Adaptive Signals [NeuraLib Machine Learning]🔷 AI Trend Detector | Adaptive Signals
AI Trend Detector is a NeuraLib-powered Machine Learning indicator. It trains a compact supervised neural model on confirmed historical movement, then uses the current market state to estimate Bear , Neutral , and Bull pressure.
The model output is converted into a clean visual system:
Trend Oscillator : A 0-100 pressure gauge. Lower values suggest bullish pressure or oversold conditions. Higher values suggest bearish pressure or overbought conditions.
Adaptive MA Cloud : A main-chart adaptive moving average with an AI-biased cloud that expands as model pressure moves away from neutral.
Confirmed Triangles : Optional chart markers for overbought and oversold interactions, with modes for zone entry, zone exit, or confirmed rotation inside a zone.
Dashboard : A compact readout showing the current state, signal value and confidence.
Triangle Alerts : Alert conditions tied to the same confirmed marker logic shown on the chart.
Directional Confidence : An optional 0-100 line showing the stronger directional model probability, calculated from the larger of Bull or Bear pressure. It does not include Neutral probability, so it reflects directional conviction rather than overall model certainty.
This is not a fixed crossover system. The signals are the visual layer of a model-driven trend pressure engine.
---
🔷 How The Model Learns
Each bar contributes a compact feature row based on price movement, adaptive MA context, and distance from the adaptive baseline. NeuraLib stores these rows in a rolling dataset, normalizes the inputs, and trains the model on recent time-series windows.
The model is trained as a 3-class classifier:
Bear
Neutral
Bull
Historical training examples use future-resolved movement to create their target class, but only after that movement has already occurred. This is the supervised learning setup: the model learns from completed historical outcomes, then applies its learned weights to the current live feature window.
The exposed settings allow users to experiment with model size, learning rate, training frequency, smoothing, trend horizon, and signal behavior.
---
🔷 Model Architecture
The model uses a compact temporal classification architecture:
Flattened state window : Recent feature rows are combined into one temporal input.
Temporal convolution stack : Conv1D-style layers extract short-term structure from the recent market sequence.
Global average pooling : The temporal output is compressed into a compact state representation.
Dense classifier head : One or two dense layers process the pooled state.
Three output logits : The model produces Bear, Neutral, and Bull logits, which are converted into display probabilities.
This keeps the model small enough for Pine Script while still giving it a true sequence-learning structure rather than a simple crossover or rule-based signal engine.
---
🔷 Reading The Signals
The oscillator is intentionally inverted for intuitive market reading:
Low values : Oversold or bullish pressure.
Mid values : Balanced or neutral pressure.
High values : Overbought or bearish pressure.
Triangles can be configured through the Triangle trigger setting:
Crossing into : Prints when the oscillator crosses into an overbought or oversold zone.
Going out of : Prints when the oscillator exits an overbought or oversold zone.
Rotation inside zone : Prints when the signal forms a confirmed turn while still inside the zone.
In rotation mode, Rotation confirmation controls how many bars must pass without breaking the candidate peak or trough before the marker is accepted. Rotation triangles print on the confirmation bar, not on the older pivot bar.
The adaptive MA cloud is visual only. The model is not trained on the shifted cloud edge. The cloud simply applies model pressure around the adaptive MA baseline.
---
⚠️ Repainting And Signal Timing
The training and signal system is designed around confirmed bars:
Training rows are pushed on confirmed bars.
Triangle signals are gated with barstate.isconfirmed .
Rotation markers print on the confirmation bar.
No negative plot offsets are used to move markers into the past.
The smoothing path uses current and past values only.
Because this model does not train on the full price history, but instead learns from the most recent N bars, repainting may occur when the script is reloaded at a later date. This happens because the model may begin training from a different market environment.
To help preserve the original model state, adjust the Historical Train Window setting to account for any new bars that have been added since the original run.
---
⚠️ Limitations
Machine Learning inside Pine Script is powerful, but it is still bounded by PulseWire's execution model.
The model is compact by design.
Training history is bounded for performance.
Changing hyperparameters rebuilds the model.
Signals depend on the chosen horizon, threshold, smoothing, and triangle mode.
The model estimates directional pressure. It does not know your entries, exits, risk, fees, or position sizing.
This indicator is best treated as a model-based market pressure tool, not as a complete trading system by itself.
This indicator is powered by the NeuraLib Deep Learning Runtime
Disclaimer: This indicator is an analytical and educational tool. It does not guarantee future results, signal accuracy, or financial gain. Past behavior does not ensure future behavior. Use it as one component in a broader trading process, under your own responsibility. Conceptual architecture and quantitative development by Alien_Algorithms.
Indicator

Machine Learning: Volume-Weighted Mean Reversion [Dots3Red]█ MACHINE LEARNING: VOLUME-WEIGHTED MEARN REVERSION KERNEL REGRESSION
Nadaraya-Watson kernel regression is a non-parametric machine learning method. Unlike moving averages which apply fixed, predefined weights to historical bars, kernel regression derives each bar's weight from a mathematical function — the kernel — that measures how relevant that bar is to the current estimate. No hardcoded coefficients. No assumed shape. The model adapts purely from the data.
This script introduces a fundamental extension to the standard method: volume as a second weighting dimension . The result is a regression curve that gravitates toward price levels where real market participation occurred — not toward price levels where a clock happened to tick.
█ WHY KERNEL REGRESSION IS MACHINE LEARNING
The term machine learning describes algorithms that derive structure from data rather than from manually specified rules. Kernel regression satisfies this definition formally. The estimator computes:
ŷ = Σ [ w(i) × close ] / Σ
where each weight w(i) is determined by a kernel function — not by the programmer. The model decides, from the data, how much each historical bar should influence the current estimate. This is the same mathematical family as K-Nearest Neighbors, which weights neighbors by proximity. It is cited as a foundational non-parametric ML method in Bishop (2006) and Hastie et al. (2009), and is described as an attention mechanism in deep learning literature — the same concept behind transformer models. The claim is accurate, not cosmetic.
█ THE CORE INNOVATION — VOLUME WEIGHTING
Every existing Nadaraya-Watson implementation on PulseWire uses a pure time kernel:
• Standard NW: w(i) = K(i/h)
This means a bar with 10,000 shares traded and a bar with 10,000,000 shares traded receive identical weight if they are the same number of bars away. A thin overnight drift and a high-volume institutional session influence the regression equally. That is statistically incorrect — volume is a direct measure of how much informational content a price bar carries.
This script uses a volume-weighted kernel:
• This script: w(i) = vol_norm(i) × K(i/h)
where vol_norm(i) is the bar's volume normalized against the peak volume in the lookback window, raised to a configurable power exponent. The regression estimate is therefore:
ŷ = Σ [ vol_norm(i) × K(i/h) × close ] / Σ
High-volume bars anchor the curve. Low-volume bars — thin sessions, overnight drift, holiday trading — contribute minimally. The regression finds where the market actually agreed on price, not just where the clock recorded a tick.
█ THREE KERNEL FUNCTIONS
All three apply the same volume weighting. The choice controls how rapidly influence decays with time distance:
• Rational Quadratic (default) — heavier tail than Gaussian. Bars from 40–60 periods ago still contribute meaningfully if they had high volume. Best for daily and weekly charts where old high-volume levels remain structurally relevant.
• Gaussian — standard bell curve decay. Weight drops sharply with distance. Best for intraday charts where recency matters more than historical anchors.
• Epanechnikov — hard cutoff at the bandwidth boundary. Anything beyond h periods receives zero weight. Produces the most locally sensitive regression. Best for fast charts requiring tight responsiveness.
█ SIGNAL LOGIC
The envelope bands are placed at a configurable multiple of ATR, standard deviation, or a fixed percentage above and below the regression line. Three band width methods are available to match different volatility contexts.
Two signal modes are available:
• Reversion mode (default) — a signal fires when price crosses back through the band after an extension. The ▲ label appears on the bar where price returns inside the lower band. The ▼ label appears on the bar where price returns inside the upper band. This confirms reversion has begun rather than anticipating it.
• Extension mode — enable Signal on extension close to fire a signal the moment price closes outside a band. This is an early warning — useful for alerts before the reversion bar arrives.
Additional signal filters: minimum bars between signals to prevent repeat firing, optional slope direction gate so signals only fire when the regression slope agrees with the signal direction.
█ WHAT YOU SEE ON THE CHART
Regression line
The volume-weighted fair value curve. Cyan when slope is rising, magenta when falling. This is where the model estimates price should be given the recent history of high-participation price levels.
Envelope bands
Upper and lower boundaries built from ATR, standard deviation, or a fixed percentage. The upper band is tinted red — resistance zone. The lower band is tinted green — support zone.
Bar coloring — 4 states
• Bright red — price closed above the upper band. Extended, statistically stretched above fair value.
• Bright green — price closed below the lower band. Extended, statistically stretched below fair value.
• Dim silver — price inside bands, regression rising or falling, i.e normal bullish or bearish context.
The contrast between fully saturated outside-band bars and dimmed inside-band bars makes overextension immediately visible without reading the scale.
Signal labels
▲ REVERT or ▼ REVERT with VW=XX% showing the volume weight of the signal bar. A signal at VW=85% fired on a high-participation bar. A signal at VW=9% fired on a thin bar — lower confidence.
Signal bar highlighting
Two additional layers available: a background flash on the signal bar and a thick vertical line through the bar's full range. Both are independently toggleable. The vertical line uses width=4 — the maximum Pine Script allows — making the signal bar visually distinct even when zoomed out.
Dashboard
Displays: current regression value, slope direction, band width, Bar Vol Weight meter (▰▰▰▱▱▱) showing how much influence the current bar has on the regression, active kernel type, volume weighting status, percentage distance from the regression midline, and non-repainting mode status.
█ NON-REPAINTING
When Non-Repainting Mode is enabled (default), all calculations use a bar offset. The current bar's close does not enter its own regression estimate. Historical signals visible on closed bars will not change as new bars form. Disable this to see a predictive (repainting) version where the current bar participates in its own estimate — useful for visual exploration but not recommended for backtesting or alerts.
█ HOW TO USE
Core use case — mean reversion
This is a mean reversion tool. It works best when price is oscillating rather than trending directionally. The recommended workflow:
1 — Confirm a ranging regime with a separate regime classifier before acting on signals.
2 — Wait for price to reach or pierce the upper or lower band (bars turn bright red or green).
3 — Check the VW% in the signal label. Higher volume weight on the signal bar = higher confidence.
4 — Enter on the reversion signal (▲ or ▼ label). Stop beyond the wick of the signal bar.
5 — Target the regression midline as the primary exit. The % from mid dashboard row tracks progress in real time.
Timeframe guidance
The volume-weighting advantage increases with timeframe because higher timeframes produce more meaningful volume data per bar. H4 and Daily are the strongest timeframes for this tool. For intraday use, reduce the Volume Weight Power to 0.3–0.5 to soften the impact of individual volume spikes.
Quick-start settings by asset class
• Stocks daily: Window=100, Bandwidth=8, Vol Power=1.0, ATR×2.0
• Crypto daily: Window=80, Bandwidth=6, Vol Power=0.7, ATR×1.8
• Forex H4: Window=100, Bandwidth=10, Vol Power=1.0, ATR×1.5
• Indices H1: Window=120, Bandwidth=12, Vol Power=0.8, Stdev×2.0
█ SETTINGS REFERENCE
Kernel Settings
• Lookback Window — number of historical bars in the regression. Larger = smoother, more lag.
• Bandwidth (h) — controls how fast kernel weight decays with time. Higher = older bars still contribute.
• Kernel Type — Gaussian / Rational Quadratic / Epanechnikov. See kernel section above.
• RQ Alpha (α) — Rational Quadratic only. Lower = smoother mixture of length scales.
• Non-Repainting Mode — uses offset. Recommended ON for backtesting.
Volume Weighting
• Enable Volume Weighting — toggle the core innovation on or off. OFF = standard NW.
• Volume Normalization Window — peak volume reference window. Match or exceed the lookback window.
• Volume Weight Power — exponent on the volume weight. 1.0 = linear. 2.0 = quadratic. 0.5 = softer.
• Volume Weight Floor — minimum weight for any bar. Prevents zero-volume bars from being ignored entirely.
Envelope Bands
• Band Width Method — ATR (volatility-adaptive), Stdev (statistical), or Percent (fixed).
• ATR Length — period for ATR calculation.
• ATR / Stdev Mult — multiplier applied to ATR or standard deviation.
• Percent Offset % — used when Percent method is selected.
Signals
• Signal on band crossover — enable signals on band cross events.
• Signal on extension close — fire signal when price closes outside a band (early warning mode).
• Require slope change — only signal when regression slope direction agrees.
• Min bars between signals — gap guard to prevent repeat signals.
Visuals
• Dashboard — regression stats and live metrics table.
• Signal labels — ▲/▼ REVERT labels with volume weight percentage.
• Band fill — fill between upper and lower bands.
• Background flash — bright background color on signal bars.
• Vertical line on signal bar — thick line through full bar height at signal.
• Large dot marker — additional plotchar layer on signal bars.
• Dashboard position — Top Right / Top Left / Bottom Right / Bottom Left.
█ ALERTS
Seven alert conditions are available:
• Long signal — reversion through lower band
• Short signal — reversion through upper band
• Any signal — either direction
• Extended below lower band — early warning before reversion fires
• Extended above upper band — early warning before reversion fires
• Regression slope turned bullish
• Regression slope turned bearish
█ DISCLAIMER
This indicator is a decision-support tool. It does not constitute financial advice and does not guarantee future results. Past statistical patterns do not predict future price behavior. Always use proper risk management.
Method: Nadaraya-Watson Kernel Regression (Non-Parametric ML)
Innovation: Volume × Time Kernel Weighting
Kernels: Gaussian · Rational Quadratic · Epanechnikov
Signals: Mean Reversion (band crossover or extension)
Repainting: Configurable — non-repainting mode available Indicator

Neural Weight Oscillator (Zeiierman)█ Overview
The Neural Weight Oscillator (Zeiierman) is an adaptive multi-factor oscillator that combines structured decision-making with dynamic market learning.
The script analyzes three core market behaviors: Trend, Mean Reversion, and Momentum. Instead of treating these components equally, the oscillator uses the Best-Worst Method (BWM) to determine which market behavior should have the greatest influence under current market conditions.
An adaptive training layer then studies historical market reactions and gradually amplifies the features that have recently produced the strongest directional behavior.
The result is a hybrid oscillator that blends:
Human-defined market logic
Adaptive feature weighting
Multi-factor momentum analysis
Dynamic market learning
Unlike traditional oscillators that rely on static formulas, the Neural Weight Oscillator continuously adjusts its internal structure based on both trader-defined weighting preferences and changing market behavior.
█ How It Works
⚪ Market Structure Engine
The oscillator builds its analysis from three independent behavioral models: Trend, Mean Reversion, and Momentum.
The Trend component measures structural direction by comparing the fast EMA against the slow EMA, then adds the EMA slope to capture acceleration.
trendSpread = (emaFast - emaSlow) / atr
trendSlope = (emaFast - emaFast ) / atr
trendScore = normalize(trendSpread + trendSlope, -2.5, 2.5)
The Mean Reversion component measures stretched conditions using RSI exhaustion and statistical deviation from the market mean.
zScore = dev == 0 ? 0 : (close - basis) / dev
meanScore = (100 - rsi) * 0.5 + normalize(-zScore, -2.5, 2.5) * 0.5
The Momentum component measures directional acceleration using ROC, RSI momentum, and EMA velocity.
rocNorm = normalize(close / close - 1.0, -0.05, 0.05)
momentumScore = rocNorm * 0.45 + rsi * 0.35 + emaMomentum * 0.20
Each component produces its own normalized score before being blended into the final oscillator.
⚪ Best-Worst Method (BWM)
The core weighting system in the oscillator is based on the Best-Worst Method (BWM), a structured decision-making framework that creates balanced weighting relationships among multiple factors.
bestIdx = criterionIndex(bestCriterion)
worstIdx = criterionIndex(worstCriterion)
array.set(bo, bestIdx, 1.0)
array.set(ow, worstIdx, 1.0)
Instead of assigning arbitrary percentages manually, BWM allows the trader to define which market behavior matters most and which matters least. The script then automatically calculates balanced internal weights.
The process begins by selecting:
The “Best” factor → the market behavior trusted most
The “Worst” factor → the market behavior trusted least
relWeight = math.sqrt((aBW / boVal) * owVal)
The oscillator then compares all remaining factors relative to those two extremes and converts those relationships into normalized internal weights.
⚪ How To Think About The BWM Weights
The easiest way to think about BWM is:
“What type of market behavior do I trust most in the current environment?”
Different market conditions naturally favor different behaviors.
In strong directional trends , traders often prioritize Trend because structural continuation becomes the dominant force.
In choppy or range-bound markets , Mean Reversion may become more important because the market repeatedly returns back toward equilibrium.
During aggressive breakout environments , Momentum may deserve the highest weighting because acceleration becomes the primary driver.
The goal is not to find a “perfect” weight configuration, but rather to align the oscillator with the type of behavior currently dominating the market.
⚪ Adaptive Neural Training Layer
The oscillator includes an adaptive learning layer that learns how the market has recently reacted to the model’s internal features.
The script looks back at prior Trend, Mean Reversion, and Momentum feature values, then compares them to the future price reaction.
target = close / close - 1.0
targetDirection = target > 0 ? 1.0 : target < 0 ? -1.0 : 0.0
High-quality samples are ranked by how strong the move was relative to volatility.
sampleScore = math.abs(target) / qualityVol
The model then compares its internal prediction against the actual market direction and adjusts the learned feature weights over time.
pred = twTrend * s.trend + twMean * s.mean + twMomentum * s.momentum + tbias
err = pred - s.target
This allows the oscillator to gradually learn which features are producing the strongest directional behavior.
⚪ Adaptive Feature Amplification
The learned weights are converted into feature amplifiers.
trendAmplifier = 1.0 + learnTrend * blend
meanAmplifier = 1.0 + learnMean * blend
momentumAmplifier = 1.0 + learnMomentum * blend
This allows stronger features to gain more influence, while weaker features receive less influence.
█ How to Use
⚪ Reading the Oscillator
The oscillator operates between 0 and 100.
Values above 50 suggest bullish pressure dominates the market, while values below 50 suggest bearish pressure dominates.
As the oscillator moves farther away from the neutral 50 level, directional imbalance becomes stronger.
Readings above 70 typically indicate strong bullish expansion, while readings below 30 indicate strong bearish pressure. Extreme zones above 80 or below 20 may signal exhaustion conditions where reversals become more likely.
⚪ Using the BWM Weighting System
The BWM system allows traders to align the oscillator with current market behavior by controlling how much influence Trend, Mean Reversion, and Momentum should have inside the model.
Imagine the market is trending strongly upward.
You may believe:
Trend is the dominant market behavior.
Mean Reversion still matters during pullbacks.
Momentum should have the least influence.
In this case, you could choose:
Best = Trend
Worst = Momentum
You then control how strongly Trend dominates the other factors through the comparison inputs.
For example:
Best-to-Others:
Trend = 1
Mean = 3
Mom = 6
Relative-to-Worst:
Trend = 4
Mean = 2
Mom = 1
This tells the oscillator:
Trend is selected as the strongest market behavior.
Momentum is selected as the weakest market behavior.
Trend is 3x more important than Mean Reversion.
Trend is 6x more important than Momentum.
Mean Reversion is 2x more important than Momentum.
The script automatically converts these relationships into balanced internal weights.
As a result, the oscillator becomes more trend-sensitive while reducing the influence of short-term momentum fluctuations and weak counter-trend behavior.
If the market becomes highly rotational or range-bound, traders may instead increase the importance of Mean Reversion so the oscillator becomes more responsive to exhaustion and reversal conditions.
During aggressive breakout environments, increasing Momentum weighting can help the oscillator react faster to acceleration phases.
The weighting system is designed to adapt the oscillator’s personality to different market environments rather than forcing one static interpretation onto every condition.
█ Settings
Fast EMA: controls the responsiveness of the Trend and Momentum calculations.
Slow EMA: controls the structural trend baseline used throughout the oscillator.
Smoothing: controls the smoothness of the final oscillator line.
The Best and Worst: determine how the BWM weighting model prioritizes market behaviors.
Best-to-Others: define how strongly the selected Best factor dominates the remaining components.
Relative-to-Worst: define how much stronger each component is compared to the selected Worst factor.
Use Training: enables the adaptive learning layer.
Influence: controls how strongly the learned model amplifies features.
Line Impact: controls how much the adaptive model can directly influence the oscillator line itself.
-----------------
Disclaimer
The content provided in my scripts, indicators, ideas, algorithms, and systems is for educational and informational purposes only. It does not constitute financial advice, investment recommendations, or a solicitation to buy or sell any financial instruments. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
Indicator

Indicator

Ask Dr. Alex AIAsk Dr. Alex AI — Interactive Chart Intelligence for PulseWire
Ask Dr. Alex AI is an interactive chart intelligence indicator built to help traders understand what the chart is saying before making a decision. Instead of only printing a simple buy or sell label, Ask Dr. Alex AI lets the user select a question from a built-in menu and then reveals the specific chart evidence behind the answer.
This indicator is designed as a guided market assistant for traders who want clearer context around support, resistance, patterns, momentum, trend pressure, forecast bias, and trade planning.
What Makes Ask Dr. Alex AI Different
Most indicators only show signals.
Ask Dr. Alex AI answers questions.
Users can select from guided questions such as:
Is this safe to trade right now?
Am I buying from support, selling from resistance, or chasing price?
What pattern is active?
What does the next candle / 10C forecast suggest?
What is the entry, stop loss, and take-profit plan?
ALL — Show Everything
Deep Scan Mode
When a question is selected, the indicator highlights the relevant chart areas and summarizes what it sees using the Dr. Alex AI answer panel.
Core Features
Interactive Question Menu
Choose a question and the indicator reveals only the relevant chart evidence.
Dr. Alex AI Answer Panel
Provides a plain-English summary of the current market condition.
Deep Scan Mode
Unlocks deeper diagnostic checks such as:
Trend Strength
MTF Agreement
Support Bounce Check
Resistance Rejection
Pattern Quality
Forecast Conflict
Ribbon Conflict
Entry Quality
Risk / Reward
Invalidation Point
Fakeout Risk
Wilson Tangent
Full Diagnostic
Support / Resistance Intelligence
Displays major support and resistance zones, higher-timeframe levels, and whether price is reacting from a meaningful area.
Pattern Awareness
Detects and explains major active patterns such as doji at support, hammer at support, double bottom, engulfing candles, marubozu candles, breakout retests, traps, and continuation patterns.
Respect Support Bounce Mode
When price touches major support and a bullish rejection pattern appears, the system can shift from hard bearish continuation into Support Bounce Watch / Bull Watch instead of blindly forecasting into support.
Next-Candle Bias Ribbon
A five-state visual ribbon helps summarize the projected next-candle condition:
Green = Bullish
Blue = Bull Watch
Gray = Neutral
Orange = Bear Watch
Red = Bearish
10-Candle Forecast View
Shows a forward projection path based on confidence, pattern context, support/resistance, trend pressure, and active sentiment.
Trade Plan Panel
When a setup is active, the indicator can display:
Entry range
Stop loss
TP1
TP2
Risk/reward model
Setup status
Confidence and Rank Engine
Uses a multi-factor scoring system to compare bullish and bearish pressure across trend, momentum, structure, volatility, MTF alignment, candle behavior, and ribbon state.
Machine-Learning-Inspired Scoring Logic
Ask Dr. Alex AI uses adaptive, weighted, machine-learning-inspired decision logic to evaluate chart conditions and adjust the way it interprets support bounces, forecast conflicts, momentum shifts, and pattern quality. It is designed to behave like an intelligent diagnostic layer, not just a static signal generator.
How to Use
Add the indicator to your chart.
Choose a question from the Ask Dr. Alex AI menu.
Review the highlighted chart evidence.
Read the Dr. Alex AI answer panel.
Use Deep Scan Mode when you want a more detailed diagnostic breakdown.
Use ALL — Show Everything when you want the full visual system displayed at once.
Best Use Case
Ask Dr. Alex AI is best used as a decision-support and educational chart assistant. It is built to help traders slow down, identify context, avoid chasing price, respect support/resistance, and understand why a setup is active, weak, conflicted, or invalidated.
It is especially useful for traders who want the chart to answer questions such as:
“Is this actually a trade, or am I forcing it?”
“Is price bouncing from support or breaking down?”
“Why is the forecast bullish if the trend is bearish?”
“Why is the signal waiting?”
“What must happen before this setup becomes valid?”
Important Disclaimer
Ask Dr. Alex AI is for educational and informational purposes only. It does not guarantee profits, predict the future with certainty, or replace personal judgment, risk management, or professional financial advice. Trading involves risk, and users are responsible for their own trading decisions.
Indicator

NeuraLib Expansion: Advanced Model LayersNeuraLib_Models is the companion model expansion for NeuraLib .
NeuraLib provides the runtime: tensors, graph execution, datasets, scalers, losses, optimizers, training, inference, and validation tools. NeuraLib_Models builds on that foundation with higher-level neural architectures that are difficult and repetitive to write by hand.
The purpose of this expansion is to keep the main NeuraLib runtime clean, compact, and general, while giving researchers ready-to-use model families for sequence learning, attention, temporal pattern extraction, and Reinforcement Learning workflows.
----------------------------------------------------------------------------------------------------------------
🔷 HOW IT FITS INTO NEURALIB
NeuraLib_Models is built entirely on top of the public NeuraLib API. It does not replace the main runtime and it does not introduce a separate training engine.
After importing NeuraLib_Models, its fluent methods become available directly on NeuraLib `Sequential` models. The expansion alias can remain unused in the layer chain.
//@version=6
indicator("NeuraLib Models Quick Start", overlay = false, calc_bars_count = 600)
import Alien_Algorithms/NeuraLib/1 as nl
import Alien_Algorithms/NeuraLib_Models/1 as models
var nl.Sequential model = nl.sequential("advanced_model")
var float qLong = na
var float qFlat = na
var float qShort = na
if barstate.isfirst
model := model
.input(array.from(8), "sequence")
.temporalConvStack(4, 2, 2, 2, 1, 1, nl.ActivationKind.relu, 0.0, "temporal")
.globalAvgPool1d(3, 2, "pool")
.duelingQHead(4, 3, nl.ActivationKind.relu, "dueling_head")
.build(nl.rng(7))
float ret0 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret1 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret2 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret3 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float atrValue = ta.atr(14)
float atr0 = close == 0.0 ? 0.0 : atrValue / close
float atr1 = close == 0.0 ? 0.0 : atrValue / close
float atr2 = close == 0.0 ? 0.0 : atrValue / close
float atr3 = close == 0.0 ? 0.0 : atrValue / close
bool ready = not na(ret3) and not na(atr3)
if ready
nl.Tensor state = nl.vector(array.from(ret3, atr3, ret2, atr2, ret1, atr1, ret0, atr0), "state_window")
nl.Tensor qValues = model.predict(state)
qLong := qValues.get1d(0)
qFlat := qValues.get1d(1)
qShort := qValues.get1d(2)
plot(qLong, "Q long", color = color.lime, linewidth = 2)
plot(qFlat, "Q flat", color = color.gray)
plot(qShort, "Q short", color = color.red, linewidth = 2)
hline(0.0, "Zero", color = color.new(color.gray, 70))
The model is still a normal NeuraLib model. You still call `.compile()`, `.trainOnBatch()`, `.predict()`, `.evaluate()`, `.getWeightsArray()`, and `.softUpdateFrom()` from the main library.
----------------------------------------------------------------------------------------------------------------
🔷 WHY THIS EXPANSION EXISTS
The main NeuraLib library is the foundation. It exposes a graph engine powerful enough to create custom architectures, but repeatedly building LSTM gates, attention projections, residual blocks, Conv1D stacks, or Transformer paths from raw graph operations would be too verbose for everyday research.
NeuraLib_Models packages those patterns into readable blocks:
Temporal models : Conv1D blocks, temporal convolution stacks, global average pooling, and global max pooling for flattened sequence inputs.
Recurrent models : LSTM and GRU blocks for compact sequence memory.
Attention models : Self-attention, multi-head self-attention, cross-attention, Transformer encoder blocks, Transformer encoder stacks, and Transformer decoder blocks.
Residual models : Residual dense blocks for deeper feedforward paths.
Reinforcement Learning heads : Q-head blocks and dueling Q-heads for action-value style outputs.
Replay utilities : Deterministic Prioritized Experience Replay for reproducible Pine research.
Sequence helpers : Positional encoding for token, sequence, and attention workflows.
----------------------------------------------------------------------------------------------------------------
🔷 PRACTICAL EXAMPLES
🔸 Temporal Conv Model With Dueling Q-Head
This pattern is useful when a flattened sequence contains recent market states and the output represents action values.
//@version=6
indicator("NeuraLib Models Temporal Q Example", overlay = false, calc_bars_count = 600)
import Alien_Algorithms/NeuraLib/1 as nl
import Alien_Algorithms/NeuraLib_Models/1 as models
var nl.Sequential qModel = nl.sequential("temporal_q_model")
var nl.WindowDataset qDataset = nl.windowDataset(8, 3, 400, "q_rows")
var float qDown = na
var float qNeutral = na
var float qUp = na
var float qLoss = na
if barstate.isfirst
nl.CompileConfig cfg = nl.compileConfig()
cfg := cfg
.presetQValues()
.optimizer(nl.adamW(0.001))
.withTrainingGate(true)
qModel := qModel
.input(array.from(8), "state_window")
.temporalConvStack(4, 2, 2, 2, 1, 1, nl.ActivationKind.relu, 0.0, "temporal")
.globalAvgPool1d(3, 2, "pool")
.duelingQHead(4, 3, nl.ActivationKind.relu, "dueling_head")
.compile(cfg)
qDataset := qDataset
.setInputScaler(nl.ScalerKind.zScore)
.setTargetScaler(nl.ScalerKind.none)
float ret0 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret1 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret2 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret3 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret4 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float atrValue = ta.atr(14)
float atr0 = close == 0.0 ? 0.0 : atrValue / close
float atr1 = close == 0.0 ? 0.0 : atrValue / close
float atr2 = close == 0.0 ? 0.0 : atrValue / close
float atr3 = close == 0.0 ? 0.0 : atrValue / close
float atr4 = close == 0.0 ? 0.0 : atrValue / close
bool rowReady = not na(ret4) and not na(atr4)
if rowReady
array features = array.from(ret4, atr4, ret3, atr3, ret2, atr2, ret1, atr1)
float downTarget = math.max(-ret0, 0.0)
float neutralTarget = math.max(0.002 - math.abs(ret0), 0.0)
float upTarget = math.max(ret0, 0.0)
qDataset := qDataset.pushRow(features, array.from(downTarget, neutralTarget, upTarget))
if qDataset.ready(48)
if barstate.islastconfirmedhistory
nl.Batch train = qDataset.trainBatch(12)
qModel := qModel.trainOnBatch(train.inputTensor, train.targetTensor)
qLoss := qModel.trainStats.lastLoss
nl.Tensor liveState = nl.vector(array.from(ret3, atr3, ret2, atr2, ret1, atr1, ret0, atr0), "live_state")
nl.Tensor scaledState = qDataset.scaleInput(liveState)
nl.Tensor qValues = qModel.predict(scaledState)
qDown := qValues.get1d(0)
qNeutral := qValues.get1d(1)
qUp := qValues.get1d(2)
plot(qDown, "Q down", color = color.red, linewidth = 2)
plot(qNeutral, "Q neutral", color = color.gray)
plot(qUp, "Q up", color = color.lime, linewidth = 2)
plot(qLoss, "Training loss", color = color.orange)
hline(0.0, "Zero", color = color.new(color.gray, 70))
Input shape `array.from(8)` represents a flattened 4 step by 2 feature sequence. The temporal stack extracts short sequence structure, pooling compresses the sequence, and the dueling head separates value and advantage paths before producing action scores. The example trains only on the last confirmed historical bar so it remains safe to paste onto long charts.
🔸 Transformer Encoder For Token Rows
Attention models are useful when each row is a token or time step, and each column is a feature dimension.
//@version=6
indicator("NeuraLib Models Transformer Encoder Example", overlay = false, calc_bars_count = 600)
import Alien_Algorithms/NeuraLib/1 as nl
import Alien_Algorithms/NeuraLib_Models/1 as models
var nl.Sequential encoder = nl.sequential("encoder_model")
var float tokenSignal = na
var float tokenContext = na
var float tokenVolatility = na
if barstate.isfirst
encoder := encoder
.input(array.from(4), "tokens")
.multiHeadSelfAttention(4, 2, true, "mha")
.transformerEncoder(4, true, 2, nl.ActivationKind.geluApprox, "encoder", 0.05, 2)
.build(nl.rng(11))
float emaValue = ta.ema(close, 21)
float atrValue = ta.atr(14)
float ret0 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret1 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret2 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret3 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float emaGap0 = emaValue == 0.0 ? 0.0 : close / emaValue - 1.0
float emaGap1 = emaValue == 0.0 ? 0.0 : close / emaValue - 1.0
float emaGap2 = emaValue == 0.0 ? 0.0 : close / emaValue - 1.0
float emaGap3 = emaValue == 0.0 ? 0.0 : close / emaValue - 1.0
float atr0 = close == 0.0 ? 0.0 : atrValue / close
float atr1 = close == 0.0 ? 0.0 : atrValue / close
float atr2 = close == 0.0 ? 0.0 : atrValue / close
float atr3 = close == 0.0 ? 0.0 : atrValue / close
bool ready = not na(ret3) and not na(emaGap3) and not na(atr3)
if ready
nl.Tensor tokens = nl.vector(array.from(
ret3, emaGap3, atr3, -1.0,
ret2, emaGap2, atr2, -0.33,
ret1, emaGap1, atr1, 0.33,
ret0, emaGap0, atr0, 1.0), "tokens").reshape(array.from(4, 4))
nl.Tensor encoded = encoder.predict(tokens)
tokenSignal := encoded.get1d(12)
tokenContext := encoded.get1d(13)
tokenVolatility := encoded.get1d(14)
plot(tokenSignal, "Latest token signal", color = color.aqua, linewidth = 2)
plot(tokenContext, "Latest token context", color = color.purple)
plot(tokenVolatility, "Latest token volatility", color = color.orange)
hline(0.0, "Zero", color = color.new(color.gray, 70))
In this example, each input row has 4 features. `headCount` is 2, so the model dimension is split into two attention heads.
Attention rule: `modelDim` must be divisible by `headCount`, and the current implementation supports up to 8 heads.
🔸 Prioritized Experience Replay
Prioritized Experience Replay stores examples with priorities, then returns reproducible weighted samples. This is especially useful for Reinforcement Learning experiments where high-error transitions should be revisited more often.
//@version=6
indicator("NeuraLib Models PER Example", overlay = false, calc_bars_count = 1200)
import Alien_Algorithms/NeuraLib/1 as nl
import Alien_Algorithms/NeuraLib_Models/1 as models
var models.PrioritizedReplayBuffer replay = models.prioritizedReplayBuffer(4, 2, 300, "replay")
var nl.Sequential replayModel = nl.sequential("replay_q_model")
var float replayLoss = na
var float firstImportanceWeight = na
var float replayRows = na
if barstate.isfirst
nl.CompileConfig cfg = nl.compileConfig()
cfg := cfg
.presetQValues()
.optimizer(nl.adamW(0.001))
.trainEveryCall()
replayModel := replayModel
.input(array.from(4), "state")
.dense(8, nl.ActivationKind.relu, "hidden")
.qHead(2, nl.ActivationKind.linear, "q_values")
.compile(cfg)
float rsiValue = ta.rsi(close, 14)
float emaValue = ta.ema(close, 21)
float atrValue = ta.atr(14)
float atrPct = close == 0.0 ? 0.0 : atrValue / close
float momentum = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float nextReturn = na(close ) ? 0.0 : nl.nextReturnValue(close , close)
bool rowReady = not na(rsiValue ) and not na(emaValue ) and not na(atrPct ) and not na(momentum )
if rowReady
float prevEma = emaValue
float priceVsEma = prevEma == 0.0 ? 0.0 : close / prevEma - 1.0
array stateFeatures = array.from(rsiValue / 100.0, priceVsEma, atrPct , momentum )
array targetValues = array.from(math.max(-nextReturn, 0.0), math.max(nextReturn, 0.0))
float priority = math.abs(nextReturn) + 0.0001
replay := replay.pushExperience(stateFeatures, targetValues, priority)
replayRows := float(replay.size())
if replay.ready(32)
models.PrioritizedReplaySample sample = replay.sampleBatch(32, 0.6, 0.4, 17)
replayModel := replayModel.trainOnBatch(sample.batch.inputTensor, sample.batch.targetTensor)
replayLoss := replayModel.trainStats.lastLoss
firstImportanceWeight := sample.weightArray.size() > 0 ? sample.weightArray.get(0) : na
if sample.indexArray.size() > 0
replay := replay.updatePriority(sample.indexArray.get(0), replayLoss + 0.0001)
plot(replayLoss, "Replay training loss", color = color.orange, linewidth = 2)
plot(firstImportanceWeight, "First sample weight", color = color.aqua)
The returned sample includes:
batch : A normal NeuraLib `Batch` containing sampled inputs and targets.
indexArray : Logical replay indices that can be passed back to `updatePriority()`.
weightArray : Normalized importance weights for custom loss weighting or diagnostics.
sampleRows : Number of sampled rows.
PER sampling is deterministic for a given buffer, `batchSize`, and `seed`. That makes Pine tests and live research easier to reproduce.
----------------------------------------------------------------------------------------------------------------
🔷 MODEL FAMILIES
🔸 Residual Dense Blocks
`residualDense()` adds a feedforward residual block. Residual paths help preserve information through deeper models and reduce the chance that a dense stack destroys useful features too early.
🔸 Conv1D And Temporal Convolution Stacks
`conv1d()` and `temporalConvStack()` operate on flattened sequence inputs. A sequence with `timeSteps = 4` and `featureCount = 2` is represented as 8 input features. These blocks are useful for local temporal structure, short rolling windows, feature rhythm, and compact pattern extraction.
🔸 Global Pooling
`globalAvgPool1d()` and `globalMaxPool1d()` compress flattened sequence outputs into feature-level summaries. Average pooling captures broad sequence behavior, while max pooling emphasizes the strongest activation per feature.
🔸 LSTM And GRU Blocks
`lstm()` and `gru()` provide recurrent sequence memory over flattened time-series inputs. They are useful when the order of recent states matters more than a single snapshot.
🔸 Attention And Transformers
`selfAttention()`, `multiHeadSelfAttention()`, `crossAttention()`, `transformerEncoder()`, `transformerEncoderStack()`, and `transformerDecoder()` bring attention-style modeling into Pine. They are designed for compact token matrices, packed target-memory layouts, and small Transformer-style research models that fit PulseWire limits.
🔸 Q-Heads And Dueling Q-Heads
`qHeadBlock()` creates action-value style outputs. `duelingQHead()` splits the model into value and advantage branches, then recombines them into Q-values. This is useful when you want the model to estimate both the overall state value and the relative value of each action.
🔸 Positional Encoding
`pushPositionalEncoding()` adds sinusoidal position features to a NeuraLib `FeatureBuilder`. This helps attention-style models distinguish where a token or time step sits in a sequence.
----------------------------------------------------------------------------------------------------------------
🔷 FEATURE QUICK REFERENCE
Built on NeuraLib : Uses the main NeuraLib graph, tensor, training, optimizer, dataset, and inference runtime.
Fluent API : Adds methods directly to NeuraLib `Sequential` models after import.
Block factories : Provides standalone `GraphBlock` factories for users who want lower-level composition.
Temporal modeling : Conv1D, temporal convolution stacks, and 1D pooling.
Recurrent modeling : LSTM and GRU sequence blocks.
Attention modeling : Self-attention, multi-head self-attention, cross-attention, encoders, encoder stacks, and decoders.
Reinforcement Learning support : Q-heads, dueling Q-heads, target-model soft updates through NeuraLib, and Prioritized Experience Replay.
Reproducible replay : PER sampling is deterministic for a given seed.
Shape guardrails : Advanced builders validate expected model feature counts and attention head compatibility.
----------------------------------------------------------------------------------------------------------------
🔷 IMPORTANT USAGE NOTES
Import order matters : Import `NeuraLib` first, then `NeuraLib_Models`.
The alias can be unused : The imported expansion registers methods on NeuraLib types, so `.lstm()`, `.gru()`, `.transformerEncoder()`, and similar methods can be called in the model chain.
Keep models compact : Pine Script has execution limits. Start with small hidden sizes, short sequences, and low head counts.
Control chart history : Use `calc_bars_count = 600` in `indicator()` when needed to balance available training history against model size and execution time.
Respect sequence shapes : Conv1D, temporal stacks, LSTM, and GRU methods expect flattened sequence sizes of `timeSteps * featureCount`.
Respect attention shapes : Attention methods expect each input row to have `modelDim` columns. Cross-attention and decoder blocks use packed rows.
Use NeuraLib guardrails : Train/validation splits, scalers, EarlyStopper, training gates, and gradient clipping remain part of the main NeuraLib workflow.
----------------------------------------------------------------------------------------------------------------
🔷 API REFERENCE
🔸 Sequential Methods
residualDense(hiddenUnits, activationKind, dropoutRate, name) : Adds a residual dense block.
duelingQHead(hiddenUnits, actionCount, activationKind, name) : Adds a dueling value/advantage Q-head.
conv1d(timeSteps, featureCount, filters, kernelSize, stride, activationKind, name) : Adds a Conv1D block for flattened sequences.
temporalConvStack(timeSteps, featureCount, filters, kernelSize, layers, stride, activationKind, dropoutRate, name) : Adds stacked temporal Conv1D layers.
globalAvgPool1d(timeSteps, featureCount, name) : Adds global average pooling over a flattened 1D sequence.
globalMaxPool1d(timeSteps, featureCount, name) : Adds global max pooling over a flattened 1D sequence.
lstm(timeSteps, featureCount, units, activationKind, name) : Adds an LSTM scan block.
gru(timeSteps, featureCount, units, activationKind, name) : Adds a GRU scan block.
selfAttention(modelDim, causal, name) : Adds row-wise self-attention.
multiHeadSelfAttention(modelDim, headCount, causal, name) : Adds multi-head self-attention.
crossAttention(queryRows, memoryRows, modelDim, headCount, name) : Adds packed query-memory cross-attention.
transformerEncoder(modelDim, causal, ffMultiplier, activationKind, name, dropoutRate, headCount) : Adds one Transformer encoder block.
transformerEncoderStack(modelDim, layers, causal, ffMultiplier, activationKind, dropoutRate, headCount, name) : Adds repeated Transformer encoder blocks.
transformerDecoder(targetRows, memoryRows, modelDim, headCount, ffMultiplier, activationKind, dropoutRate, name) : Adds a packed target-memory Transformer decoder.
🔸 GraphBlock Factories
qHeadBlock(inputFeatures, actionCount, activationKind, name) : Creates a Q-head block.
duelingQHeadBlock(inputFeatures, hiddenUnits, actionCount, activationKind, name) : Creates a dueling Q-head block.
residualDenseBlock(inputFeatures, hiddenUnits, activationKind, dropoutRate, name) : Creates a residual dense block.
conv1dBlock(timeSteps, featureCount, filters, kernelSize, stride, activationKind, name) : Creates a Conv1D block.
temporalConvStackBlock(timeSteps, featureCount, filters, kernelSize, layers, stride, activationKind, dropoutRate, name) : Creates a temporal convolution stack.
globalAvgPool1dBlock(timeSteps, featureCount, name) and globalMaxPool1dBlock(timeSteps, featureCount, name) : Create pooling blocks.
lstmBlock(timeSteps, featureCount, units, activationKind, name) and gruBlock(timeSteps, featureCount, units, activationKind, name) : Create recurrent blocks.
selfAttentionBlock(modelDim, causal, name) , multiHeadSelfAttentionBlock(modelDim, headCount, causal, name) , and crossAttentionBlock(queryRows, memoryRows, modelDim, headCount, name) : Create attention blocks.
transformerEncoderBlock(modelDim, causal, ffMultiplier, activationKind, name, dropoutRate, headCount) and transformerDecoderBlock(targetRows, memoryRows, modelDim, headCount, ffMultiplier, activationKind, dropoutRate, name) : Create Transformer blocks.
🔸 Prioritized Experience Replay
prioritizedReplayBuffer(featureCount, targetCount, maxRows, name) : Creates a replay buffer.
pushExperience(featureRowArray, targetRowArray, priority) : Adds or overwrites one replay row.
sampleBatch(batchSize, alpha, beta, seed) : Returns a deterministic weighted sample.
updatePriority(index, priority) : Updates a sampled row priority.
toBatch() : Returns all replay rows in chronological order.
ready(minRows) , size() , and clear() : Replay buffer utilities.
🔸 Feature Helpers
pushPositionalEncoding(position, dimensions, maxPeriod, featurePrefix) : Appends sinusoidal positional encoding values to a NeuraLib `FeatureBuilder`.
NeuraLib_Models is for Pine Script developers who want higher-level neural architecture blocks without leaving the NeuraLib runtime. It is built for compact research models inside PulseWire's execution limits, not for oversized GPU-style networks.
All the diagrams in this publication are rendered natively on PulseWire using Pine3D
----------------------------------------------------------------------------------------------------------------
This work is licensed under (CC BY-NC-SA 4.0) , meaning usage is free for non-commercial purposes given that Alien_Algorithms is credited in the description for the underlying software. For commercial use licensing, contact Alien_Algorithms
Library

NeuraLib: A Native AI and Deep Learning RuntimeNeuraLib is a tensor-based, auto-differentiating Machine Learning runtime built natively for Pine Script™.
It brings real Deep Learning mechanisms that power modern Artificial Intelligence systems into PulseWire. Instead of relying on fixed formulas, static regressions, or rigid structures, NeuraLib gives Pine developers a different tool: a compact neural runtime that can learn from the features you feed it, using the architecture you define.
This means users are no longer limited to classical methods like Linear Regression, Logistic Regression, KNN, Naive Bayes, Kalman Filters, or Markov Chains. One can build adaptive architectures perfectly suited for custom indicators, strategies, regime detection, directional prediction, price transforms, and AI-assisted signal generation.
Using NeuraLib, one can build a model, collect market data, normalize it, run predictions, train through backpropagation, track validation behavior, and update weights directly inside PulseWire.
Furthermore, it is not necessary to directly display trained variables. The process can be a part of a larger script functionality, where AI-powered decision making changes how an indicator behaves.
The goal is to make real neural network workflows usable in Pine Script without hiding the important controls, being scalable with evolving market dynamics, and abstracting away the complexity that comes with such software. The provided API is highly modular and intuitive, using chained object-oriented programming for easy readability and use. The backend is engineered with fault-tolerance in mind, providing users with sanity checks and preventing common pitfalls by default.
Think of NeuraLib as a comprehensive machine learning ecosystem, containing:
A Model Builder : Define neural networks with readable chained calls like `.input()`, `.dense()`, and `.dropout()`.
An In-Pine Training Engine : Models calculate losses, backpropagate gradients, update weights, and produce predictions directly on chart data.
Automated Data Pipelines : Built-in datasets handle feature collection, robust scaling (Z-Score, Min-Max), validation holdout splits, and time-series rolling windows.
Finance-Native Loss Functions : Beyond standard error metrics, the engine includes Directional, Quantile, Multi-Horizon Weighted, and Sharpe-style losses tailored for trading.
Practical Training Controls : Layer Normalization, AdamW weight decay, gradient clipping, gradient accumulation, and early stopping are built in to prevent overfitting.
Advanced Optimizers : Train networks using RMSProp, Adam, or AdamW, paired with learning rate schedules like Warmup Cosine and Step Decay.
For newer users, this means you can start with a simple dense model. For advanced users, the same runtime exposes graph operations, custom blocks, tensors, matrix operations, optimizers, schedules, losses, and extension hooks.
In plain terms, a model receives a row of numbers called features, compares its output against a target, measures the error with a loss function, and then adjusts its internal weights to reduce that error next time.
----------------------------------------------------------------------------------------------------------------
🔷 WHAT MAKES IT DIFFERENT
🔸 Parity-tested neural math
NeuraLib’s core operations have been tested against established Machine Learning Runtimes outside of PulseWire (Such as Keras / TensorFlow / PyTorch).
The goal was not to imitate the appearance of Machine Learning, but to reproduce the math that is proven to work. Standard forward passes, gradients, losses, and optimizer behavior were checked for 1:1 algorithmic parity, with negligible differences coming from normal floating-point behavior.
That means the matrix math, backpropagation, and gradient updates running on your chart follow the same underlying logic expected from professional Machine Learning environments.
🔸 Matrix-first computation
NeuraLib uses tensor and matrix abstractions as the foundation of the runtime. Under the hood, it supports the operations needed for neural computation, including matrix multiplication, broadcasting, activation functions, softmax, slicing, concatenation, reductions, normalization, attention scoring, convolution-style operations, and recurrent scan blocks.
🔸 Auto-differentiating graph engine
NeuraLib makes the computational graph a first-class object.
You can use high-level Sequential models, or build custom GraphBlocks from lower-level operations. Once a custom block is connected to a model, the same runtime handles the backward pass. That means your custom architecture can be trained with the same `.trainOnBatch()` workflow as standard layers.
----------------------------------------------------------------------------------------------------------------
🔷 CUSTOM GRAPHS
The Sequential API is the easiest way to start, but NeuraLib is not just a list of built-in layers.
You can create a `GraphBlock`, add operations, set an output node, and plug that block into a model. Once connected, the runtime handles the backward pass and parameter updates.
Useful graph operations include:
Matrix multiplication, transpose, add, subtract, multiply, divide, and scale.
Activation functions and softmax.
Layer Normalization and Dropout.
Causal masking, slicing, concatenation, row reduction, and column reduction.
Global average pooling and global max pooling for 1D sequences.
Attention score and attention apply operations.
Conv1D, LSTM scan, and GRU scan primitives.
This is the foundation that allows companion model libraries to add advanced AI and Machine Learning architectures without changing the main NeuraLib runtime.
----------------------------------------------------------------------------------------------------------------
🔷 BUILT-IN DATA GUARDRAILS
NeuraLib is not only a training mechanism. It also includes guardrails for cleaner research:
Invalid rows are rejected : Dataset rows must match the configured feature and target counts, and rows containing `na` values are not inserted.
Shape checks protect model calls : Forward, training, backward, and evaluation paths validate input and target shapes before running expensive graph code.
Train and validation splits are separated : `trainBatch()` and `validationBatch()` use holdout rows instead of blending all rows into one batch.
Scaler leakage is controlled : Validation batches are scaled from the training-side profile where the dataset split requires it, so validation normalization does not learn from the holdout slice.
Rolling windows respect time order : `RollingDataset` supports target offsets and wrapped ring buffers while preserving chronological reads.
These checks help reduce common data poisoning and data leakage mistakes: wrong row widths, missing values, validation contamination, target-offset leakage, and accidental overtraining across every historical bar.
----------------------------------------------------------------------------------------------------------------
🔷 A FIRST MODEL
The basic API is intentionally readable. This creates a small model with dropout, one hidden layer, Huber loss, AdamW optimization, and MAE tracking.
//@version=6
indicator("NeuraLib Basic Model", overlay = false, calc_bars_count = 600)
import Alien_Algorithms/NeuraLib/1 as nl
var nl.Sequential model = nl.sequential("basic_model")
var float modelOutput = na
if barstate.isfirst
nl.CompileConfig cfg = nl.compileConfig()
cfg := cfg
.optimizer(nl.adamW(0.001))
.loss(nl.LossKind.huber)
.metric(nl.MetricKind.mae)
.withTrainingGate(true)
model := model
.input(array.from(4), "features")
.dropout(0.15)
.dense(8, nl.ActivationKind.relu, "hidden")
.dense(1, nl.ActivationKind.linear, "output")
.compile(cfg)
float rsiValue = ta.rsi(close, 14)
float emaValue = ta.ema(close, 21)
float atrValue = ta.atr(14)
float atrPct = close == 0.0 ? 0.0 : atrValue / close
float momentum = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
bool ready = not na(rsiValue) and not na(emaValue) and not na(atrPct) and not na(momentum)
if ready
float priceVsEma = emaValue == 0.0 ? 0.0 : close / emaValue - 1.0
nl.Tensor inputTensor = nl.vector(array.from(rsiValue, priceVsEma, atrPct, momentum), "features")
nl.Tensor outputTensor = model.predict(inputTensor)
modelOutput := outputTensor.get1d(0)
plot(modelOutput, "Untrained model output", color = color.aqua, linewidth = 2)
hline(0.0, "Zero", color = color.new(color.gray, 70))
The same model can then receive scaled batches from a dataset and train with `.trainOnBatch()`. The plot in this first example is the untrained forward output, included so the block can be pasted directly into an indicator.
----------------------------------------------------------------------------------------------------------------
🔷 A PRACTICAL DATA FLOW
Machine Learning models usually fail when the data pipeline is careless. Price, volume, volatility, and oscillators often live on very different scales. NeuraLib includes dataset and scaling helpers so the common workflow stays explicit:
Build a feature row.
Build a target row.
Push the row into a dataset.
Request a training batch.
Request a validation batch when needed.
Train, evaluate, predict, and inverse-scale targets when appropriate.
//@version=6
indicator("NeuraLib Return Validation Example", overlay = false, calc_bars_count = 600)
import Alien_Algorithms/NeuraLib/1 as nl
var nl.Sequential model = nl.sequential("returns_model")
var nl.WindowDataset dataset = nl.windowDataset(4, 1, 500, "returns_dataset")
var float predictedReturn = na
var float validationLossValue = na
var float trainingLossValue = na
if barstate.isfirst
nl.CompileConfig cfg = nl.compileConfig()
cfg := cfg
.optimizer(nl.adamW(0.003))
.loss(nl.LossKind.huber)
.metric(nl.MetricKind.mae)
.trainEveryCall()
model := model
.input(array.from(4), "features")
.dense(8, nl.ActivationKind.relu, "hidden")
.dropout(0.10, "dropout")
.dense(1, nl.ActivationKind.linear, "next_return")
.compile(cfg)
dataset := dataset
.setInputScaler(nl.ScalerKind.zScore)
.setTargetScaler(nl.ScalerKind.zScore)
float rsiValue = ta.rsi(close, 14)
float emaValue = ta.ema(close, 21)
float atrValue = ta.atr(14)
float atrPct = close == 0.0 ? 0.0 : atrValue / close
float momentum = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float realizedReturn = na(close ) ? na : nl.nextReturnValue(close , close)
bool rowReady = not na(rsiValue ) and not na(emaValue ) and not na(atrPct ) and not na(momentum ) and not na(close )
if rowReady
float prevEma = emaValue
float priceVsEma = prevEma == 0.0 ? 0.0 : close / prevEma - 1.0
array features = array.from(
rsiValue ,
priceVsEma,
atrPct ,
momentum )
array target = array.from(nl.nextReturnValue(close , close))
dataset := dataset.pushRow(features, target)
if dataset.ready(64)
nl.Batch train = dataset.trainBatch(16)
nl.Batch validation = dataset.validationBatch(16)
model := model.trainOnBatch(train.inputTensor, train.targetTensor)
trainingLossValue := model.trainStats.lastLoss
nl.LossResult validationLoss = model.evaluate(validation.inputTensor, validation.targetTensor)
validationLossValue := validationLoss.value
bool liveReady = not na(rsiValue) and not na(emaValue) and not na(atrPct) and not na(momentum)
if liveReady
float livePriceVsEma = emaValue == 0.0 ? 0.0 : close / emaValue - 1.0
array liveFeatures = array.from(rsiValue, livePriceVsEma, atrPct, momentum)
nl.Tensor liveInput = nl.vector(liveFeatures, "live_features")
nl.Tensor scaledInput = dataset.scaleInput(liveInput)
nl.Tensor scaledPrediction = model.predict(scaledInput)
nl.Tensor rawPrediction = dataset.inverseScaleTarget(scaledPrediction)
predictedReturn := rawPrediction.get1d(0)
plot(realizedReturn, "Last realized return", color = color.gray)
plot(predictedReturn, "Predicted next return", color = color.aqua, linewidth = 2)
plot(validationLossValue, "Validation loss", color = color.orange)
plot(trainingLossValue, "Training loss", color = color.new(color.blue, 35))
hline(0.0, "Zero", color = color.new(color.gray, 70))
This example trains from completed historical pairs. The feature row comes from the previous bar, and the target is the return from that previous bar to the current bar. That keeps the example easy to inspect and avoids using future information in the feature row. When pasted into an indicator, it plots the last realized return, the model's predicted next return, training loss, and validation loss.
----------------------------------------------------------------------------------------------------------------
🔷 TWO PRACTICAL EXECUTION MODES
Deep Learning in Pine requires careful execution control. NeuraLib supports two main workflows.
🔸 1. Live-edge training
Use this when you want safer execution for larger models.
The dataset can collect rows across the chart, while the expensive training step only runs on the last confirmed historical bar. This helps avoid timeouts while still allowing the model to learn from recent prepared data.
cfg := cfg.withTrainingGate(true)
Use this for:
Larger models
More features
Rolling sequence inputs
Heavier architectures
Safer live-edge updates
🔸 2. Full-history training and inference
Use this when the model is intentionally small.
The model can train and infer across historical bars, which makes it possible to create lightweight adaptive indicators, such as an AI Moving Average that learns from recent local structure instead of using a fixed smoothing formula.
cfg := cfg.trainEveryCall()
Use this for:
Tiny dense models
Small batches
Fast adaptive filters
AI-assisted moving averages
Lightweight feature transforms
For full-history workflows, start small. A shallow model with 4 to 8 hidden units and a batch size of 8 or 16 is usually a better starting point than a deep architecture.
----------------------------------------------------------------------------------------------------------------
🔷 ADVANCED MODEL EXPANSION
NeuraLib is designed to act as the foundation for larger model libraries and community-built extensions.
To demonstrate this, NeuraLib Expansion: Advanced Model Layers is built entirely on top of the public NeuraLib API and is launched in parallel on day one. The expansion library is published as NeuraLib_Models . It extends the runtime with higher-level builders for LSTMs, GRUs, temporal convolution stacks, residual dense blocks, dueling Q-heads for Reinforcement Learning, Transformer-style attention blocks, and Prioritized Experience Replay utilities.
The important part is architectural: advanced models plug into the same runtime. NeuraLib remains the foundation for tensors, graph execution, optimization, training, inference, datasets, and scaling. After importing `NeuraLib_Models`, its fluent methods become available on NeuraLib `Sequential` models, so the expansion alias does not need to be referenced directly in the layer chain.
//@version=6
indicator("NeuraLib Models Extension Demo", overlay = false, calc_bars_count = 600)
import Alien_Algorithms/NeuraLib/1 as nl
import Alien_Algorithms/NeuraLib_Models/1 as models
var nl.Sequential model = nl.sequential("advanced_demo")
if barstate.isfirst
model := model
.input(array.from(8), "sequence")
.temporalConvStack(4, 2, 3, 2, 2, 1, nl.ActivationKind.relu, 0.0, "temporal")
.globalAvgPool1d(2, 3, "pool")
.duelingQHead(4, 2, nl.ActivationKind.relu, "q_head")
.build(nl.rng(7))
----------------------------------------------------------------------------------------------------------------
🔷 FEATURE QUICK REFERENCE
Runtime : Matrix-first auto-differentiating neural graph runtime for Pine Script.
Model API : Chainable `Sequential` builder with `input`, `dense`, `dropout`, `layerNorm`, `activation`, `flatten`, `reshape`, and custom `block` support.
Training : Forward pass, loss calculation, backpropagation, gradient accumulation, optimizer steps, train stats, and history buffers.
Inference : `.predict()` for deterministic inference and `.predictMC()` for dropout-based uncertainty sampling.
Datasets : `WindowDataset` for flat rows and `RollingDataset` for time-series windows.
Scaling : None, Z-Score, Min-Max, Running Z-Score scalers, dataset input scaling, target scaling, and inverse target scaling.
Optimizers : SGD, Momentum, RMSProp, Adam, and AdamW.
Schedulers : Constant, Step Decay, Cosine Decay, and Warmup Cosine.
Activations : Linear, ReLU, Leaky ReLU, ELU, GELU Approx, Sigmoid, Tanh, Softplus, Swish, and Softmax.
Losses : MSE, MAE, Huber, LogCosh, Binary Cross Entropy, Binary Cross Entropy From Logits, Categorical Cross Entropy, Softmax Cross Entropy From Logits, Directional, Quantile, Multi-Horizon Weighted, and Sharpe.
Metrics : MAE, RMSE, Directional Accuracy, Binary Accuracy, Binary Accuracy From Logits, Categorical Accuracy, and Cosine Similarity.
Guardrails : Shape validation, invalid-row rejection, train/validation split helpers, leakage-aware scaler profiles, training gates, gradient clipping, and EarlyStopper.
Advanced expansion : Conv1D, temporal stacks, recurrent blocks, attention, Transformers, dueling Q-heads, positional encodings, and Prioritized Experience Replay.
----------------------------------------------------------------------------------------------------------------
🔷 IMPORTANT CONSIDERATIONS
Start small : Pine Script is not a GPU training environment. Compact models are the right starting point.
Control chart history : Use `calc_bars_count = 600` in `indicator()` when needed to balance available training history against model size and execution time.
Use the training gate : For heavier models, use `.withTrainingGate(true)` so backpropagation runs only at the confirmed historical edge.
Scale your inputs : Raw market features often differ by orders of magnitude. Use dataset scalers unless you have a deliberate reason not to.
Validate separately : Use `trainBatch()` and `validationBatch()` to monitor generalization instead of only watching training loss.
Avoid lookahead : Build feature rows only from information available at the time of the row. Use completed target rows for training.
Treat outputs as research signals : NeuraLib provides model mechanics. Strategy design, risk management, and market assumptions remain the user's responsibility.
----------------------------------------------------------------------------------------------------------------
🔷 API REFERENCE
🔸 Model Setup
sequential(name) : Creates an empty `Sequential` model.
compileConfig() : Creates a model configuration object.
build(rng) : Builds model parameters with a deterministic random stream.
compile(config) : Builds the model when needed and applies the training configuration.
rng(seed, streamId) : Creates a deterministic random stream.
🔸 Sequential Methods
input(dimsArray, name) : Defines the input shape.
dense(units, activation, name) : Adds a fully connected layer.
qHead(actionCount, activation, name) : Adds a Q-value output head.
activation(activationKind, alpha, name) : Adds an activation block.
dropout(rate, name) : Adds dropout regularization.
layerNorm(name) : Adds layer normalization.
flatten(name) and reshape(outputDimsArray, name) : Adjust model shape metadata.
block(graphBlock) : Adds a custom `GraphBlock`.
trainOnBatch(inputTensor, targetTensor) : Runs training when the active gate allows it.
backward(targetTensor) : Accumulates gradients from the last forward pass without stepping.
step() : Applies the optimizer step to accumulated gradients.
predict(inputTensor) : Runs inference.
predictMC(inputTensor, samples) : Runs dropout-enabled Monte Carlo prediction and returns mean and variance.
evaluate(inputTensor, targetTensor) : Calculates loss without updating weights.
fitDataset(dataset) and fitRollingDataset(dataset, targetOffset) : Train through dataset adapters.
getWeightsArray() and setWeightsArray(weightsArray) : Export and import flat model weights.
softUpdateFrom(sourceModel, tau) : Soft-update parameters from another model.
🔸 CompileConfig Methods
optimizer(optimizerState) : Sets the optimizer.
schedule(scheduleState) : Sets the learning-rate schedule.
loss(lossKind) : Sets the training loss.
reduction(reductionKind) : Sets loss reduction behavior.
metric(metricKind) : Adds a metric.
batchSize(size) , epochsPerBar(count) , evalStride(stride) , and historyLength(length) : Store batch and cadence preferences, and set the metric history length.
clipNorm(value) and clipValue(value) : Apply gradient clipping.
gradAccumSteps(steps) : Accumulates gradients before stepping.
withTrainingGate(enabled) : Restricts training to the last confirmed historical bar when enabled.
trainEveryCall() : Allows training whenever `.trainOnBatch()` is called.
presetPriceRegression() , presetReturnRegression() , presetBinaryDirection() , presetBinaryDirectionLogits() , presetQValues() , and presetSharpe() : Apply common loss and metric presets.
🔸 Datasets
windowDataset(featureCount, targetCount, maxRows, name) : Stores flat feature and target rows.
rollingDataset(timeSteps, featureCount, targetCount, maxRows, name) : Stores time-series windows.
pushRow(featureArray, targetArray) : Adds one validated row.
pushBuilderRow(featureBuilder, targetArray) : Adds a row from a `FeatureBuilder`.
pushNextReturnRow(featureBuilder, currentValue, futureValue) : Adds a next-return target.
pushNextDirectionRow(featureBuilder, currentValue, futureValue, threshold, zeroOne) : Adds a direction target.
ready(minRows or minWindows, targetOffset) and size() : Check dataset readiness.
lastBatch(batchSize) : Returns the most recent scaled rows from a `WindowDataset`.
toBatch() : Returns all rows from a `WindowDataset`.
unrollBatch(targetOffset) : Returns all rolling windows from a `RollingDataset`.
trainBatch(validationRows or validationWindows, targetOffset) : Returns the training side of the split.
validationBatch(validationRows or validationWindows, targetOffset) : Returns the validation side of the split.
setInputScaler(kind) , setTargetScaler(kind) , scaleInput(tensor) , scaleTarget(tensor) , and inverseScaleTarget(tensor) : Configure and apply scaling.
clear() : Clears stored rows.
🔸 Tensor, Matrix, and Feature Helpers
scalar(value) , vector(valuesArray) , matrix2d(rows, cols, fillValue) , zeros(shape) , ones(shape) , and full(shape, fillValue) : Create tensors.
shapeFromDims(dimsArray) : Creates a shape.
matrixTensor(tensor) , matrixTensor2d(rows, cols, fillValue) , and matrixTensorFromMatrix(sourceMatrix) : Create matrix tensors.
reshape(dimsArray) , flatten() , row(rowIndex) , get1d(index) , sum() , mean() , variance() , normL2() , argmax() , and dot(other) : Tensor methods.
matmul() , transpose() , add() , subtract() , multiply() , divide() , scale() , activate() , softmax() , sliceRows() , sliceCols() , concatRows() , concatCols() , globalAvgPool1d() , and globalMaxPool1d() : MatrixTensor methods.
featureBuilder(name) , push(value, featureName) , addFeature(value, featureName) , toTensor(tensorName) , toArray() , size() , and clear() : Feature row helpers.
🔸 Scalers, Optimizers, and Schedules
zScoreScaler() , minMaxScaler() , runningZScoreScaler() , and noneScaler() : Standalone scaler states.
fit(tensor) , partialFit(tensor) , transform(tensor) , and inverseTransform(tensor) : Scaler methods.
sgd(learningRate) , momentum(learningRate, momentum) , rmsprop(learningRate, rho, epsilon) , adam(learningRate, beta1, beta2, epsilon) , and adamW(learningRate, beta1, beta2, epsilon, weightDecay) : Optimizers.
constantSchedule(learningRate) , stepDecay(baseLearningRate, decaySteps, gamma) , cosineDecay(baseLearningRate, minLearningRate, decaySteps) , and warmupCosine(baseLearningRate, minLearningRate, warmupSteps, decaySteps) : Schedules.
currentRate(stepCount) : Reads a schedule's learning rate at a step.
paramBank() , append() , zeroGrad() , globalGradNorm() , step(optimizerState) , and softUpdateFrom(sourceBank, tau) : Low-level parameter bank utilities.
🔸 Losses and Metrics
mse() , mae() , huber() , logCosh() , binaryCrossEntropy() , binaryCrossEntropyFromLogits() , categoricalCrossEntropy() , softmaxCrossEntropyFromLogits() , directionalLoss() , quantileLoss() , multiHorizonWeighted() , and sharpeLoss() : Direct loss helpers.
metricValue(metricKind, predictionTensor, targetTensor) : Direct metric helper.
earlyStopper(patience, minDelta) , update(validationLoss) , and reset() : Validation stopping helper.
nextReturnValue(currentValue, futureValue) and nextDirectionValue(currentValue, futureValue, threshold, zeroOne) : Common target helpers.
🔸 GraphBlock Operations
graphBlock(name) : Creates a custom trainable graph block.
input() , param() , constScalar() , constMatrix() , and output() : Define graph inputs, parameters, constants, and output metadata.
matmul() , add() , subtract() , multiply() , divide() , scale() , activate() , softmax() , transpose() , layerNorm() , and dropout() : NeuraLib graph math.
causalMask() , sliceRows() , concatRows() , sliceCols() , concatCols() , reduceRows() , and reduceCols() : Structural graph operations.
globalAvgPool1d() , globalMaxPool1d() , attentionScore() , attentionApply() , conv1d() , scanLstm() , and scanGru() : Sequence and architecture primitives.
🔸 NeuraLib_Models API
prioritizedReplayBuffer(featureCount, targetCount, maxRows, name) : Creates a replay buffer.
pushExperience(featureRowArray, targetRowArray, priority) , sampleBatch(batchSize, alpha, beta, seed) , updatePriority(index, priority) , toBatch() , ready(minRows) , size() , and clear() : Prioritized Experience Replay helpers.
pushPositionalEncoding(position, dimensions, maxPeriod, featurePrefix) : Adds positional encoding values to a `FeatureBuilder`.
residualDense() , duelingQHead() , conv1d() , temporalConvStack() , globalAvgPool1d() , globalMaxPool1d() , lstm() , gru() , selfAttention() , multiHeadSelfAttention() , crossAttention() , transformerEncoder() , transformerEncoderStack() , and transformerDecoder() : NeuraLib_Models `Sequential` methods.
NeuraLib is for Pine Script developers who want to move beyond fixed formulas and experiment with real neural network workflows directly inside PulseWire. It is a research framework, not a guarantee of market performance. Use validation, avoid lookahead, control risk, and keep models small enough for Pine's execution limits.
All the diagrams in this publication are rendered natively on PulseWire using Pine3D
----------------------------------------------------------------------------------------------------------------
This work is licensed under (CC BY-NC-SA 4.0) , meaning usage is free for non-commercial purposes given that Alien_Algorithms is credited in the description for the underlying software. For commercial use licensing, contact Alien_Algorithms
Library

Wave 3 Sniper SystemWave 3 Sniper System with AI - Precision Trend & Wave Analysis
Overview
Experience the next level of market analysis with the Wave 3 Sniper System with AI. This indicator is specifically designed to identify high-probability "Wave 3" setups—the most explosive phase of market trends. By integrating advanced AI-driven algorithms, the system filters out market noise and pinpoints precise entry and exit zones, as seen in the current XAUUSD (Gold) chart.
Key Features:
AI Trend Filtering: Uses machine learning logic to confirm trend direction, ensuring you're always on the right side of the market.
Wave 3 Detection: Specifically tuned to catch the strongest momentum waves for maximum R:R (Risk-to-Reward).
Visual Signals: Clear "W3 BUY" and "W3 SELL" flags with dynamic support/resistance levels.
Optimized for Gold (XAUUSD): While versatile, this system excels in high-volatility environments like Gold Spot.
Current Market Insight (XAUUSD):
As shown in the attached chart, the system recently signaled a W3 SELL near the 4,830 level, accurately capturing the bearish momentum. The AI is currently monitoring a consolidation zone near 4,795 for the next impulsive move.
Exclusive Partner Offer 🎁
To get the most out of this system, I recommend using PulseWire’s Premium features for real-time alerts and deeper backtesting.
Special Benefit for My Community:
If you haven't upgraded your PulseWire plan yet, use the link below to sign up. You will receive a $15 discount coupon toward your new plan immediately!
👉 www.pulsewire.com OANDA:XAUUSD
Sign up within 90 days via the link above to claim your $15 credit and access professional tools that complement the Wave 3 Sniper System.
Disclaimer:
Trading involves significant risk. This script is for educational and analysis purposes only and does not constitute financial advice. Indicator

SNP420_claudos v1.0Indicator Overview (Work in Progress)
A technical analysis indicator enhanced with a machine learning model. Feedback is welcome.
Chart Elements & Signal Logic
BUY (green label up) – Green arrow below the candle: Long entry signal based on EMA bullish crossover + confirmed trend + RSI confirmation.
★ BUY (strong green) – Brighter green: High-confidence long signal, additionally near support → improved risk-to-reward ratio.
SELL (red label down) – Red arrow above the candle: Short entry signal based on EMA bearish crossover + confirmed trend + RSI confirmation.
★ SELL (strong red) – Brighter red: High-confidence short signal, additionally near resistance.
EXIT (gold ×) – Gold cross: Close position when opposite EMA crossover occurs or RSI reaches extreme levels.
Take Profit (TP) – Green dashed line: Target level, typically set at 2× the Stop Loss distance.
Stop Loss (SL) – Red dashed line: Risk level, typically set at 1.5× ATR.
Entry Line – Solid blue line: Trade entry price.
Dashboard (Top Right Panel)
Trend – Displays current market direction: UP / DOWN / FLAT.
ATR – Shows current volatility in pips.
RSI – Indicates momentum strength (Red > 70 = overbought, Green < 30 = oversold).
Support – Nearest support level below the current price.
Resistance – Nearest resistance level above the current price.
Next Action – Suggested action: BUY / SELL / WAIT.
TP – Recommended Take Profit level.
SL – Recommended Stop Loss level.
Summary
This indicator combines trend-following logic (EMA crossovers), momentum confirmation (RSI), volatility-based risk management (ATR), support/resistance context, and a machine learning layer for filtering and prioritizing signals. The objective is to provide clear, actionable trade signals with predefined risk parameters and improved trade selection. Indicator

AI Neural Trend Predictor [identityKa]The AI Neural Trend Predictor is a professional-grade, zero-lag trend tracking system designed to keep traders in massive moves while aggressively filtering out market noise. Traditional moving averages suffer from two fatal flaws: they either lag heavily behind the price, or they whipsaw the trader out of positions during minor pullbacks. This script solves both issues by combining a zero-lag mathematical smoothing algorithm with a dynamic volatility shield.
Core Mechanics & Detection
Zero-Lag Base Engine: The core of the algorithm utilizes a highly responsive, smoothed proxy to track the live price instantly, eliminating the delayed entry problem found in SMA or EMA based indicators.
Volatility Shield (Noise Filter): Instead of flipping signals the moment price crosses the baseline, the engine projects a dynamic ATR-based shield around the trend. During a bullish run, minor price drops will simply compress into the shield without triggering a premature SELL signal. The trend only flips when the institutional order flow breaks through the true volatility threshold.
Clear BUY / SELL Labels: The engine prints highly visible, definitive BUY (Green) or SELL (Red) labels directly on the chart, taking the guesswork out of your entries.
HUD Dashboard & AI Logic
The strictly positioned on-chart intelligence panel evaluates the live market state:
Dangerous (Orange): Displayed actively whenever the internal volatility ratio drops below the algorithmic threshold, indicating a Choppy or Ranging market. This warns the trader to avoid taking new positions until momentum returns.
LONG / SHORT: The engine generates a clear directional bias when the market shifts to a "TRENDING" state and the volatility shield remains unbreached in the direction of the trend.
How to Use It
This tool is built for capturing massive swings. When an AI BUY label appears, you ride the trend until the opposing SELL label is printed. Do not panic-sell during minor red candles (pullbacks); trust the Volatility Shield to keep you in the trade. For optimal results, ignore signals generated while the dashboard reads "Dangerous." Indicator

Machine Learning: Trend Classifier [identityKa]Overview
The Machine Learning: Trend Classifier is a professional-grade algorithmic momentum and trend analysis tool designed for data-driven traders. Unlike traditional moving averages that inherently lag behind live price action, this script introduces a multi-factor mathematical classification engine that evaluates real-time market behavior to predict the true direction of the trend.
Core Mechanics & Detection
The algorithm uses a continuous data-stream calculation to locate major market shifts:
Bullish Classification (Neon Green): Detected when the underlying momentum, volatility, and trend-flow simultaneously show aggressive upward expansion. The dynamic data ribbon shifts to green, encapsulating the price.
Bearish Classification (Neon Red): Detected when the structural momentum shifts downwards. The dynamic ribbon turns red, acting as algorithmic resistance.
Neutral / Chop Zones (Orange): Detected when the market loses clear direction. The engine recognizes this as a friction zone and shifts to a neutral state, warning the trader of potential whipsaws.
The Algorithmic Classification Engine
A fundamental rule of this indicator is the "AI Confidence Score". The engine normalizes multiple indicators (RSI, CCI, and MACD flows) into a strict 0 to 100 percentage scale.
The script constantly monitors this confidence score. If the score is above 20%, a Bullish state is confirmed. If it is below -20%, a Bearish state is confirmed. Anything in between is classified as market noise.
Upon crossing these algorithmic thresholds, the script instantly updates the on-chart Ribbon, ensuring that only statistically significant trend shifts are highlighted for the trader. This keeps the workspace incredibly clean and mathematically sound.
HUD Dashboard & AI Logic
The on-chart intelligence panel evaluates the live market state and generates actionable data:
Dangerous: Displayed actively whenever the current live price is trading inside the Neutral zone (Confidence Score between -20% and 20%). This serves as a warning that the price is in a high-friction area where sharp rejections and false breakouts are imminent.
LONG / SHORT: The engine tracks the macro bias based on the classification state. If the AI Confidence heavily favors upward momentum, the bias shifts to LONG. If the momentum breaks downwards, the bias shifts to SHORT.
How to Use It
This tool provides exceptional context for trade entries and trend following. When the AI Suggestion reads "LONG," traders should look for pullbacks toward the lower band of the green ribbon. When the state reads "Dangerous," it is highly recommended to stay out of the market or tighten stop losses until a clear trend direction is re-established by the algorithm. Indicator

AI-SuperTrend (KNN Machine Learning)AI-SuperTrend (KNN Machine Learning)
▶️Overview
The AI-SuperTrend (KNN Machine Learning) is a trend-following indicator that integrates a K-Nearest Neighbors (KNN) classification engine into the classic SuperTrend algorithm. Rather than attempting to "predict" the future in the traditionally volatile and noise-heavy financial markets, this tool treats the market as a multi-dimensional state to be estimated.
By continuously sampling historical data, the engine identifies clusters of past conditions that mirror the present. It then analyzes the trend of those neighbors to deduce the "True State" of the current market, using this statistical consensus to validate SuperTrend signals and filter out deceptive market noise.
▶️Why KNN for Financial Markets?
In the noise-heavy environment of financial markets, complex parametric models like Support Vector Machines (SVM) or Deep Neural Networks often struggle with stability. These models frequently suffer from convergence issues during training, or they produce outputs that stagnate around the mean due to the low signal-to-noise ratio of financial data. Most critically, they are highly prone to overfitting, capturing random price fluctuations as if they were true alpha.
KNN offers a distinct advantage through its Robustness and Adaptability:
Non-parametric Nature:
KNN makes no underlying assumptions about the distribution of data, allowing it to adapt to non-linear and evolving market regimes.
Rolling Window Learning:
The model utilizes a rolling "Learning Window" that naturally aligns with the bar-by-bar execution of Pine Script. This approach ensures that the engine is always synchronized with the most relevant, recent market structures while remaining computationally efficient within the platform's resource constraints.
▶️Core Methodology: KNN and State Estimation
1. The KNN Engine
K-Nearest Neighbors is a non-parametric "Lazy Learning" algorithm. Instead of building a static model, it looks at the current market "Feature Vector" and searches the historical database for the K most similar instances.
Distance Metric: Uses the Minkowski Distance. This is adjustable via the p-parameter, where p=1 represents Manhattan distance and p=2 represents Euclidean distance.
Gaussian Weighting: Not all neighbors are equal. The script applies a Weighting kernel where neighbors closer to the current state carry significantly more weight in the final prediction than those further away.
2. State Estimation (Bayesian-like Approach)
The state estimation logic implemented in this script follows the methodology used by myself in the "KNN Machine Learning Momentum Indicator." By applying this approach to the SuperTrend framework, the indicator achieves a higher level of precision in trend validation.
Probability Calculation: The probability of a Bullish state is calculated as (Sum of Weights of Bullish Neighbors) divided by (Total Weights of all K Neighbors).
Synergistic Robustness: By combining the volatility-based boundaries of SuperTrend with the KNN state estimation, the system significantly improves robustness against market noise. A SuperTrend flip is only considered a "Major" signal if the AI confirms that the underlying market state has truly shifted, based on historical probability.
Confirmation: A signal is only triggered if the estimated probability exceeds the user-defined Prediction Threshold (e.g., 0.9 or 90%).
3. Sampling Stride (Efficiency and Diversity)
To balance computational load and data diversity within Pine Script's limits, the engine utilizes a Stride mechanism:
Computational Efficiency: Instead of checking every single bar in the lookback window, the script samples data at intervals defined by the Stride (e.g., every 15th bar).
Pattern Diversity: By skipping adjacent, highly correlated bars, the "Learning Window" covers a broader range of market structures. This ensures the KNN engine sees various types of volatility and price action rather than redundant near-term data.
▶️Key Features
Multi-Dimensional Feature Engineering
The AI analyzes a "Feature Space" consisting of:
RSI Momentum Clusters: Captures momentum across three different time horizons (Short, Medium, Long) to detect lead/lag convergence.
MA Deviations: Measures the "stretch" or distance from the mean using various Moving Average types (ZLSMA, HMA, etc.).
PCA Compression: An optional Dimensionality Reduction toggle that merges correlated features into 3 Principal Components. This reduces the "Curse of Dimensionality" and focuses the AI on the most impactful data trends.
▶️Parameter Guide
🔲SuperTrend Settings
ATR Length: The lookback period for volatility calculation.
Factor: The multiplier that determines the distance of the SuperTrend line from price.
🔲Machine Learning Engine
K-Neighbors (K): The number of historical patterns to compare. A smaller K is more sensitive to recent changes, while a larger K is more robust but may lag.
Learning Window Size: How far back in history the AI "remembers" or searches for neighbors.
Stride: The sampling interval. A stride of 15 means the AI learns from every 15th bar, increasing the effective historical range without hitting script calculation limits.
Prediction Threshold: The confidence level (0.1 to 1.0) required to trigger a signal. A value of 0.9 means the AI must be 90% certain based on historical weights.
🔲Feature Engineering
Feature MA Type: Choose the baseline for deviation (e.g., ZLSMA for zero-lag, HMA for speed).
Normalizing Window: The lookback for Z-Score normalization, ensuring all features are on the same scale (mean=0, std=1).
Minkowski Parameter (p): Controls the distance logic. p=1 is Manhattan, p=2 is Euclidean.
Shape Parameter: Controls the sensitivity of the Gaussian weighting. Higher values make the weights drop off more aggressively as distance increases.
▶️Visual Analytics
Major Signals (▲/▼): High-confidence trend changes confirmed by the AI. These are plotted only when the SuperTrend direction aligns with the AI's predicted direction and its probability exceeds the defined threshold.
Probability Labels: At every SuperTrend reversal point, the indicator displays a label showing the AI's estimated probability for that trend direction (e.g., "Pred 92%"). This allows for real-time visual assessment of the AI's confidence in the SuperTrend flip.
Major Signals: High-confidence trend changes confirmed by the AI.
ST Dots: Standard SuperTrend flips without full AI confirmation.
Dynamic Bar Color: A gradient representing the real-time AI confidence score.
Blue/Cyan: High Bullish Confidence.
Red/Pink: High Bearish Confidence.
Gray: Neutral or Indecisive state.
Disclaimer
Past performance does not guarantee future results. This indicator is a tool for statistical analysis and should be used in conjunction with a complete risk management strategy. Indicator

Self-Playing Snake (For Fun) [UAlgo]Self Playing Snake is a lightweight mini game built entirely in Pine Script for entertainment and UI experimentation. It renders a 15 by 15 grid using PulseWire tables, spawns a snake and a food item, then drives the snake automatically with a simple path selection algorithm. The game updates on the last bar, so it behaves like a small live widget on the chart while keeping the price chart itself visually clean.
The script is intentionally simple and fun. It demonstrates how Pine can be used for stateful simulations, table based rendering, and basic decision making logic without requiring external inputs or manual controls. The snake continuously tries to reach food, grows when it eats, tracks score and high score, and resets automatically when it can no longer make a valid move.
🔹 Features
1) Table Rendered Game Board
The game board is drawn using a table with fixed dimensions. Each cell represents a coordinate on the grid, and the script updates cell background color and emoji text to visualize the snake body, the snake head, and the food.
This makes the game visible directly on the chart without using traditional plotting.
2) Persistent Game State with Custom Types
The script uses two custom types:
Point stores integer x and y coordinates.
GameState stores the snake body as an array of Points, the food position, grid size, score, high score, and a game over flag.
A single persistent GameState variable holds the full game memory across bars.
3) Automatic Food Spawning with Collision Avoidance
Food spawns at a random grid coordinate. The script prevents food from spawning on the snake body by retrying up to 100 times. This keeps gameplay consistent as the snake grows and occupies more space.
4) Greedy AI Movement Logic
Each tick, the snake evaluates four possible moves: up, down, left, right. It rejects moves that would collide with walls or the snake’s body, then chooses the valid move that minimizes Manhattan distance to the food.
This creates a simple, deterministic style of behavior that looks intelligent in open space while still being vulnerable to self trapping as the snake becomes long.
5) Game Loop with Growth and Scoring
On each update step:
A new head point is added to the front of the snake.
If the head reaches the food, score increases and the snake grows by keeping its tail.
If the head does not reach the food, the tail is removed so snake length stays constant.
High score is updated whenever a new best is reached.
6) Automatic Reset on Game Over
If no valid move exists, the state is marked game over. On the next tick, the game resets automatically by restoring the initial snake shape, resetting score, and spawning new food. This keeps the widget running indefinitely without user interaction.
7) Minimal Chart Impact
The script does not draw traditional overlays on the price chart. It includes a fully transparent plot call only to satisfy indicator output requirements while keeping the chart clean.
🔹 Calculations
1) Board Representation and Coordinates
The grid uses integer coordinates from 0 to gridSize minus 1 in both x and y directions. Each Point represents one cell:
type Point
int x
int y
The board is rendered by looping through all cells and deciding what to draw in each position.
2) Snake Body Membership Check
The script checks whether a coordinate is occupied by the snake by scanning the snake array:
method isBody(GameState state, int x, int y) =>
bool found = false
if not na(state.snake) and state.snake.size() > 0
for i = 0 to state.snake.size() - 1
p = state.snake.get(i)
if p.x == x and p.y == y
found := true
break
found
This method is used both for collision checks and for rendering.
3) Manhattan Distance for AI Scoring
The AI uses Manhattan distance to estimate how close a candidate move is to food:
method dist(Point p1, Point p2) =>
math.abs(p1.x - p2.x) + math.abs(p1.y - p2.y)
This favors direct horizontal or vertical progress toward the target.
4) Food Spawning Logic
Food spawns randomly inside the grid, retrying if it lands on the snake:
int newX = int(math.random(0, state.gridSize - 1))
int newY = int(math.random(0, state.gridSize - 1))
int attempts = 0
while state.isBody(newX, newY) and attempts < 100
newX := int(math.random(0, state.gridSize - 1))
newY := int(math.random(0, state.gridSize - 1))
attempts += 1
state.food := Point.new(newX, newY)
5) Reset Initialization
The reset routine clears the snake and creates a small starting body, resets score, clears game over, and spawns food:
state.snake.clear()
state.snake.push(Point.new(7, 7))
state.snake.push(Point.new(7, 8))
state.score := 0
state.isGameOver := false
state.spawnFood()
6) AI Next Move Selection
The AI evaluates four directional moves. It rejects collisions with walls or body and chooses the valid move with the smallest distance:
Point head = state.snake.first()
array directions = array.from(
Point.new(0, -1),
Point.new(0, 1),
Point.new(-1, 0),
Point.new(1, 0)
)
float minDistance = 1000.0
Point bestMove = na
for i = 0 to directions.size() - 1
Point dir = directions.get(i)
int nextX = head.x + dir.x
int nextY = head.y + dir.y
bool isWallHit = nextX < 0 or nextX >= state.gridSize or nextY < 0 or nextY >= state.gridSize
bool isBodyHit = state.isBody(nextX, nextY)
if not isWallHit and not isBodyHit
Point potentialMove = Point.new(nextX, nextY)
float d = potentialMove.dist(state.food)
if d < minDistance
minDistance := d
bestMove := potentialMove
If bestMove remains na, there is no safe move and the game ends.
7) Tick Update Rules
The tick method controls the game loop:
If game over, reset.
Else decide next move.
If no move, set game over.
Else add head, then check food:
If food eaten, increment score, update high score, and spawn new food.
If not eaten, remove tail.
8) Rendering Logic with Tables
On the last bar, the script renders each cell:
Food cell draws an apple emoji and red tint.
Snake body draws a green square emoji.
Snake head draws a different emoji and brighter tint.
It also renders a small UI table that displays the current score and best score.
The script updates continuously on the last bar, making it behave like a live widget. Indicator

Smart Money Concepts AI - AdaptiveSmart Money Concepts AI scores every Fair Value Gap and Order Block with a 5-factor quality engine so you can instantly see which zones are worth trading and which are noise.
◈ How It Works
This indicator detects three core Smart Money / ICT concepts and layers an AI scoring system on top.
Market Structure tracks swing highs and lows to identify Break of Structure (BOS) and Change of Character (CHoCH). BOS means the trend is continuing. CHoCH means it may be reversing. The indicator automatically classifies each break and draws labeled lines on your chart. CHoCH lines are solid and thicker since they're the more significant events. BOS lines are dashed. Both can be toggled independently.
Fair Value Gaps (FVGs) are 3-candle imbalances where price moved so fast it left a gap. The indicator detects these automatically and draws scored boxes on the chart. Each FVG gets a quality score from 0 to 100. Higher-scored zones appear more vivid; lower-scored zones fade out. When price fills the gap (mitigation), the box turns dashed.
Order Blocks (OBs) are the last opposite candle before a structural break. They represent institutional accumulation or distribution. When a bullish CHoCH/BOS fires, the indicator looks back for the last bearish candle near the swing low and marks it as a demand zone. Bearish OBs work in reverse. Each OB is scored by displacement strength, volume, and trend alignment.
◈ The AI Scoring Engine
Every zone gets a 0-100 quality score based on 5 factors:
For FVGs:
Gap Size vs ATR: sweet spot is 0.3x to 1.5x ATR. Too small = noise, too big = likely fills fast
Displacement Strength: body-to-range ratio of the middle candle. Full-body candles = institutional conviction
Volume: displacement candle volume vs 20-period average
Trend Alignment: does the FVG direction match the EMA trend?
Structure Alignment: does it align with the current BOS/CHoCH direction?
For Order Blocks:
OB Size: tighter zones (0.3-1.0 ATR) score higher for precision
Post-OB Displacement: how far price moved after leaving the OB. Bigger moves = stronger institutional interest
Volume, Trend, and Structure: same alignment checks as FVGs
The score directly controls visual opacity. High-scoring zones are vivid and prominent, low-scoring zones are subtle and transparent. You can filter to "High Only" to hide zones scoring below 50.
◈ Signals
Signals fire when price enters a scored FVG zone with structural and trend alignment. If a scored Order Block overlaps the FVG, the score increases further.
★ Bright signals = high confluence (score ≥ 70 default). FVG + OB overlap + structure + trend all confirm.
○ Dim signals = moderate confluence (score ≥ 50). The setup exists but not all factors align perfectly.
By default, only ★ bright signals are shown to keep the chart clean. You can enable dim signals in settings if you want to see every zone touch. A configurable cooldown (default 10 bars) prevents signal spam.
All signals are non-repainting. They only appear on confirmed bar closes.
◈ How to Read the Dashboard
SMC AI ◈: header
Structure: current direction (▲ BULLISH / ▼ BEARISH / — RANGING) with bias label
Trend(50): whether the EMA trend agrees with structure (✓ ALIGNED = go / ✗ COUNTER = caution)
Best FVG: quality score of the highest-rated active FVG in the current direction, with visual bar
Best OB: quality score of the highest-rated active Order Block, with visual bar
Signal: last signal state (★ LONG / ○ SHORT / — WAITING) with the actual entry score
Zones: count of active bull/bear FVGs and OBs on chart
The Signal row shows the actual score from when the signal fired, so it always matches the label on the chart.
◈ Recommended Settings
Forex (EUR/USD, GBP/JPY) 1H to 4H: Swing Length 5, ATR 14, Trend EMA 50, Signal Cooldown 10
Forex scalping 15min: Swing Length 3, ATR 10, Trend EMA 34, Signal Cooldown 5
Crypto (BTC, ETH) 1H to 4H: Swing Length 5, ATR 14, Trend EMA 50, Signal Cooldown 10
Gold / Commodities 4H to Daily: Swing Length 7, ATR 14, Trend EMA 50, Signal Cooldown 15
Indices (NAS100, SPX500) 15min to 1H: Swing Length 3 to 5, ATR 10, Trend EMA 34, Signal Cooldown 8
For aggressive setups: Lower Min Signal Score to 40, enable dim signals, show more FVGs (8 to 10)
For conservative setups: Raise Min Signal Score to 70, filter FVGs to "High Only", increase cooldown
◈ Key Features
✓ Non-repainting: all signals confirmed on bar close
✓ AI zone scoring: 5-factor quality engine, 0-100 per zone
✓ Visual hierarchy: opacity reflects score, you instantly see what matters
✓ Mitigation tracking: filled FVGs and broken OBs fade automatically
✓ Rich tooltips: hover any signal for full breakdown
✓ 9 alert conditions: BOS, CHoCH, bull/bear signals, AI-confirmed signals
✓ Signal clutter control: cooldown + dim toggle keeps charts clean
✓ Fully customizable: colors, zone counts, thresholds, all adjustable
✓ 100% original code: not derived from any existing script
◈ What This Is NOT
This is not a "paint arrows and win" indicator. SMC/ICT trading requires understanding context. Where is structure pointing? Which zones are institutionally significant? Is the trend aligned? This indicator helps you answer those questions faster by scoring every zone objectively.
Always use proper risk management. Past performance does not guarantee future results.
Happy trading. Indicator

Polynomial Regression Clustering [LuxAlgo]The Polynomial Regression Clustering indicator utilizes K-Means clustering to categorize historical price data into discrete levels and fits polynomial regression curves to each identified cluster.
This tool allows traders to visualize non-linear trends within specific price regimes, providing a unique perspective on support, resistance, and price momentum.
🔶 USAGE
The indicator identifies "K" number of clusters based on the vertical distribution of price over a user-defined lookback period. Each cluster represents a group of bars that share similar price levels, and a polynomial regression line is calculated to represent the localized trend for that specific group.
🔹 Cluster Identification
The script groups price action into color-coded dots. By default, it uses the HL2 (Average price) to determine which cluster a bar belongs to. This is particularly useful for identifying historical value areas where price has spent a significant amount of time.
🔹 Polynomial Fitting
Unlike standard linear regression, which produces a straight line, the polynomial regression curves can bend to fit the data more accurately.
A Polynomial Degree of 1 will result in a standard linear regression (straight lines). A Polynomial Degree of 2 or higher allows for curves that capture parabolic moves or cyclical swings within each cluster.
🔹 Future Projections
The current active cluster (the one containing the most recent price point) can be projected into the future. This allows you to see where the localized trend for the current price regime is heading based on the mathematical fit of historical data.
🔶 DETAILS
🔹 K-Means Algorithm
The script uses an iterative K-Means algorithm to find the optimal centroids (center points) for the price levels. It calculates the distance of each price point to the nearest centroid and refines the centroid position until the clusters are stable or the maximum iterations are reached.
🔹 Regression Logic
Once price points are assigned to a cluster, the script solves for the coefficients of a polynomial equation that minimizes the distance between the line and the cluster's data points. To ensure numerical stability with higher degrees, the horizontal (time) axis is normalized before performing matrix operations.
🔶 SETTINGS
🔹 K-Means
Number of Clusters (K): Defines how many price levels the indicator should look for. Higher values create more granular levels. Lookback Period: The number of recent bars used to perform the clustering and regression calculation. Max Iterations: The maximum number of refinement steps for the K-Means algorithm.
🔹 Regression
Polynomial Degree: Controls the "bend" of the regression lines. Higher degrees allow for more complex curves. Extend All Fits to Current Bar: When enabled, the regression lines for all historical clusters are extended to the rightmost edge of the chart. Project Current Cluster into Future: Extends the current regime's regression line into the future (empty space) using a dashed line.
🔹 Visual Style
Show Regression Lines: Toggles the visibility of the polynomial curves. Show Cluster Dots: Toggles the visibility of the colored dots on each price bar. Dot Size: Adjusts the size of the cluster dots. Cluster Colors: Customizable colors for each of the identified clusters. Indicator

Big Tech AI vs AI Semi Market Cap
Recently, Big Tech stocks have faced downward pressure due to growing concerns over whether they can sustain massive AI CapEx and ultimately achieve monetization. In contrast, AI-related semiconductor stocks—the direct recipients of these investment funds—are rebounding and gaining momentum.
Some market participants compare this flow to the Dot-com bubble era. I created this script to track in real-time whether a true "Market Cap Flipping" (reversal) is occurring between the AI Service providers (Big Tech) and the AI Infrastructure providers (Semiconductors).
This indicator aggregates and compares the total Market Capitalization (Price × Shares Outstanding) of two distinct groups:
🟦 Big Tech (AI Solutions & Services): The companies spending heavily on AI infrastructure.
🟧 AI Semiconductors (Hardware & Infra): The companies benefiting from Big Tech's CapEx.
Real-time Comparison: Visualizes the aggregate value of both sectors on a single chart to spot divergence or convergence.
Cap Flipping Watch: Easily identify if the "Hardware" sector's valuation overtakes the "Solution" sector.
Percentage Ratio: Displays a label showing the Semiconductor sector's size relative to Big Tech (e.g., "Semi is 60% of Tech").
Customizable Tickers: You can toggle individual companies On/Off in the settings to adjust your basket.
Big Tech: MSFT, GOOGL, AMZN, META, AAPL, TSLA, PLTR, ORCL, ADBE
AI Semi: NVDA, TSM, AVGO, AMD, MU, ARM, ASML, ANET, MRVL
If the Orange Line (Semi) rises while the Blue Line (Tech) falls/stagnates, it indicates the market is favoring "Infrastructure Builders" over "Service Providers."
Use this to gauge the maturity of the AI investment cycle. Indicator
