MLP - BTC Breakout Probability [Deep Learning] [Open Source]I trained a single Multilayer Perceptron on 13 years of Bitcoin price history and open-sourced the result. Not because it's perfect, but because the idea is worth sharing.
The concept is simple.
Most breakout strategies are rule-based. Fixed levels, static conditions. This one is different, instead of predicting direction, the model learned the distribution of Bitcoin's daily price moves. You pick a threshold, it gives you the probability. Same model, any level.
How to use it
Pick a percentage threshold , by doing that you're asking the model to evaluate. When price breaks that level and the model is showing meaningful confidence, a label is shown on the chart.. Daily only. BTC only.
Under the hood
A lightweight Multilayer Perceptron (MLP) trained on ~4,700 daily candles of raw OHLC data from May 2009 to May 2022 . The architecture is two hidden layers (16→8), ReLU activations throughout, and a sigmoid output that squashes the result into a clean 0–1 probability score. ReLU keeps the internal representations sparse and non-linear, sigmoid makes the output as a probability.
What makes this interesting is that the model didn't just learn a raw number, it learned the underlying distribution of Bitcoin's daily price moves. That's what allows a single model to answer probability questions across different thresholds rather than being hardcoded to one fixed level.
The output isn't a prediction, it's a calibrated belief about where price is likely to go, derived from 13 years of market structure.
Honest limitations
Fat tails eat this model alive. The features are correlated and the model has no concept of liquidity. It underestimates the extremes.
Daily timeframe only. Bitcoin only. Long only.
This was built as a personal project, mostly for fun and to serve as a working example of how ML concepts can be applied to market data.
Disclaimer
This indicator is provided for educational and informational purposes only. It does not constitute financial advice, trading recommendations, or a guarantee of future results. Past performance does not predict future returns. You alone are responsible for your trading decisions. Always test thoroughly in a simulated environment before trading with real capital. 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

