Strong Gold NN Forecast | ProjectSyndicateStrong Gold NN Forecast turns the last five days of Gold into a single question, answered by a genuine neural network: where are today's HIGH and LOW most likely to land? Instead of a restyled oscillator, it runs a real multi-layer perceptron — trained offline on XAUUSD daily history, its weights baked into the script — and performs the forward pass live on your chart. Every new daily candle, it reads only completed bars, locks a forecast for that day's High, Low and Close at the open, and never moves it again. The whole network is drawn on the chart as an inspectable diagram — input, three hidden layers, output — with every node lit by its live activation and every connection weighted by the signal flowing through it. And every forecast that resolves is scored on a live accuracy panel against a naïve baseline — hits and misses alike — so you judge it on the instrument you trade, not on a number typed into a description.
🧠 Neural Core — the model is a 6·6·6·6·3 multi-layer perceptron: six inputs, three hidden layers of six tanh neurons, and three linear outputs, for 147 trained weights and biases. Its lifecycle each bar is FEATURE ▸ NORMALISE ▸ FORWARD ▸ RECONSTRUCT. The network was trained by backpropagation offline on XAUUSD daily data; the learned weight matrices are embedded directly in the script and the on-chart forward pass — weighted sums, biases, and tanh activations, layer by layer — reproduces the trained model exactly. Nothing is trained on your chart, so the mapping is fixed and deterministic.
🔢 Feature Anatomy — the fingerprint is six percentage-based ingredients, all derived from the last five completed days of OHLC plus RSI: 5-day momentum (mean daily return), range position (where the last close sits inside the 5-day high-low range), RSI(14) centred at 50, the 5-day average daily range %, the 5-day average candle body %, and a short-vs-medium momentum acceleration. Working in percentage space rather than raw price is what lets a model learn from a market that ran from the 2,600s into the 4,000s without the price level itself dominating the signal.
🧊 Frozen at the Open — this indicator does not repaint. Every input is read from candles that have already closed, and the forecast is anchored to the last completed close. That means the projected High, Low and Close for the current day are computed once when the candle opens and stay fixed until it closes — no sliding lines, no intrabar drift, no numbers that quietly improve as the session plays out.
🧭 No-Lookahead Normalisation — the part most on-chart ML gets wrong. Each feature is standardised against a causal rolling window of past bars only, computed live and identically to training. No future statistic ever touches a historical prediction: the forecast printed on any past bar is identical whether or not the bars after it exist. This is verified, not assumed.
📐 Volatility-Normalised Targets — the network does not predict raw High% and Low%; it predicts each excursion in units of the recent daily range, which the script measures live. The output is then rebuilt into a four-digit Gold price. Because the size of the move is expressed relative to current volatility, the same learned shape adapts automatically as the market shifts between calm and violent regimes instead of freezing the behaviour of the period it was trained on.
🕸️ Live Network Map — the model is not a black box. The full network is drawn to the right of price: an input column labelled with each feature, three hidden columns, and an output column carrying the four-digit High, Low and Close. Every node is shaded by its live activation and every connection is coloured by weight sign and brightened by the signal passing through it, so you can watch which inputs and pathways are actually driving today's forecast.
📊 Live Accuracy Panel — a compact dashboard reports, in real time: the setup and anchor close, the frozen High/Low/Close forecast with its implied % move and range, each input as a live z-score, and a running mean absolute error of the High and Low forecasts measured against the actual bars — shown next to the error of a naïve recent-range baseline. Every resolved forecast is counted, winners and misses in full, so the number is built live on your symbol and timeframe rather than advertised in advance.
🎚️ Controls — the map's size, horizontal position, column spacing, connection glow, node values and connection drawing are all adjustable, as are the forecast projection length, the shaded High-Low range, the historical prediction track, line width, two themes, and the dashboard's position and size. None of these change the model — they change how you read it.
🎯 Why this is different — most "AI" indicators restyle an oscillator and call the top; most that claim a neural network never show one. This runs an actual trained MLP, draws it live, normalises its inputs causally so there is no lookahead, freezes each forecast at the open so it cannot repaint, and reports an honest error tracked against a baseline instead of a marketing figure. You can see the network, see the inputs, and see how it has actually done on your chart.
🚀 Where to use it — the model was trained specifically on XAUUSD on the Daily timeframe, and that is where it is designed to run; the dashboard flags the setup when the symbol or timeframe differs. The first bars of any chart are a warm-up while the causal normalisation window fills, after which the forecast and the live accuracy panel come alive.
🎯 How to trade it
1 Apply it to XAUUSD on the Daily chart and let the causal window warm up until the dashboard reads a live forecast and the accuracy panel starts counting.
2 At each new daily candle, read the frozen High / Low / Close forecast and the shaded projected range — it is locked at the open and will not move.
3 Check the Live Accuracy panel: the High and Low mean-absolute-error against the naïve baseline tells you, on your own data, whether the model is adding anything right now.
4 Use the projected High and Low as context for where the session may stretch to — a reference for targets, fades, and stop placement — not as an automatic entry.
5 Combine the forecast with your own structure, levels, and risk management. It describes a likely daily envelope; it is not an entry-and-exit system on its own.
⚠️ Important — this is a decision-support tool, not a standalone buy/sell system, and it makes no performance guarantees. It is a fixed, pre-trained model: the weights were learned once on XAUUSD daily history and do not adapt on your chart, so bars inside that training period are in-sample by nature — genuine out-of-sample behaviour is what you see going forward on the live panel. In leakage-free walk-forward testing the network's High/Low error modestly beat a naïve recent-range baseline (strongest on the Low), at roughly 0.7–0.9% of price; that is a small, real edge, not a crystal ball, and on some periods it will sit close to the baseline. Forecasting a single day's exact high and low is inherently hard, and a sharp regime shift or a shock can run straight through any daily envelope. It is deliberately a small network — larger nets overfit this much daily data and test worse. Always wait for the candle to open so the forecast is frozen, and test it on your own data before trading it live. 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