Deep Machine Learning - Artificial Neural Network -⭐ Full-Scale Deep Learning AI on PulseWire ⭐
🌟 Introduction: A Paradigm Shift in Technical Analysis
We are currently living in an unprecedented era of Artificial Intelligence. Large Language Models (LLMs) like Google's Gemini and OpenAI's GPT have fundamentally revolutionized how we process data, generate code, and understand complex non-linear relationships. Inspired by the tremendous analytical power of these modern AI models, this script bridges the gap between advanced data science and retail trading.
🟢 In Simple Terms (For Beginners)
Not a data scientist? Don't worry! Here is what this script does in plain English:
Imagine having a tireless assistant who has studied decades of chart patterns. Instead of you staring at 5 different indicators (like RSI, MACD, and Bollinger Bands) and trying to guess the trend, this AI looks at all of them simultaneously. It learns from its past mistakes, figures out what is actually working right now, and gives you a single, easy-to-read "Bullish" or "Bearish" line. You don't need a PhD in math to use it!
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🏫 Educational Deep Dive: Unveiling the "Black Box"
Before diving into the indicator settings, it is essential to understand how a Neural Network (NN) operates. Traditional indicators look at past math to plot a line; Neural Networks learn from past mistakes to forecast a probability.
🧠 The "Sports Team" Analogy (How it works simply)
Think of the Neural Network like a professional sports organization:
The Scouts (Input Layer): They gather raw data from the field (Momentum, Trend, Volume).
The Coaches (Hidden Layers): They sit in the locker room, debate the data, and figure out complex game strategies.
The Manager (Output Layer): Makes the final, definitive decision to "Buy" or "Sell" based on the coaches' advice.
Learning from Mistakes (Backpropagation): When the team loses a game (makes a bad prediction), they review the tape and adjust their strategy for the next game. This AI does exactly this on every single new candle!
🏗️ The Network Architecture (For Advanced Users)
A neural network is inspired by the biological human brain, organized into specific layers. Here is a simplified map of what is happening mathematically inside this script on every single bar:
→weighted sum & activation→
→weighted sum & activation→
💡 DEEP DIVE: Activation Functions (Mapping Non-Linearity)
If a Neural Network only used basic multiplication and addition, it would mathematically collapse into a single, rigid linear regression formula, completely failing to map the chaotic realities of financial markets.
Activation Functions introduce non-linearity, allowing the model to warp its decision boundaries and solve complex, multi-dimensional problems.
📈 ReLU (Rectified Linear Unit): max(0, x) -> Mitigates the "vanishing gradient" problem. It aggressively turns off negative noise, creating sparse, highly efficient activations.
🌊 Tanh (Hyperbolic Tangent): Squashes values into an S-curve between -1 and 1. Being zero-centered, it generally yields faster convergence during gradient descent than Sigmoid.
📉 Sigmoid: Squashes values between 0 and 1. Used for probability estimation, though susceptible to gradient saturation on extreme inputs.
🧠 DEEP DIVE: Optimizers (Navigating the Loss Landscape)
When the AI makes a mistake, Backpropagation uses the Chain Rule of calculus to compute the "Gradient"—the vector pointing toward the steepest increase in error. The Optimizer dictates how to move in the opposite direction to minimize this error.
SGD (Stochastic Gradient Descent): Takes uniform steps down the gradient. Prone to getting stuck in local minima and ravines.
Momentum: Accumulates a moving average of past gradients to accelerate through flat regions and dampen oscillations.
RMSprop: Adapts the learning rate individually by dividing the gradient by a running average of its recent magnitude.
Adam (Adaptive Moment Estimation): The absolute state-of-the-art. It calculates both the 1st moment (mean, like Momentum) and 2nd moment (uncentered variance, like RMSprop) of the gradients. Crucially, it employs Bias Correction to prevent the moments from skewing towards zero early in training, allowing it to navigate the non-convex loss landscapes of financial markets with unmatched precision.
🛡️ DEEP DIVE: Regularization & MC Dropout (Bayesian Approximation)
Overfitting is the fatal flaw of poorly built AI—memorizing the past instead of learning the underlying structure.
L1 Regularization (Lasso): Acts as an algorithmic feature selector. It aggressively pushes the weights of useless, noisy indicators to exactly zero (Sparsity).
L2 Regularization (Ridge): Applies "Weight Decay" by penalizing large weights quadratically. It forces the network to distribute its reliance across all inputs rather than trusting a single dominant feature.
Monte Carlo (MC) Dropout: By randomly turning off nodes during live inference, we aren't just creating noise. Mathematically, this approximates a Gaussian Process, transforming the model into a Bayesian Neural Network. Instead of absolute point estimates, it provides a probabilistic distribution, allowing us to quantify the model's true epistemic uncertainty.
🌀 DEEP DIVE: Kalman Filter Dynamics (Signal vs. Noise)
Financial data is notoriously non-stationary. The script utilizes a 1D Kalman Filter—an algorithm originally designed for aerospace telemetry. It operates on a predict-update cycle. It mathematically balances Process Noise (Q) (the true underlying shift in market trend) and Measurement Noise (R) (the erratic, short-term price fluctuations). By continuously minimizing the error covariance, it extracts the pure signal from the raw Neural Network output without introducing the severe lag inherent in standard moving averages.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚙️ Groundbreaking Features
This indicator is packed with state-of-the-art machine learning techniques previously unseen in native Pine Script:
🎛️ Fully Customizable Architecture: You are the data scientist. Customize hidden layers, nodes per layer, Activation Functions, L1/L2 Regularization penalties, and select from advanced Optimizers to tailor the brain specifically for Crypto, Forex, or Stocks.
🔄 True Online Learning: A model trained on 2021 data will fail in 2024. This network solves that by sampling random historical bars and training itself using Gradient Descent on every single new bar. If the market regime shifts from a bull run to a chop zone, the model re-weights itself dynamically today.
⚖️ Layer Normalization: Financial data is wildly unstable. Layer Norm stabilizes the learning process by standardizing the inputs across the hidden layers, dramatically speeding up convergence and preventing the network from "exploding" mathematically.
🌊 Kalman Filter Smoothing: The raw neural network output is incredibly fast but can be noisy. The output is passed through a mathematically rigorous 1D Kalman Filter, which minimizes error covariance and produces a buttery-smooth, highly actionable Oracle line.
🖥️ Intelligent Dashboard UI: A sleek, dark-themed dashboard displays raw inputs, hidden layer activations (color-coded by activation strength), the final Oracle prediction, and the Uncertainty margin, directly on your chart.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🛠️ Comprehensive Configuration Guide
1️⃣ Engine Configuration (Tuning the Brain)
Optimizer: Leave this on Adam for the best general performance.
Learning Rate (LR): The "step size." If the line is too chaotic, lower the LR. If it adapts too slowly, raise it.
Hidden Layers & Nodes: More is not always better. Giving the network 5 layers and 15 nodes on a 1-minute timeframe will cause it to memorize noise. Start small (e.g., 2 layers, 8 nodes).
2️⃣ Target Configuration (What is the AI predicting?)
Candle: Predicts if the current candle is green or red. (Very noisy, best for scalping).
HTF Candle: Predicts the direction of a predefined Higher Timeframe candle.
Pivot State (Recommended): The AI learns the broader macro market structure by identifying historical Higher Highs (HH) and Lower Lows (LL). This filters out the noise and forces the AI to learn true trend waves.
3️⃣ Signals & Chart Overlays (Actionable Intelligence)
The script goes beyond just an oscillator by providing direct visual cues on your main price chart.
Threshold Crossing Alerts: You define an Alert Threshold (e.g., 0.5 or 1.0 Sigma). When the Oracle line crosses this threshold with conviction, the script triggers a Buy (▲) or Sell (▼) label and can fire native PulseWire alerts.
Smart Label Opacity (MA Alignment): To filter out weak or counter-trend signals, the script utilizes a dual-confirmation system with the Signal MA (nn_ma).
Bright Labels: If a signal triggers and aligns with the Signal MA (e.g., a Buy signal fires while the Oracle is also above its Moving Average), the label is plotted brightly, indicating high momentum and strong trend agreement.
Faint Labels: If a signal triggers but contradicts the Signal MA, the label is plotted faintly (transparently). This acts as a visual warning that the move lacks full momentum backing and might be a riskier, counter-trend setup.
4️⃣ Decoding the AI Dashboard (Visualizing the Brain)
The on-chart Intelligent Dashboard is not just for aesthetics; it literally visualizes the internal thought process of the neural network in real-time.
VECTOR & INPUT (The Senses): This column lists your chosen feature indicators and their current Z-Score normalized values. You can see exactly how strongly the market is pushing each individual metric.
L1, L2... (The Hidden Layers): These columns represent the actual artificial neurons in each hidden layer. The numbers displayed are the post-activation values.
Notice the Colors: The cells are color-coded dynamically based on activation strength. Bright blue/red cells mean those specific neurons are firing strongly, recognizing a pattern. Dark/transparent cells mean those neurons are currently inactive or squashed by the activation function. You are literally watching the AI "think."
ORACLE (The Final Output):
The Score: The aggregated final prediction value (typically clamped between -3.0 and +3.0).
The Phase: A clear text label indicating the current market regime (e.g., "STRONG BUY", "BULLISH", "BEARISH", "STRONG SELL").
Uncertainty (± Margin): The exact numerical value of the Confidence Interval calculated via MC Dropout. A low margin (e.g., ±0.15) means the AI is laser-focused and highly confident. A high margin (e.g., ±0.80) means the AI is mathematically uncertain due to conflicting data.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
💡 Advanced Pro-Tips for Real Trading
Reading the Oracle Line:
Values > 0 indicate a Bullish bias (Blue gradient).
Values < 0 indicate a Bearish bias (Red gradient).
Watch the color intensity: A solid, bright line means the AI has strong statistical conviction. Faded, transparent lines mean standard deviation is high and the signal is weak.
Using the CI Box (The Squeeze & Expand Tactic): Look at the transparent box projected into the future.
The Expand (Avoid): When the box is incredibly wide, the AI is telling you the market is chaotic and unpredictable. Protect your capital and stay out.
The Squeeze (Action): When the box gets extremely tight, the AI has high certainty. Look for entries in the direction of the Oracle line.
Wait for the Cross & Check the Smart Labels: Do not execute a trade the millisecond the line turns blue. Trade when it crosses the Alert Threshold. More importantly, look at the brightness of the chart label. Prioritize bright labels where the AI's conviction aligns perfectly with the underlying Signal MA, and be extremely cautious with faint labels.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠️ Disclaimer
This script is a complex statistical machine learning model designed for educational and deep analytical purposes. Neural Networks are highly dependent on user-defined hyperparameter settings and the specific features fed into them. A poorly tuned model will produce garbage output. Past performance and back-tested training do not guarantee future live market results. Do not use this tool as the sole basis for real-money trading decisions. Always employ strict risk management, position sizing, and use this in confluence with your own price action analysis.
If you appreciate the hundreds of hours of coding and advanced mathematics that went into making this first-of-its-kind Native Pine Script Neural Network a reality, please drop a Boost 🚀, add it to your favorites, and leave a comment below! Let's push the boundaries of what is possible on PulseWire. Indicator

NAND PerceptronExperimental NAND Perceptron based upon Python template that aims to predict NAND Gate Outputs. A Perceptron is one of the foundational building blocks of nearly all advanced Neural Network layers and models for Algo trading and Machine Learning.
The goal behind this script was threefold:
To prove and demonstrate that an ACTUAL working neural net can be implemented in Pine, even if incomplete.
To pave the way for other traders and coders to iterate on this script and push the boundaries of Tradingview strategies and indicators.
To see if a self-contained neural network component for parameter optimization within Pinescript was hypothetically possible.
NOTE: This is a highly experimental proof of concept - this is NOT a ready-made template to include or integrate into existing strategies and indicators, yet (emphasis YET - neural networks have a lot of potential utility and potential when utilized and implemented properly).
Hardcoded NAND Gate outputs with Bias column (X0):
// NAND Gate + X0 Bias and Y-true
// X0 // X1 // X2 // Y
// 1 // 0 // 0 // 1
// 1 // 0 // 1 // 1
// 1 // 1 // 0 // 1
// 1 // 1 // 1 // 0
Column X0 is bias feature/input
Column X1 and X2 are the NAND Gate
Column Y is the y-true values for the NAND gate
yhat is the prediction at that timestep
F0,F1,F2,F3 are the Dot products of the Weights (W0,W1,W2) and the input features (X0,X1,X2)
Learning rate and activation function threshold are enabled by default as input parameters
Uncomment sections for more training iterations/epochs:
Loop optimizations would be amazing to have for a selectable length for training iterations/epochs but I'm not sure if it's possible in Pine with how this script is structured.
Error metrics and loss have not been implemented due to difficulty with script length and iterations vs epochs - I haven't been able to configure the input parameters to successfully predict the right values for all four y-true values for the NAND gate (only been able to get 3/4; If you're able to get all four predictions to be correct, let me know, please).
// //---- REFERENCE for final output
// A3 := 1, y0 true
// B3 := 1, y1 true
// C3 := 1, y2 true
// D3 := 0, y3 true
PLEASE READ: Source article/template and main code reference:
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com Indicator