AI Source Switching Moving Average (Zeiierman)█ Overview
The AI Source Switching Moving Average is an adaptive price-selection and trend intelligence system that combines historical analog recognition, machine learning classification, neural learning, feature optimization, dynamic source selection, and AI-driven trend management into a single framework.
Rather than calculating a moving average from a fixed source such as Close, Open, High, or Low, the indicator continuously evaluates which price source currently contains the most useful market information.
The script transforms each OHLC source into a multi-dimensional feature space, stores historical behavior, searches for similar historical environments, and allows those analogs to vote on which source currently provides the highest predictive value.
An adaptive feature-weighting engine continuously learns which characteristics best separate bullish and bearish conditions, while an online neural model adds a second layer of directional intelligence.
█ Why Is This One Unique
Most moving averages are static.
You select a source:
• Close
• Open
• High
• Low
Then the moving average simply smooths that source. This indicator does something fundamentally different.
Instead of assuming one source is always optimal, it continuously evaluates all four OHLC streams and determines which source currently contains the strongest information based on historical behavior.
The indicator effectively asks:
"Which price source has historically produced the best outcome under conditions most similar to the current market?"
That selected source then becomes the input for the moving average and AI Supertrend. This transforms a traditional moving average into a dynamic source-selection engine.
█ How It Works
⚪ Builds Multi-Dimensional OHLC Features
The model does not analyze raw prices directly.
Each OHLC source is transformed into a behavioral fingerprint consisting of:
• Trend Structure
• Mean-Reversion State
• Momentum
• Volatility Profile
• Range Position
• Price Slope
Every source becomes its own market state representation.
oT = featTrend(open, atrNow)
oM = featMean(open)
oMo = featMomentum(open)
oV = featVol(open)
oR = featRange(open)
oS = featSlope(open, atrNow)
The same feature process is applied to High, Low, and Close.
hT = featTrend(high, atrNow)
lT = featTrend(low, atrNow)
cT = featTrend(close, atrNow)
Instead of asking:
"Where is price?"
The model asks:
"How is this source behaving?"
⚪ Creates A Historical Memory Bank
Every confirmed bar is stored together with:
• Source feature state
• Future market outcome
• Volatility-normalized labels
This becomes the learning dataset.
moveFwd = close - close
bandFwd = learnAtrFactor * atrNow
outcome = moveFwd > 2 * bandFwd ? 3 :
moveFwd > bandFwd ? 2 :
moveFwd > 0 ? 1 :
moveFwd < -2 * bandFwd ? -3 :
moveFwd < -bandFwd ? -2 :
moveFwd < 0 ? -1 : 0
Each stored row contains the feature snapshot plus the outcome label.
rowO = makeRow(oT , oM , oMo , oV , oR , oS , outcome)
Each confirmed observation becomes a real historical example the model can reference later.
if barstate.isconfirmed and bar_index > horizonBars + 120
if validO
addBank(bankO, rowO, memoryDepth)
addBank(bankAll, rowO, memoryDepth * 4)
⚪ Uses Historical Analog Matching
Once enough data has been collected, the model begins searching for historical situations that resemble current conditions.
Similarity is measured using a compressed Lorentzian-style distance function:
compress(d) =>
math.log(1.0 + math.abs(d))
The gap between the current feature state and each historical row is then calculated across all features.
gapTo(t, m, mo, v, r, s, array row) =>
wT * compress(t - row.get(0)) +
wM * compress(m - row.get(1)) +
wMo * compress(mo - row.get(2)) +
wV * compress(v - row.get(3)) +
wR * compress(r - row.get(4)) +
wS * compress(s - row.get(5))
This helps reduce outlier influence and prevents any single feature from dominating the comparison process.
The goal is not to find identical charts. The goal is to find historically similar market environments.
⚪ Let Historical Analogs Vote
After finding the closest historical examples, the model allows them to vote.
Closer analogs receive greater influence. More distant analogs contribute less.
wg = 1.0 / (1.0 + g)
score += cls * wg
bull += cls > 0 ? wg : 0.0
bear += cls < 0 ? wg : 0.0
The weighted voting system produces:
• Analog Score
• Directional Bias
• Agreement Fraction
• Similarity Tightness
• Market Conviction
analog = total > 0 ? score / total : 0.0
dir = analog > 0.15 ? 1 : analog < -0.15 ? -1 : 0
agree = total > 0 ? (dir == 1 ? bull : dir == -1 ? bear : 0.0) / total : 0.0
tight = clamp(1.0 - avgGap / gapScale, 0.0, 1.0)
This creates a probabilistic ranking system rather than a binary signal engine.
⚪ Auto-Optimizes Feature Importance
Different markets reward different behaviors.
A feature that is extremely predictive today may become less useful tomorrow. The indicator solves this problem using adaptive Fisher-discriminant optimization.
The engine continuously measures which features best separate bullish outcomes from bearish outcomes.
f = math.pow(meanB - meanS, 2) / (varB + varS + 0.000001)
• Features with higher predictive value receive larger weights.
• Features with lower predictive value gradually lose influence.
norm = maxF > 0 ? fish.get(j) / maxF : 1.0
imp.set(j, math.max(floor, norm * 8.0))
The optimized weights are smoothed over time.
wAuto.set(j, prev + fisherSpeed * (wRaw.get(j) - prev))
This allows the model to adapt automatically without requiring manual optimization.
⚪ Adds Neural Learning
Beyond analog classification, the indicator includes an online neural learning layer.
The neural model continuously updates itself using confirmed market outcomes and adjusts internal directional bias over time.
neuralScore(t, m, mo, v, r, s) =>
nt * t + nm * m + nmo * mo + nv * v + nr * r + ns * s + nb
The neural layer evaluates:
• Trend Structure
• Mean Reversion
• Momentum
• Volatility
• Range Position
• Slope Behavior
Training is performed using an Adam-style optimizer.
adam(weight, grad, mom, vel, step) =>
newMom = beta1 * mom + (1.0 - beta1) * grad
newVel = beta2 * vel + (1.0 - beta2) * grad * grad
mHat = newMom / (1.0 - math.pow(beta1, step))
vHat = newVel / (1.0 - math.pow(beta2, step))
newWeight = weight - learnRate * mHat / (math.sqrt(vHat) + eps)
This creates a second intelligence layer that works alongside the analog engine.
⚪ Ranks All Four Sources
Every bar receives independent scores for:
• Open
• High
• Low
• Close
rO = rankSource(oT, oM, oMo, oV, oR, oS, oAnalog, oAgree, oTight, oK)
rH = rankSource(hT, hM, hMo, hV, hR, hS, hAnalog, hAgree, hTight, hK)
rL = rankSource(lT, lM, lMo, lV, lR, lS, lAnalog, lAgree, lTight, lK)
rC = rankSource(cT, cM, cMo, cV, cR, cS, cAnalog, cAgree, cTight, cK)
The ranking combines:
• Analog Classification Strength
• Historical Agreement
• Similarity Quality
• Feature Separation
• Neural Confidence
rankSource(t, m, mo, v, r, s, analog, agree, tight, k) =>
neural = useNeural ? neuralScore(t, m, mo, v, r, s) : 0.0
directional = math.abs(analog) / 3.0
raw = directional * 0.35 + agree * 0.25 + tight * 0.20 + normScore(neural) * neuralInfluence + (k >= kNeighbors ? 0.10 : 0.0)
clamp(raw, 0.0, 1.0)
The highest-ranked source becomes the active source for both the moving average and Supertrend.
bestId = safeRO >= safeRH and safeRO >= safeRL and safeRO >= safeRC ? 0 :
safeRH >= safeRL and safeRH >= safeRC ? 1 :
safeRL >= safeRC ? 2 : 3
This means the indicator can dynamically switch between Open, High, Low, and Close depending on which source currently demonstrates the strongest historical edge.
⚪ Builds An Adaptive AI Moving Average
After selecting the best source, the indicator calculates a moving average using that dynamically chosen input.
hardSrc = bestId == 0 ? open :
bestId == 1 ? high :
bestId == 2 ? low : close
The selected source is then smoothed and passed into the moving-average engine.
aiSourceRaw = hardSrc
aiSource = ta.ema(aiSourceRaw, srcSmoothLen)
aiMA = ma(aiSource, maLen, maType)
Unlike traditional averages that remain tied to a fixed source, the AI MA continuously adapts to changing market conditions.
The result is a smoother and more context-aware trend representation.
█ Main Weakness
The indicator is not deep learning.
It does not train a large neural network.
Instead, it operates as an online analog classifier enhanced by adaptive feature weighting and lightweight neural optimization.
Because it learns from historical analogs, performance can vary depending on:
• Symbol
• Timeframe
• Market Regime
• Memory Depth
• Feature Configuration
• Learning Horizon
As with all adaptive systems, historical similarity does not guarantee future outcomes.
█ How To Use
⚪ Reading The AI Moving Average
• Rising average = bullish conditions dominate.
• Falling average = bearish conditions dominate.
• Strong slope = stronger trend conviction.
• Flat slope = weaker directional conviction.
The AI Moving Average can be used much like a traditional moving average, but with the added benefit of dynamic source selection.
Use it for:
• Identifying trend direction
• Spotting trend changes
• Confirming momentum shifts
• Dynamic support and resistance analysis
• Pullback and retest opportunities
• Trend continuation setups
In bullish conditions , traders may look for price to remain above the moving average and use pullbacks into the average as potential continuation zones.
In bearish conditions , traders may look for price to remain below the moving average and use rallies into the average as potential resistance areas.
⚪ Reading The AI Supertrend
The AI Supertrend acts as:
• Trend Filter
• Dynamic Trailing Stop
• Market Structure Guide
• Bullish flips indicate positive trend conditions.
• Bearish flips indicate negative trend conditions.
Because the band width adapts to model confidence, trend changes become more responsive during strong conditions and more tolerant during weak conditions.
Use the AI Supertrend for:
• Trend confirmation
• Trade management
• Trailing stop placement
• Exit planning
• Market structure analysis
• Trend-following systems
Many traders may choose to remain long while price stays above the bullish trail and remain short while price stays below the bearish trail.
The Supertrend can also be used as a dynamic stop-loss framework, allowing positions additional room during uncertain conditions while tightening risk management when the AI model detects stronger directional conviction.
█ Settings
MA Type: Selects the moving average formula used after source selection.
MA Length: Controls the smoothing period of the AI moving average.
AI Source Smoothing: Smooths source transitions after source switching.
Memory Depth: Controls how many historical examples are stored.
Analog Count: Controls how many historical analogs participate in voting.
Learning Horizon: Controls how far ahead outcomes are evaluated.
Analog Spacing: Controls sampling diversity within the memory bank.
Learning Sensitivity × ATR: Controls how future outcomes are classified.
Use Neural Online Training: Enables the adaptive neural learning layer.
Neural Influence: Controls neural contribution to source ranking.
Learning Rate: Controls neural adaptation speed.
Huber Delta: Controls error sensitivity during training.
Auto Optimize Feature Weights: Enables adaptive feature importance learning.
Adaptation Speed: Controls weight adjustment speed.
Weight Floor: Sets minimum feature influence.
Minimum Rows: Controls when Fisher optimization becomes active.
Show AI Supertrend: Displays the adaptive trail.
ATR Length: Controls volatility measurement.
ATR Multiplier: Controls trail width.
AI Band Adaptivity: Controls AI influence over trail width.
-----------------
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

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

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

Machine Learning: seMLP Q-Wavelet RL Engine [Jamallo]Author Note: I always get asked: "How can I build a Machine Learning or Artificial Intelligence trading system?" I created the study "Machine Learning: seMLP Q-Wavelet RL Engine" to showcase exactly how it can be done in a beginner-friendly manner. We will break down exactly how this AI thinks in plain English, and then show you exactly how the Pine Script code executes it step-by-step.
Introduction: The Institutional Approach to Algorithmic Trading
Most retail and algorithmic traders spend years searching for the "holy grail" by combining static indicators and hard-coded `IF/THEN` rule sets. They are often unaware that institutional quant desks abandoned those basic, curve-fitted patterns decades ago. Standard algorithmic analysis fails because financial markets are inherently chaotic—a hardcoded strategy that works perfectly in a backtest will systematically break down during a live regime shift.
To acquire a true institutional edge, algorithmic strategies cannot rely on rigid, backwards-looking formulas; they require a system that adapts dynamically in real-time. This script brings that quantitative firepower directly to your chart by constructing a live Self-Teaching AI .
Dynamic Filtering : It uses advanced frequency mathematics (Wavelets) to separate random market noise from true institutional momentum footprints with near-zero lag.
Artificial Brain : It feeds that data into a neural network—a living matrix of artificial "neurons" that continuously analyze and execute decisions.
Self-Correction : Most importantly, it executes Reinforcement Learning. If a trade fails, the AI actively calculates the error and mathematically rewires its own brain, ensuring it constantly evolves to survive changing market conditions.
Ultimately, this serves as a foundational study showing you exactly how to break away from basic scripting and get started in true Quantitative Algorithmic Trading.
1. The Core Architecture Loop
Here is the high-level flow of how the AI thinks on every single candle:
The Invisible "Burn-In" Phase
Because the AI starts with a completely randomized, "empty" brain, it will make terrible decisions on the very first few candles. To prevent it from acting prematurely on live data, the script executes an aggressive Burn-In Phase (e.g., the first 300 bars of the chart). During this period, the indicator is completely invisible. It aggressively executes hundreds of "mock trades" in the background, tracking virtual PnL, taking massive risks, and rapidly rewiring its brain without showing a single signal on your screen. Once the 300 bars are up, the burn-in phase ends. The AI stops acting recklessly and officially enters "Live Trading" mode with a fully trained, highly-intelligent brain.
SECTIONS 2 & 3: Setting Up the Brain
Conceptual Overview
Imagine the brain as a massive team of financial analysts.
We have 16 junior analysts looking at chart data.
They report their findings up to 12 senior analysts.
The seniors report to 6 directors.
The 6 directors send their final opinions to 3 executives representing the 3 possible actions: `BUY, SELL, HOLD`. This is called a 16 → 12 → 6 → 3 network structure.
Before we hand the price data to the junior analysts, we Normalize it (Z-Score). This just means "leveling the playing field" so a massive $500 candle wick doesn't break the analysts' math compared to a tiny $1 movement.
The Code Breakdown
// Section 2: Brain Size Constants
int NI = 16 // 16 Inputs (Junior analysts)
int NH1 = 12 // 12 Hidden layer 1 nodes
int NH2 = 6 // 6 Hidden layer 2 nodes
int NO = 3 // 3 Outputs
// Section 3: Normalization Helper
norm(series float x, simple int win) =>
float mu = ta.sma(x, win)
float sg = ta.stdev(x, win)
float sf = nz(sg) < 1e-10 ? 1.0 : sg
float res = (x - nz(mu, x)) / sf // Levels out the price data
na(res) ? 0.0 : res
SECTIONS 4 & 5: Giving the AI "Memory"
Conceptual Overview
By default, PulseWire indicators suffer from permanent amnesia! Every time a new candle paints, PulseWire completely deletes its short-term memory and forgets what happened on the last candle. If we are building an AI for trading that needs to "learn", it must be able to remember its past mathematical mistakes.
To force PulseWire to remember, we use special variables called `var` to create "Persistent Memory Matrices" where the AI for trading stores its brain's wiring throughout the entire chart history.
The Code Breakdown
// Using 'var' locks the memory so it never resets when a new candle paints
var matrix W1 = matrix.new(NI, NH1, 0.0) // The connections between neurons
var matrix W2 = matrix.new(NH1, NH2, 0.0)
...
var int pos = 0 // The AI remembers its current position: Long (1), Short (-1), or Flat (0)
SECTION 6: Seeing the Market (Wavelets)
Conceptual Overview
If you use a Moving Average, it always "lags" behind the real price. By the time the Moving Average crosses to tell you to buy, the massive breakout has already happened.
To fix this, we teach the AI for trading to see using Haar Wavelets . A Wavelet is a piece of advanced math that splits the price candle with minimal lag into two things:
The Detail (D) : The immediate, rapid volatility chop.
The Smooth (V) : The true underlying smooth momentum. By looking at the detail and momentum completely separately, the AI for trading can react to shifts with minimal lag.
The Code Breakdown
// We take standard features like Open, Close, and Volume:
float f0 = open
float f1 = close...
// We break them into Wavelets using simple math combinations:
float v1_0 = (f0 + nz(f0 , f0)) / 2.0 // Smooth momentum
float d1_0 = (f0 - nz(f0 , f0)) / 2.0 // Instant volatility detail
...
// We pack all 16 traits into the 'feat' array to feed the AI for trading's Brain
feat.set(0, norm(d1_0, i_normWin))
feat.set(14, float(pos)) // Tells the brain its current trade position
feat.set(15, norm(portRet, i_normWin)) // Tells the brain its current open trade return
SECTION 7: How the Brain Thinks (seMLP)
Conceptual Overview
An "MLP" is just a standard Neural Network (a massive web of variables that pass data to each other). The problem is that if you give PulseWire an insanely massive web of math equations, it will crash and throw a compiler timeout error.
So, we use a Self-evolving MLP (seMLP) . The AI pushes the Wavelet data through its network dynamically. To prevent "dead zones" where a neuron just stops firing in a flat market, it uses a formula called LeakyReLU . It basically acts as a gatekeeper that tells the neuron: "If this signal is incredibly weak, shrink it down to 1%, but don't explicitly delete it."
The Code Breakdown
// The data enters Hidden Layer 1 (h1)
array h1 = array.new(NH1, 0.0)
for j = 0 to NH1 - 1
float s = B1.get(j)
// The inner brain loops through all 16 incoming inputs
for i = 0 to NI - 1
s += feat.get(i) * W1.get(i, j)
// LeakyReLU Formula: f(x) = x if x > 0 else 0.01 * x
// If the signal 's' is positive, keep it. If 's' is negative, shrink to 1%
h1.set(j, s > 0 ? s : 0.01 * s)
SECTION 8: Taking Action (Exploration vs Exploitation)
Conceptual Overview
How does the AI actually press the BUY or SELL button? It calculates a "Confidence Score" (called a Q-Value) for all three options— Buy, Sell, and Hold. The highest score wins and executes the trade.
However, during its invisible "Burn-In Period", the AI uses a variable called Epsilon . Think of Epsilon as a dice roll. Sometimes, instead of making the smartest, highest-scoring choice, the AI will randomly pick a completely stupid trade just to "experiment" and see if a hidden market pattern exists! This is conceptually how AI for trading discovers new, out-of-the-box strategies. As training goes on, Epsilon gets smaller, and the AI stops experimenting.
The Code Breakdown
// Calculate Epsilon: Start at a high 50% and slowly decay to 5% over time
float epsilon = bar_index <= i_burnIn ? math.max(0.05, i_epsStart_val * ...)
// Roll the dice. If the random number is less than epsilon, we experiment randomly!
bool explore = math.random(0.0, 1.0) < epsilon
// Find the AI for trading's highest confidence choice: Q(0) = Buy, Q(1) = Sell, Q(2) = Hold
if Q.get(1) > bestQ // If Sell confidence is higher than current best (Buy)...
bestQ := Q.get(1)
bestAct := 1
if Q.get(2) > bestQ // If Hold is even higher...
bestQ := Q.get(2)
bestAct := 2
// Execute the final action
int act = explore ? math.min(int(math.floor(math.random(0.0, 2.999))), 2) : qArg
SECTION 9: Training with Rewards (Reinforcement Learning)
Conceptual Overview
This is the heart of Machine Learning. It functions exactly like training a pet. If the AI makes a winning trade that generates cash, we give it a mathematical "treat" (a positive reward). If the AI loses money, we hit it with a brutal negative reward. Over time, the AI autonomously refines its neural weights exclusively to collect the maximum amount of "treats".
The Code Breakdown
// Calculate how much money the candle moved
float cRet = nz((close - close ) / close , 0.0)
// The Reward (R) is a combination of three factors:
// 1. PnL (rPn) - Did we make raw cash profit?
// 2. Trail (rTn) - Did we efficiently track the trend?
// 3. Lee (rLee) - A shaping bonus for correct directional positioning.
float R = i_alphaT * rTn + i_alphaP * rPn + 0.1 * rLee
SECTION 10: Learning from Mistakes (Backpropagation)
Conceptual Overview
If the AI's trade failed, how does it adjust its internal logic? It uses a process called Backpropagation . It looks at the Reward it just received, realizes it was horribly wrong, and calculates the "Error Margin" (How far off my prediction was I?). It then mathematically rewrites all of the internal connections `(W1, W2, W3)` in reverse, editing them to be slightly smarter for the next candle!
Because updating a massive brain on every single micro-tick causes chaotic glitches, we "Accumulate" the errors in a batch over several candles, and then update the brain smoothly with the batch average.
The Code Breakdown
// Compare the Target Reward vs what the Brain actually Predicted (Temporal Difference Error)
float tgt = R + i_gamma * max_qt
float td = tgt - pOut.get(prevAct)
// Accumulate the backwards gradients over multiple bars so we don't glitch
for j = 0 to NO - 1
gB3_acc.set(j, gB3_acc.get(j) + g3.get(j))
accumCount += 1
// Once 'i_accumSteps' bars have passed, we apply the compiled batch update to 'Rewire' the Brain weights!
if accumCount >= i_accumSteps
for i = 0 to NH2 - 1
for j = 0 to NO - 1
float dw = gW3_acc.get(i, j) * sc
W3.set(i, j, W3.get(i, j) + clr * dw - clr * i_l2 * W3.get(i, j))
SECTION 11: Link Pruning (Making the Brain Faster)
Conceptual Overview
Stage 1: The Initial Brain (Complex & Slow)
Stage 2: The Pruning Decision
Stage 3: The Optimized AI for trading (Sleek & Fast)
As the brain learns, some of the mathematical connections become totally useless. Having a giant Tradingview indicator calculate hundreds of useless math connections will trigger a calculation timeout. At a specific point in training length (defaulting to the end of the 300-bar burn-in period), the script literally pauses and deletes (zeroes out) the weakest neural links. PulseWire skips over calculations containing plain zeroes, making your indicator insanely fast and completely lag-proof.
The Code Breakdown
if bar_index == i_pruneBar and not pruned
// Evaluate every single connection weight...
// Find the bottom weakest percentage (i_prunePct)
float thr = absW.get(pidx)
// Explicitly set the weakest weights to Zero!
for i = 0 to NI - 1
for j = 0 to NH1 - 1
if math.abs(W1.get(i, j)) <= thr
W1.set(i, j, 0.0) // Permanent pruning: weak link removed
Important Disclaimer
This indicator is published strictly for educational and research purposes. It is a conceptual showcase proving that advanced Deep Reinforcement Learning architectures generally reserved for Python/TensorFlow can be natively executed within the PulseWire Pine Script environment. Due to Pine Script's structural time-series limitations—specifically the lack of a random-access historical buffer required for true experience replay—this is NOT intended for practical live trading. For production-grade deployment, it is highly recommended to port this mathematical framework to Python.
References
This indicator's mathematical engine was directly modeled and bridged from the following quantitative research papers:
Lee et al. (2021) — " Learning to trade in financial time series using high-frequency through wavelet transformation and deep reinforcement learning " (Used for the MODWT Wavelet integration & State architecture).
Tsantekidis et al. (2021) — " Price Trailing for Financial Trading using Deep Reinforcement Learning " (Used for the dynamic margin-trailing reward system).
Seow et al. (2021) — " seMLP: Self-evolving Multi-layer Perceptron " (Used for the 16 → 12 → 6 → 3 sparse Neural Network structure and the automatic Link Pruning logic).
Indicator