ANN MACD : 25 IN 1 SCRIPTIn this script, I tried to fit deep learning series to 1 command system up to the maximum point.
After selecting the ticker, select the instrument from the menu and the system will automatically turn on the appropriate ann system.
Listed instruments with alternative tickers and error rates:
WTI : West Texas Intermediate (WTICOUSD , USOIL , CL1! ) Average error : 0.007593
BRENT : Brent Crude Oil (BCOUSD , UKOIL , BB1! ) Average error : 0.006591
GOLD : XAUUSD , GOLD , GC1! Average error : 0.012767
SP500 : S&P 500 Index (SPX500USD , SP1!) Average error : 0.011650
EURUSD : Eurodollar (EURUSD , 6E1! , FCEU1!) Average error : 0.005500
ETHUSD : Ethereum (ETHUSD , ETHUSDT ) Average error : 0.009378
BTCUSD : Bitcoin (BTCUSD , BTCUSDT , XBTUSD , BTC1!) Average error : 0.01050
GBPUSD : British Pound (GBPUSD,6B1! , GBP1!) Average error : 0.009999
USDJPY : US Dollar / Japanese Yen (USDJPY , FCUY1!) Average error : 0.009198
USDCHF : US Dollar / Swiss Franc (USDCHF , FCUF1! ) Average error : 0.009999
USDCAD : Us Dollar / Canadian Dollar (USDCAD) Average error : 0.012162
SOYBNUSD : Soybean (SOYBNUSD , ZS1!) Average error : 0.010000
CORNUSD : Corn (ZC1! ) Average error : 0.007574
NATGASUSD : Natural Gas (NATGASUSD , NG1!) Average error : 0.010000
SUGARUSD : Sugar (SUGARUSD , SB1! ) Average error : 0.011081
WHEATUSD : Wheat (WHEATUSD , ZW1!) Average error : 0.009980
XPTUSD : Platinum (XPTUSD , PL1! ) Average error : 0.009964
XU030 : Borsa Istanbul 30 Futures ( XU030 , XU030D1! ) Average error : 0.010727
VIX : S & P 500 Volatility Index (VX1! , VIX ) Average error : 0.009999
YM : E - Mini Dow Futures (YM1! ) Average error : 0.010819
ES : S&P 500 E-Mini Futures (ES1! ) Average error : 0.010709
GAZP : Gazprom Futures (GAZP , GZ1! ) Average error : 0.008442
SSE : Shangai Stock Exchange Composite (Index ) ( 000001 ) Average error : 0.011287
XRPUSD : Ripple (XRPUSD , XRPUSDT ) Average error : 0.009803
Note 1 : Australian Dollar (AUDUSD , AUD1! , FCAU1! ) : Instrument has been removed because it has an average error rate of over 0.13.
The average error rate is 0.1850.
I didn't delete it from the menu just because there was so much request,
You can use.
Note 2 : Friends have too many requests, it took me a week in total and 1 other script that I'll share in 2 days.
Reaching these error rates is a very difficult task, and when I keep at a low learning rate, they are trained for a very long time.
If I don't see the error rate at an average low, I increase the layers and go back into a longer process.
It takes me 45 minutes per instrument to command artificial neural networks, so I'll release one more open source, and then we'll be laying 70-80 percent of the world trade volume with artificial neural networks.
Note 3 :
I would like to thank wroclai for helping me with this script.
This script is subject to MIT License on behalf of both of us.
You can review my original idea scripts from my Github page.
You can use it free but if you are going to modify it, just quote this script .
I hope it will help everyone, after 1-2 days I will share another ann script that I think is of the same importance as this, stay tuned.
Regards , Noldo .
Indicator