SNP420 - SAO - Ultima - Multi-Asset Momentum IndicatorMulti-timeframe trend-following indicator for H1 charts. Combines D1 + H4 trend alignment with H1 entry precision using EMA, RSI, MACD, and ADX filters. Designed for EURUSD, USDJPY, and GBPUSD during London/NY
sessions.
Entry: Requires D1 and H4 trend agreement, price above/below EMA21, RSI in momentum zone (50-75 long / 25-50 short), positive MACD histogram, and ADX above 25. Signals only fire during active sessions (London,
Overlap, NY).
Exit logic (8 layers, priority-ordered): Hard SL at 2.5×ATR, TP at 5R, trailing stop from 2R profit, breakeven protection at 2R, stale position killer at 8 bars, D1/H4 trend reversal exits, and adaptive time
stops (48 bars losers / 96 bars winners).
On-chart display: Entry arrows (LONG/SHORT), color-coded exit labels (SL, TP, TRAIL, BE, STALE, FLIP, TIME), live SL/TP/trail level lines, trend background shading, EMA ribbon (21/50/200), and real-time info
panel showing D1/H4 trend, ADX, RSI, session status, and position state. Built-in alerts for all entry and exit events.
Backtested: +448% in 2025 (12/12 months profitable), +107% in 2026 Q1. Profit driven by TRAIL exits (100% WR, 83% of total profit). Robust across 10 synthetic market Monte Carlo scenarios (100% profitable, avg
78% of backtest performance).
Piece and love. 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

Ghost Candles👻 Ghost Candles - Predictive Market Projection
Ghost Candles is an advanced forward-projection indicator that visualizes potential future price action directly on your chart using dynamically generated “ghost” candles.
Unlike traditional indicators that lag or react, Ghost Candles attempts to anticipate short-term market structure by learning from real-time order-flow proxies, volatility, and price behavior.
🔍 What It Does:
Ghost Candles projects up to 32 future candles ahead of the current price, rendering them as semi-transparent candles that evolve in real time.
These projections are not static - they continuously adapt as new data comes in, giving you a live, evolving forecast of market direction and structure.
⚙️ How It Works:
At its core, Ghost Candles uses a lightweight neural network trained directly on-chart.
The model updates itself every bar, adapting to changing market conditions without external data.
🧠 How to Use:
Ghost Candles is best used as a contextual tool, not a standalone signal generator.
Use it to:
Anticipate short-term directional bias
Visualize potential continuation vs reversal scenarios
Identify compression before expansion
Gauge market hesitation or momentum build-up
⚠️ Important Notes:
This indicator is predictive and experimental, not deterministic
Projections will change as new data comes in (especially on live bars)
Best used alongside structure, liquidity, and confirmation tools
Not financial advice Indicator

Neural RibbonNeural Ribbon:
6 independent neural networks running live on your chart. Five predict price direction at different horizons (T+2 through T+32), forming the ribbon. A sixth "trader" network reads all five predictions, their gradients, and multi-timeframe order flow to generate entry and exit signals.
When a trade closes, the actual P&L retrains the trader via reinforcement learning - wins reinforce the pattern, losses suppress it. All trade parameters (entry threshold, stop loss, take profit, hold time, cooldown) self-adjust based on rolling performance. No curve-fitting, no static rules. The system evolves on every trade. Recommended on BTCUSDT 15m where the RL loop has been most thoroughly validated. Indicator

Indicator