Indicator

ANN MACD BTC v2.0 This script is the 2nd version of the BTC Deep Learning (ANN) system.
Created with the following indicators and tools:
RSI
MACD
MOM
Bollinger Bands
Guppy Exponential Moving Averages:
(3,5,8,10,12,15,30,35,40,45,50,60)
Note: I was inspired by the CM Guppy Ema script.
Thank you very much to dear wroclai for his great help.
He has been a big help in the deep learning series.
That's why the licenses in this series are for both of us.
I'm sharing these series and thats the first. Stay tuned and regards!
Note : Alerts added. Indicator

Indicator

Indicator

ANN MACD Future Forecast (SPY 1D) NOTE : Deep learning was conducted in a narrow sample set for testing purposes. So this script is Experimental .
This system is based on the following article and is inspired by an external program:
hackernoon.com
None of the artificial neural networks in Tradingview work and are not based on completely correct logic. Unlike others in this system:
IMPORTANT NOTE: If the tangent activation function is used, the input data must also have tangent values (compared to the previous values of 1 bar).
Inputs were prepared according to this judgment.
1. The tangent function which is the activation function is written correctly. (The tangent function in the article: ActivationFunctionTanh (v) => (1 - exp (-2 * v)) / (1 + exp (-2 * v)))
2. Missing bias parts in the formulas were added.
3. The output function is taken from the next day (historical), so that the next bar can be predicted, which is the truth.
4.The forecast value of the next bar is subtracted from the current bar change and the market direction is determined.
5.When the future forecast and the current close are added together, the resulting data is called seed.
The seed carries data both from the present and from yesterday and from the future.
6.And this seed was subjected to the MACD method.
Thus, due to exponential averages, more importance will be given to recent developments and
The acceleration situations will show us the direction.
However, a short position should be taken for crossover and a long position for crossunder .
Because the predicted values work in reverse.Even though we use the same period (9,12,26) it is much faster!
7. There is no future code that can cause Repaint.
However, the color after closing should be checked.
The system is completely correct.
However, a very narrow sample was selected.
100 data: Tangent diffs ; volume change, bollinger bands values changes (Upband , Midband , Lowband) and LazyBear's Squeeze Momentum Indicator (SQZMOM_LB) change and the next bar data (historical) price change were put into the deep learning test.
IMPORTANT NOTE : The larger the sample set and the more effective dependent variables, the higher the hit rate of the deep learning test!
EDIT : This code is open source under the MIT License. If you have any improvements or corrections to suggest, please send me a pull request via the github repository github.com
Stay tuned. Best regards!
Indicator