Institutional Levels (CNN) - [PhenLabs]📊Institutional Levels (Convolutional Neural Network-inspired)
Version : PineScript™v6
📌Description
The CNN-IL Institutional Levels indicator represents a breakthrough in automated zone detection technology, combining convolutional neural network principles with advanced statistical modeling. This sophisticated tool identifies high-probability institutional trading zones by analyzing pivot patterns, volume dynamics, and price behavior using machine learning algorithms.
The indicator employs a proprietary 9-factor logistic regression model that calculates real-time reaction probabilities for each detected zone. By incorporating CNN-inspired filtering techniques and dynamic zone management, it provides traders with unprecedented accuracy in identifying where institutional money is likely to react to price action.
🚀Points of Innovation
● CNN-Inspired Pivot Analysis - Advanced binning system using convolutional neural network principles for superior pattern recognition
● Real-Time Probability Engine - Live reaction probability calculations using 9-factor logistic regression model
● Dynamic Zone Intelligence - Automatic zone merging using Intersection over Union (IoU) algorithms
● Volume-Weighted Scoring - Time-of-day volume Z-score analysis for enhanced zone strength assessment
● Adaptive Decay System - Intelligent zone lifecycle management based on touch frequency and recency
● Multi-Filter Architecture - Optional gradient, smoothing, and Difference of Gaussians (DoG) convolution filters
🔧Core Components
● Pivot Detection Engine - Advanced pivot identification with configurable left/right bars and ATR-normalized strength calculations
● Neural Network Binning - Price level clustering using CNN-inspired algorithms with ATR-based bin sizing
● Logistic Regression Model - 9-factor probability calculation including distance, width, volume, VWAP deviation, and trend analysis
● Zone Management System - Intelligent creation, merging, and decay algorithms for optimal zone lifecycle control
● Visualization Layer - Dynamic line drawing with opacity-based scoring and optional zone fills
🔥Key Features
● High-Probability Zone Detection - Automatically identifies institutional levels with reaction probabilities above configurable thresholds
● Real-Time Probability Scoring - Live calculation of zone reaction likelihood using advanced statistical modeling
● Session-Aware Analysis - Optional filtering to specific trading sessions for enhanced accuracy during active market hours
● Customizable Parameters - Full control over lookback periods, zone sensitivity, merge thresholds, and probability models
● Performance Optimized - Efficient processing with controlled update frequencies and pivot processing limits
● Non-Repainting Mode - Strict mode available for backtesting accuracy and live trading reliability
🎨Visualization
● Dynamic Zone Lines - Color-coded support and resistance levels with opacity reflecting zone strength and confidence scores
● Probability Labels - Real-time display of reaction probabilities, touch counts, and historical hit rates for active zones
● Zone Fills - Optional semi-transparent zone highlighting for enhanced visual clarity and immediate pattern recognition
● Adaptive Styling - Automatic color and opacity adjustments based on zone scoring and statistical significance
📖Usage Guidelines
● Lookback Bars - Default 500, Range 100-1000, Controls the historical data window for pivot analysis and zone calculation
● Pivot Left/Right - Default 3, Range 1-10, Defines the pivot detection sensitivity and confirmation requirements
● Bin Size ATR units - Default 0.25, Range 0.1-2.0, Controls price level clustering granularity for zone creation
● Base Zone Half-Width ATR units - Default 0.25, Range 0.1-1.0, Sets the minimum zone width in ATR units for institutional level boundaries
● Zone Merge IoU Threshold - Default 0.5, Range 0.1-0.9, Intersection over Union threshold for automatic zone merging algorithms
● Max Active Zones - Default 5, Range 3-20, Maximum number of zones displayed simultaneously to prevent chart clutter
● Probability Threshold for Labels - Default 0.6, Range 0.3-0.9, Minimum reaction probability required for zone label display and alerts
● Distance Weight w1 - Controls influence of price distance from zone center on reaction probability
● Width Weight w2 - Adjusts impact of zone width on probability calculations
● Volume Weight w3 - Modifies volume Z-score influence on zone strength assessment
● VWAP Weight w4 - Controls VWAP deviation impact on institutional level significance
● Touch Count Weight w5 - Adjusts influence of historical zone interactions on probability scoring
● Hit Rate Weight w6 - Controls prior success rate impact on future reaction likelihood predictions
● Wick Penetration Weight w7 - Modifies wick penetration analysis influence on probability calculations
● Trend Weight w8 - Adjusts trend context impact using ADX analysis for directional bias assessment
✅Best Use Cases
● Swing Trading Entries - Enter positions at high-probability institutional zones with 60%+ reaction scores
● Scalping Opportunities - Quick entries and exits around frequently tested institutional levels
● Risk Management - Use zones as dynamic stop-loss and take-profit levels based on institutional behavior
● Market Structure Analysis - Identify key institutional levels that define current market structure and sentiment
● Confluence Trading - Combine with other technical indicators for high-probability trade setups
● Session-Based Strategies - Focus analysis during high-volume sessions for maximum effectiveness
⚠️Limitations
● Historical Pattern Dependency - Algorithm effectiveness relies on historical patterns that may not repeat in changing market conditions
● Computational Intensity - Complex calculations may impact chart performance on lower-end devices or with multiple indicators
● Probability Estimates - Reaction probabilities are statistical estimates and do not guarantee actual market outcomes
● Session Sensitivity - Performance may vary significantly between different market sessions and volatility regimes
● Parameter Sensitivity - Results can be highly dependent on input parameters requiring optimization for different instruments
💡What Makes This Unique
● CNN Architecture - First indicator to apply convolutional neural network principles to institutional-level detection
● Real-Time ML Scoring - Live machine learning probability calculations for each zone interaction
● Advanced Zone Management - Sophisticated algorithms for zone lifecycle management and automatic optimization
● Statistical Rigor - Comprehensive 9-factor logistic regression model with extensive backtesting validation
● Performance Optimization - Efficient processing algorithms designed for real-time trading applications
🔬How It Works
● Multi-timeframe pivot identification - Uses configurable sensitivity parameters for advanced pivot detection
● ATR-normalized strength calculations - Standardizes pivot significance across different volatility regimes
● Volume Z-score integration - Enhanced pivot weighting based on time-of-day volume patterns
● Price level clustering - Neural network binning algorithms with ATR-based sizing for zone creation
● Recency decay applications - Weights recent pivots more heavily than historical data for relevance
● Statistical filtering - Eliminates low-significance price levels and reduces market noise
● Dynamic zone generation - Creates zones from statistically significant pivot clusters with minimum support thresholds
● IoU-based merging algorithms - Combines overlapping zones while maintaining accuracy using Intersection over Union
● Adaptive decay systems - Automatic removal of outdated or low-performing zones for optimal performance
● 9-factor logistic regression - Incorporates distance, width, volume, VWAP, touch history, and trend analysis
● Real-time scoring updates - Zone interaction calculations with configurable threshold filtering
● Optional CNN filters - Gradient detection, smoothing, and Difference of Gaussians processing for enhanced accuracy
💡Note
This indicator represents advanced quantitative analysis and should be used by traders familiar with statistical modeling concepts. The probability scores are mathematical estimates based on historical patterns and should be combined with proper risk management and additional technical analysis for optimal trading decisions. Indicator

Indicator

CNN Statistical Trading System [PhenLabs]📌 DESCRIPTION
An advanced pattern recognition system utilizing Convolutional Neural Network (CNN) principles to identify statistically significant market patterns and generate high-probability trading signals.
CNN Statistical Trading System transforms traditional technical analysis by applying machine learning concepts directly to price action. Through six specialized convolution kernels, it detects momentum shifts, reversal patterns, consolidation phases, and breakout setups simultaneously. The system combines these pattern detections using adaptive weighting based on market volatility and trend strength, creating a sophisticated composite score that provides both directional bias and signal confidence on a normalized -1 to +1 scale.
🚀 CONCEPTS
• Built on Convolutional Neural Network pattern recognition methodology adapted for financial markets
• Six specialized kernels detect distinct price patterns: upward/downward momentum, peak/trough formations, consolidation, and breakout setups
• Activation functions create non-linear responses with tanh-like behavior, mimicking neural network layers
• Adaptive weighting system adjusts pattern importance based on current market regime (volatility < 2% and trend strength)
• Multi-confirmation signals require CNN threshold breach (±0.65), RSI boundaries, and volume confirmation above 120% of 20-period average
🔧 FEATURES
Six-Kernel Pattern Detection:
Simultaneous analysis of upward momentum, downward momentum, peak/resistance, trough/support, consolidation, and breakout patterns using mathematically optimized convolution kernels.
Adaptive Neural Architecture:
Dynamic weight adjustment based on market volatility (ATR/Price) and trend strength (EMA differential), ensuring optimal performance across different market conditions.
Professional Visual Themes:
Four sophisticated color palettes (Professional, Ocean, Sunset, Monochrome) with cohesive design language. Default Monochrome theme provides clean, distraction-free analysis.
Confidence Band System:
Upper and lower confidence zones at 150% of threshold values (±0.975) help identify high-probability signal areas and potential exhaustion zones.
Real-Time Information Panel:
Live display of CNN score, market state with emoji indicators, net momentum, confidence percentage, and RSI confirmation with dynamic color coding based on signal strength.
Individual Feature Analysis:
Optional display of all six kernel outputs with distinct visual styles (step lines, circles, crosses, area fills) for advanced pattern component analysis.
User Guide
• Monitor CNN Score crossing above +0.65 for long signals or below -0.65 for short signals with volume confirmation
• Use confidence bands to identify optimal entry zones - signals within confidence bands carry higher probability
• Background intensity reflects signal strength - darker backgrounds indicate stronger conviction
• Enter long positions when blue circles appear above oscillator with RSI < 75 and volume > 120% average
• Enter short positions when dark circles appear below oscillator with RSI > 25 and volume confirmation
• Information panel provides real-time confidence percentage and momentum direction for position sizing decisions
• Individual feature plots allow granular analysis of specific pattern components for strategy refinement
💡Conclusion
CNN Statistical Trading System represents the evolution of technical analysis, combining institutional-grade pattern recognition with retail accessibility. The six-kernel architecture provides comprehensive market pattern coverage while adaptive weighting ensures relevance across all market conditions. Whether you’re seeking systematic entry signals or advanced pattern confirmation, this indicator delivers mathematically rigorous analysis with intuitive visual presentation. Indicator

Indicator

Simple Neural Network Transformed RSI [QuantraSystems]Simple Neural Network Transformed RSI
Introduction
The Simple Neural Network Transformed RSI (ɴɴᴛ ʀsɪ) stands out as a formidable tool for traders who specialize in lower timeframe trading.
It is an innovative enhancement of the traditional RSI readings with simple neural network smoothing techniques.
This unique blend results in fairly accurate signals, tailored for swift market movements. The ɴɴᴛ ʀsɪ is particularly resistant to the usual market noise found in lower timeframes, ensuring a clearer view of short-term trends.
Furthermore, its diverse range of visualization options adds versatility, making it a valuable tool for traders seeking to capitalize on short-duration market dynamics.
Legend
In the Image you can see the BTCUSD 1D Chart with the ɴɴᴛ ʀsɪ in Trend Following Mode to display the current trend. This is visualized with the barcoloring.
Its Overbought and Oversold zones start at 50% and end at 100% of the selected Standard Deviation (default σ = 2), which can indicate extremely rare situations which can lead to either a softening momentum in the trend or even a mean reversion situation.
Here you can also see the original Indicator line and the Heikin Ashi transformed Indicator bars - more on that now.
Notes
Quantra Standard Value Contents:
To draw out all the information from the indicator calculation we have added a Heikin-Ashi (HA) Candle Visualization.
This HA transformation smoothens out the indicator values and gives a more informative look into Momentum and Trend of the Indicator itself.
This allows early entries and exits by observing the HA transformed Indicator values.
To diversify, different visualization options are available, either a classic line, HA transformed or Hybrid, which contains both of the previous.
To make Quantra's Indicators as useful and versatile as possible we have created options
to change the barcoloring and thus the derived signal from the indicator based on different modes.
Option to choose different Modes:
Trend Following (Indicator above mid line counts as uptrend, below is downtrend)
Extremities (Everything going beyond the Deviation Bands in a Mean Reversion manner is highlighted)
Candles (Color of HA candles as barcolor)
Reversion (HA ONLY) (Reversion Signals via the triangles if HA candles change state outside of the Deviation Bands)
- Reversion Signals are indicated by the triangles in the Heikin-Ashi or Hybrid visualization when the HA Candles revert
from downwards to upwards or the other way around OUTSIDE of the SD Bands.
Depending on the Indicator they signal OB/OS areas and can either work as high probability entries and exits for Mean Reversion trades or
indicate Momentum slow downs and potential ranges.
Please use another indicator to confirm this.
Case Study
To effectively utilize the NNT-RSI, traders should know their style and familiarize themselves with the available options.
As stated above, you have multiple modes available that you can combine as you need and see fit.
In the given example mostly only the mode was used in an isolated fashion.
Trend Following:
Purely relied on State Change - Midline crossover
Could be combined with Momentum or Reversion analysis for better entries/exits.
Extremities:
Ideal entry/exit is in the accordingly colored OS/OB Area, the Reversion signaled the latest possible entry/exit.
HA Candles:
Specifically applicable for strong trends. Powerful and fast tool.
Can whip if used as sole condition.
Reversions:
Shows the single entry and exit bars which have a positive expected value outcome.
Can also be used as confirmation or as last signal.
Please note that we always advise to find more confluence by additional indicators.
Traders are encouraged to test and determine the most suitable settings for their specific trading strategies and timeframes.
In the showcased trades the default settings were used.
Methodology
The Simple Neural Network Transformed RSI uses a simple neural network logic to process RSI values, smoothing them for more accurate trend analysis.
This is achieved through a linear combination of RSI values over a specified input length, weighted evenly to produce a neural network output.
// Simple neural network logic (linear combination with weighted aggregation)
var float inputs = array.new_float(nnLength, na)
for i = 0 to nnLength - 1
array.set(inputs, i, rsi1 )
nnOutput = 0.0
for i = 0 to nnLength - 1
nnOutput := nnOutput + array.get(inputs, i) * (1 / nnLength)
nnOutput
This output is then compared against a standard or dynamic mean line to generate trend following signals.
Mean = ta.sma(nnOutput, sdLook)
cross = useMean? 50 : Mean
The indicator also incorporates Heikin Ashi candlestick calculations to provide additional insights into market dynamics, such as trend strength and potential reversals.
// Calculate Heikin Ashi representation
ha = ha(
na(nnOutput ) ? nnOutput : nnOutput ,
math.max(nnOutput, nnOutput ),
math.min(nnOutput, nnOutput ),
nnOutput)
Standard deviation bands are used to create dynamic overbought and oversold zones, further enhancing the tool's analytical capabilities.
// Calculate Dynamic OB/OS Zones
stdv_bands(_src, _length, _mult) =>
float basis = ta.sma(_src, _length)
float dev = _mult * ta.stdev(_src, _length)
= stdv_bands(nnOutput, sdLook,sdMult/2)
= stdv_bands(nnOutput, sdLook, sdMult)
The Standard Deviation bands take defined parameters from the user, in this case sigma of ideally between 2 to 3,
to help the indicator detect extremely improbable conditions and thus take an inversely probable signal from it to forward to the user.
The parameter settings and also the visualizations allow for ample customizations by the trader.
For questions or recommendations, please feel free to seek contact in the comments.
Indicator

Esqvair's Neural Reversal Probability IndicatorIntroduction
Esqvair's Neural Reversal Probability Indicator is the indicator that shows probability of reversal.
Warning: This script should only be used on 1 minute chart.
How to use
When a signal appears (by default it is a green bar), a reversal should be expected.
The signal appears when the indicator value >= Threshold.
If you want more signals, you must lower the threshold, if less, you must increase the threshold.
For some assets, like Forex pairs, you have to optimize the threshold yourself, but for most stocks, the default threshold works well.
How well a threshold fits an asset depends on the volatility of the asset.
For most assets, the indicator ranges from 35 to 75.
Settings
Smoothing - The default is 1, which means no smoothing. Indicator smoothing by SMA.
Threshold - default 71.0 is responsible for the occurrence of signals, read "How to use" part to learn more
The Indicator
This indicator is a pre-trained neural network that was trained outside of PulseWire and then its structure and weights values were converted to PineScript.
Warning: A neural network is a black box in the sense that although it can approximate any function, studying its structure will not give you any idea about the structure of the function being approximated.
Possible questions
Why does the indicator value most time range from 35 to 75 when the probability should ranges from 0 to 100?
-Due to some randomness in the markets, a neural network can never be 100% sure.
What data was used to train the neural network?
-This was BTCUSD 1 minute chart data from 02/05/2020 to 02/05/2022.
Where did you train the neural network and convert it to PineScript?
-I used a programming language that I know.
Indicator

Library

FunctionNNLayerLibrary "FunctionNNLayer"
Generalized Neural Network Layer method.
function(inputs, weights, n_nodes, activation_function, bias, alpha, scale) Generalized Layer.
Parameters:
inputs : float array, input values.
weights : float array, weight values.
n_nodes : int, number of nodes in layer.
activation_function : string, default='sigmoid', name of the activation function used.
bias : float, default=1.0, bias to pass into activation function.
alpha : float, default=na, if required to pass into activation function.
scale : float, default=na, if required to pass into activation function.
Returns: float Library

FunctionNNPerceptronLibrary "FunctionNNPerceptron"
Perceptron Function for Neural networks.
function(inputs, weights, bias, activation_function, alpha, scale) generalized perceptron node for Neural Networks.
Parameters:
inputs : float array, the inputs of the perceptron.
weights : float array, the weights for inputs.
bias : float, default=1.0, the default bias of the perceptron.
activation_function : string, default='sigmoid', activation function applied to the output.
alpha : float, default=na, if required for activation.
scale : float, default=na, if required for activation.
@outputs float Library

MLActivationFunctionsLibrary "MLActivationFunctions"
Activation functions for Neural networks.
binary_step(value) Basic threshold output classifier to activate/deactivate neuron.
Parameters:
value : float, value to process.
Returns: float
linear(value) Input is the same as output.
Parameters:
value : float, value to process.
Returns: float
sigmoid(value) Sigmoid or logistic function.
Parameters:
value : float, value to process.
Returns: float
sigmoid_derivative(value) Derivative of sigmoid function.
Parameters:
value : float, value to process.
Returns: float
tanh(value) Hyperbolic tangent function.
Parameters:
value : float, value to process.
Returns: float
tanh_derivative(value) Hyperbolic tangent function derivative.
Parameters:
value : float, value to process.
Returns: float
relu(value) Rectified linear unit (RELU) function.
Parameters:
value : float, value to process.
Returns: float
relu_derivative(value) RELU function derivative.
Parameters:
value : float, value to process.
Returns: float
leaky_relu(value) Leaky RELU function.
Parameters:
value : float, value to process.
Returns: float
leaky_relu_derivative(value) Leaky RELU function derivative.
Parameters:
value : float, value to process.
Returns: float
relu6(value) RELU-6 function.
Parameters:
value : float, value to process.
Returns: float
softmax(value) Softmax function.
Parameters:
value : float array, values to process.
Returns: float
softplus(value) Softplus function.
Parameters:
value : float, value to process.
Returns: float
softsign(value) Softsign function.
Parameters:
value : float, value to process.
Returns: float
elu(value, alpha) Exponential Linear Unit (ELU) function.
Parameters:
value : float, value to process.
alpha : float, default=1.0, predefined constant, controls the value to which an ELU saturates for negative net inputs. .
Returns: float
selu(value, alpha, scale) Scaled Exponential Linear Unit (SELU) function.
Parameters:
value : float, value to process.
alpha : float, default=1.67326324, predefined constant, controls the value to which an SELU saturates for negative net inputs. .
scale : float, default=1.05070098, predefined constant.
Returns: float
exponential(value) Pointer to math.exp() function.
Parameters:
value : float, value to process.
Returns: float
function(name, value, alpha, scale) Activation function.
Parameters:
name : string, name of activation function.
value : float, value to process.
alpha : float, default=na, if required.
scale : float, default=na, if required.
Returns: float
derivative(name, value, alpha, scale) Derivative Activation function.
Parameters:
name : string, name of activation function.
value : float, value to process.
alpha : float, default=na, if required.
scale : float, default=na, if required.
Returns: float Library

Library
