FP - SMA Crossover + Regime + Hold FilterThis indicator is the visual implementation of Strategy 270, one of the top-performing systems from my quantitative backtesting pipeline (XAUUSD H1, walk-forward OOS validation).
What it does
It identifies high-probability long entries using a three-layer confirmation system, and manages exits with a dual grace period that prevents premature closes during pullbacks within a healthy trend.
Entry conditions (all must be true):
SMA Fast (15) crosses above SMA Slow (200) — trend shift confirmed
Price is above the Regime SMA (200) — macro structure is bullish
Price is at least 0.61% above EMA200 — minimum distance from the mean, filters low-conviction setups near the line
Exit logic — two layers:
Layer 1: SMA15 crosses below SMA200, OR price has been below the Regime SMA for N consecutive bars (grace_bars = 8)
Layer 2: If the exit trigger is caused by being below the regime (not a clean crossunder), the system waits for a second confirmation window (grace_bars_2 = 12) before closing. This eliminates false exits on brief pullbacks.
Minimum hold filter:
No exit is allowed during the first 96 bars after entry (4 days on H1). This comes directly from trade analysis: in backtesting, trades closed before 96 bars had a win rate near 0% and destroyed net P&L. Trades held between 8 and 20 days showed 73% win rate. The yellow dot marks the moment the hold lock is released — from that bar onward, exits are active.
Visual elements:
🟢 Green triangle below bar — long entry signal
🔴 Red triangle above bar — exit signal
🟡 Yellow dot — hold period unlocked (exits now active)
Green background — position is open
Lines: SMA15 (orange), SMA200 (blue), EMA200 (purple dashed), Regime SMA (gray)
Three built-in alerts: entry, exit, and hold unlock.
Recommended timeframe: H1. All parameters are adjustable from the inputs panel — the defaults match the optimized backtest configuration.
This indicator does not repaint. Entry and exit signals are generated on bar close. Indicator

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

Indicator

Indices Delta DashboardThe indicator calculates "Delta" as the difference between buying and selling volume (approximated by comparing the Close to the Open). It provides two key metrics for each ticker in a clean table format:
Bar Delta: The net buy/sell volume for the most recent completed bar.
Session Delta: The cumulative net buy/sell volume since the start of the current trading day.
Key Features:
Multi-Ticker Support: Monitors NQ (Nasdaq 100), ES (S&P 500), YM (Dow Jones), and RTY (Russell 2000) simultaneously.
Session Tracking: Automatically resets the "Session Delta" at the start of each new trading day.
Customization: You can adjust the tickers, table position, and colors in the script settings.
Visual Clarity: Bullish values are highlighted in green, and bearish values in red for quick interpretation..
What has changed:
Generic Symbols: I've changed the default symbols to NQ1!, ES1!, YM1!, and RTY1!. PulseWire will now automatically look for the primary continuous futures contract available for these tickers.
Error Handling: I added the ignore_invalid_symbol = true parameter to the data requests. This prevents the script from stopping if one of the symbols isn't found.
Manual Selection: If a symbol still shows as "Invalid" in the table, you can now easily change it:
Open the indicator Settings (gear icon).
Click on the Ticker input field.
Use the search box to find and select the exact version of the symbol you use (e.g., if you use Micro Futures, search for MNQ1!).
What's New:
Text Size Control: I added a "Text Size" input in the settings (Style group). You can now choose between Tiny, Small, Normal, and Large to adjust the overall size of the table.
Extended Positions: The "Table Position" setting now explicitly includes all four corners: Top Right, Top Left, Bottom Right, and Bottom Left.
Cleaner Ticker Display: I implemented a cleaning function that:
Removes the exchange prefix (e.g., CME:NQ1! becomes NQ1!).
Specifically removes keywords like MINI or MICRO from the displayed text to keep the table compact.
The table will now look much cleaner and can be positioned anywhere on your chart to avoid overlapping with price action or other indicators.
Key Additions:
Table Timeframe: You can now set a specific timeframe for the table (e.g., 5m) independently of your chart timeframe (e.g., 1m). The "Bar Delta" will reflect the volume of the most recent 5-minute bar, and the "Session Delta" will accumulate those 5-minute bars.
Session Type (Globex):
Daily (All): Accumulates delta for the entire trading day (resetting at the daily open).
Globex (18:00-09:30 EST): Accumulates delta specifically during the overnight session from 6:00 PM to 9:30 AM EST.
The script uses the America/New_York timezone to ensure it handles Daylight Savings Time changes automatically.
Dynamic Headers: The table header now displays the current calculation timeframe in parentheses (e.g., "Ticker (5)") so you always know what data you're looking at.
How to use:
Open the indicator Settings.
Go to the Timeframe & Session group.
Adjust the Table Timeframe to your preference.
Switch Session Type to "Globex" to see only the overnight delta.
CREATED BY luxAlgo Quant
Indicator

BoaBias: Anchored Swing VWAP (MTF) - Touch, Alerts, Stats█ WHAT IT DOES
Chart timeframe: Multiple anchored VWAP curves from swing pivots—not session VWAP. Resistance-anchored paths (swing highs) and support-anchored paths (swing lows) draw as polylines and clear after confirmation (same rules as the inputs: one qualifying close or N bars in a row ). Optional touch markers when the bar range spans VWAP (green below / red above).
Higher timeframes: Optional HTF 1–3 reuse the same pivot + anchored-VWAP logic inside request.security with barmerge.gaps_off and barmerge.lookahead_off . Display as a ribbon (midline ± % of price) or stepped lines . Up to five concurrent VWAP slots per HTF (plot budget).
Alerts: Separate alert() channels—chart VWAP touches and optional HTF 1–3 midline touches when the chart bar’s range crosses the HTF VWAP. Prefixes: Chart VWAP touch / HTF VWAP touch with ticker, price, time, and touched lines on HTF. Create Alert → this script → Any alert() function call . Alert frequency input applies to every alert() from this script (once per bar / once per bar close / all ticks).
Reaction statistics (optional table): A compact on-chart table aggregates how closed swing-anchored lines behaved on the chart timeframe only —not HTF curves. Toggle in inputs; Show stats table is on in factory defaults for this build (disable to reduce on-chart load). Cohort splits include touched vs no-touch, K/M-style breakout vs bounce windows after first touch, ATR pierce vs hold, and simple marginal “first event” proxies (swing-side pivot, opposite-side VWAP range touch, close beyond last swing). Numbers are descriptive context, not trade signals or guaranteed forward behaviour. When the table is enabled, lifecycle logic shares a small Pine library module ( BoaBiasVwapSwingRxStats ) so stats stay aligned with line confirmation.
█ REACTION STATS TABLE — WHAT EACH ROW MEANS
Percent row labels use short tags: b = “ b ” bucket, br = “ br ” (break) bucket in the K/M and ATR rules defined in code (not a broker term). Counts and % are descriptive on history —not forecasts.
Row 0 (headers) — TF / Support / Resistance / All : TF shows the chart’s period. Columns 1–2 are support- and resistance-anchored closed lines. All = mixed view for FE totals and the combined line count.
Line 1 — n= and X lines : Support / Resistance show how many touched lines of that type finished (had at least one bar with range spanning VWAP before the line was confirmed and removed). The All cell shows the total completed lines: support + resistance anchors that were cleared by confirmation, including no-touch cases.
No-touch row: For lines that never had low ≤ VWAP ≤ high before the line was confirmed, split by S/R. Percent (where shown) = no-touch count ÷ all completed lines of that side (touched + no-touch).
K/M b% and K/M br% : Denominator = touched S/R lines only. After the first touch , the script tracks consecutive closes on the break side of VWAP (K bars) in a post-touch window, and a flag if that ever reaches K (see inputs). A line is bucketed as K/M br (break) if, at the confirmation bar, either: (1) the bar is still within M bars after the first touch, or (2) the K-hold was reached in the tracked window. Otherwise, among touched lines, it counts in K/M b ( b = non-`br` in this K/M sense). The All cell on the K/M rows shows the active K / M from inputs.
ATR b% and ATR br% : Denominator = touched S/R. Uses ATR = R ×ATR from VWAP (R and ATR length from inputs). A line is ATR br if, with touch, the confirmation bar is still within M_atr bars after the first touch or a pierce of that ATR band occurred in the tracked window. Otherwise the touched line is counted in ATR b . The All cell shows ATR length / R / M_atr used for the rule.
FE (marginal) rows — P(≥1) , P(swing) , P(opp) , P(cls) , P(none) : Only for touched lines: before confirmation, the script can record the first bar of three optional “events” if they occur. P(≥1): % where at least one event occurred. P(swing): a pivot of the favourable side (for a resistance-anchored line, a swing low bar is relevant; for support, a swing high ) is present in the path and used for the timing flag. P(opp): the range first crosses another active line of the opposite type (its VWAP in range). P(cls): close beyond the last recorded swing high (for support) or low (for resistance) before confirm. P(none): % where none of the three event types fired before the line closed. The All column pools S+R for the FE P(*) All percentages.
Avg life row: Average number of chart bars from the anchor to confirmation, over all completed lines. One merged cell in the table shows the value.
█ HOW IT WORKS
Pivots: ta.pivothigh / ta.pivotlow with configurable left/right length. Each anchor seeds cumulative typical-price × volume from the anchor forward; VWAP = cumulative TPV / cumulative volume along that line’s active segment.
Touch: low ≤ VWAP ≤ high on an active curve.
Confirmation: Line removal when closes satisfy the far-side rule after the minimum post-anchor bars— One bar or N bars in a row , per inputs.
HTF packaging: Same mechanics on selected higher TFs; values are pulled without lookahead from the security call.
Stats path: When the stats table is on, the script runs the shared library helpers so counters and polylines use the same confirmation and touch definitions as the visual path; HTF series do not feed those counters.
█ WHY THESE PIECES TOGETHER
Swing-anchored VWAP gives a volume path from structure; MTF ribbons or lines place that structure on a second axis of time; touch markers and alerts flag range overlap without claiming execution edges; optional stats summarize historical line outcomes for research. The bundle is one overlay for context and notification—not a black-box signal service.
█ HOW TO USE
First use: If the indicator appears in the wrong scale (squashed or fullscreen), right-click the indicator → Pin to scale → Pin to right scale.
Tune pivot length and confirmation mode; enable or disable touch markers, HTF layers, and each alert channel.
Add alert → this script → Any alert() function call ; respect HTF toggles and that HTF alerts need the HTF layer shown and a higher TF than the chart.
Higher-timeframe VWAPs: Show HTF 1–3 on the same chart to reduce time and clicks switching TFs. The higher-TF midlines/ribbons add structural context (where swing-based volume paths sit) without leaving the current timeframe.
Reaction stats: The optional table is on by default; turn it off if the on-chart table or extra compute is not needed. It aggregates how past closed chart-TF lines behaved (cohort splits, not a live edge claim). That helps reason about relative bounce/break and related counts on history—useful for testing hypotheses and ideas (what-if inputs, not guaranteed forward odds).
As a set: HTF + chart VWAP + optional stats supports exploring a wide range of VWAP interaction ideas on the same price history. Position it as a research and strategy-development layer (iterate rules on the chart, risk management stays separate)—not a turnkey signal.
█ LIMITATIONS
Meaningful volume improves the curves. Five HTF VWAP slots max per HTF (plot cap). HTF alerts use the midline VWAP, not ribbon edges. Stats are chart-TF only and historical. Structural / educational tool— not financial advice and not a substitute for independent risk management. Indicator

BoaBiasVwapSwingRxStatsLibrary "BoaBiasVwapSwingRxStats"
reset_slot_rx(idx, slotTouched, firstTouchBar, cohortConsec, kMetInWindow, atrMetInWindow, feFirstSwingBar, feFirstOppBar, feFirstBeyondBar, noTouchSent, feUnset)
Parameters:
idx (int)
slotTouched (array)
firstTouchBar (array)
cohortConsec (array)
kMetInWindow (array)
atrMetInWindow (array)
feFirstSwingBar (array)
feFirstOppBar (array)
feFirstBeyondBar (array)
noTouchSent (int)
feUnset (int)
chart_cum_pass(anchorBars, cumTPVs, cumVols, tested, maxLines, bar_index, high, low, close, volume)
Parameters:
anchorBars (array)
cumTPVs (array)
cumVols (array)
tested (array)
maxLines (int)
bar_index (int)
high (float)
low (float)
close (float)
volume (float)
chart_build_snap(snapVwap, anchorBars, cumTPVs, cumVols, tested, maxLines, bar_index)
Parameters:
snapVwap (array)
anchorBars (array)
cumTPVs (array)
cumVols (array)
tested (array)
maxLines (int)
bar_index (int)
chart_slot_rx_close(i, snapVwap, anchorBars, fromHigh, tested, consecBars, slotTouched, firstTouchBar, cohortConsec, kMetInWindow, atrMetInWindow, feFirstSwingBar, feFirstOppBar, feFirstBeyondBar, rxCounts, sumLifeHolder, bar_index, high, low, close, swingHighPx, swingLowPx, lastSwingHighPx, lastSwingLowPx, pivotLen, confirmMode, confirmBars, kHoldBars, mBarsAfterTouch, atrVal, atrRMult, mAtrWindow, noTouchSent, feUnset, maxLines)
Parameters:
i (int)
snapVwap (array)
anchorBars (array)
fromHigh (array)
tested (array)
consecBars (array)
slotTouched (array)
firstTouchBar (array)
cohortConsec (array)
kMetInWindow (array)
atrMetInWindow (array)
feFirstSwingBar (array)
feFirstOppBar (array)
feFirstBeyondBar (array)
rxCounts (array)
sumLifeHolder (array)
bar_index (int)
high (float)
low (float)
close (float)
swingHighPx (float)
swingLowPx (float)
lastSwingHighPx (float)
lastSwingLowPx (float)
pivotLen (int)
confirmMode (string)
confirmBars (int)
kHoldBars (int)
mBarsAfterTouch (int)
atrVal (float)
atrRMult (float)
mAtrWindow (int)
noTouchSent (int)
feUnset (int)
maxLines (int) Library

Indicator

Reaction Follow-Through Planner [AGPro Series]Reaction Follow-Through Planner
🧠 Core Idea
Did the first reaction actually create follow-through, or did price only bounce and fade?
📌 Overview / What it does
Reaction Follow-Through Planner is a decision-oriented overlay that evaluates what happens after price produces an initial reaction around a confirmed swing reference.
Instead of only marking the reaction itself, the script opens a structured follow-through window, measures progress, tracks defense of the reaction zone, defines invalidation, estimates target room, and converts the context into a 0-100 planner score.
It produces reaction zones, follow-through tracks, continuation markers, failed-reaction labels, risk/target guide lines, and a compact AGPro panel. It does not predict future price, place trades, automate execution, or claim that any reaction must continue.
🎯 Purpose & Design Philosophy
This script was built for traders who already understand that a reaction candle is not enough.
Many charts show a wick, bounce, rejection, hold, or local response, but the real question comes after that first response: did the market follow through with clean progress, participation, and defended invalidation?
The design philosophy is simple: treat reaction analysis as a planning workflow. The script helps organize the reaction into strength, follow-through, invalidation, room, and next action.
⚡ Why This Script Is Different
Most reaction tools focus on finding the reaction candle, drawing the level, or scoring the first response.
This script does NOT clone a rejection-block detector, a support/resistance reaction map, or a generic pivot reaction score.
Instead, it starts after the first reaction appears. It tracks whether that reaction can defend its zone, produce directional progress, maintain follow-through, and offer enough room before the context becomes stale or failed.
⚙️ Methodology
1. Context Detection
The engine tracks confirmed swing reaction references and waits for price to interact with them.
2. Reference Mapping
When the first response is accepted, the script builds a reaction zone from the first response candle and defines an invalidation edge beyond the defended area.
3. Reaction Evaluation
The script grades the initial reaction candle using close defense, wick defense, body participation, and direction agreement.
4. Follow-Through Tracking
During the tracking window, the model measures best directional progress, next-bar response, volume support, adverse excursion, time decay, and whether the invalidation edge remains defended.
5. Visual Output
The chart displays reaction zones, follow-through tracks, target room, invalidation guides, continuation markers, failed-reaction labels, and a clean AGPro planner panel.
🗺️ How to Read the Chart
Zones = the defended first-reaction area that should remain intact for the follow-through case to stay valid.
Follow-through track = the movement path from the reaction close toward the current follow-through position.
Invalidation guide = the price edge where the reaction context is considered failed by the script logic.
Target room guide = the nearby structure or ATR-based room estimate used to judge whether the reaction still has space.
Labels = optional reaction start markers, follow-through continuation, or failed-reaction context. Start labels and failed-reaction X markers are disabled by default, while failed-reaction labels use a separate low cap for a cleaner publication view.
Colors = teal for bullish reaction continuation, pink for bearish reaction continuation, gold for weak or stalled contexts, and indigo for higher-quality follow-through.
Panel = the current reaction strength, follow-through state, invalidation level, room estimate, and next action.
🚦 Signals & States
• Bull Reaction Watch → a bullish reaction window is active, but follow-through still needs progress.
• Bear Reaction Watch → a bearish reaction window is active, but follow-through still needs progress.
• Bull Follow-Through → bullish follow-through reached the planner threshold.
• Bear Follow-Through → bearish follow-through reached the planner threshold.
• No Follow-Through → the reaction stayed defended but did not generate enough progress inside the tracking window.
• Failed Reaction → price closed beyond the reaction invalidation edge.
🔔 Alerts Logic
Alerts are attention markers, not trade instructions.
New Bull Reaction Window triggers when a bullish first-response window opens.
New Bear Reaction Window triggers when a bearish first-response window opens.
Bull Follow-Through Ready triggers when bullish follow-through reaches the score and progress thresholds.
Bear Follow-Through Ready triggers when bearish follow-through reaches the score and progress thresholds.
Reaction Failed triggers when price closes beyond the active invalidation edge.
🧩 Confluence Logic
The strongest context appears when reaction strength, next-bar progress, volume response, wick defense, and room all align.
When the reaction candle is strong but follow-through is weak, the panel will usually remain in watch or no-follow-through mode.
When follow-through progresses but invalidation is too close or room is limited, interpretation should stay cautious.
📊 When to Use
• After a visible reaction from a swing high or swing low reference.
• During retest, hold, rejection, or continuation planning.
• When you want to separate first-response reactions from reactions that actually continue.
• On symbols and timeframes with enough liquidity for clean candle structure.
⚠️ When NOT to Use
• Extremely low-liquidity markets where reaction candles are unreliable.
• Very noisy micro timeframes with erratic wicks.
• News-driven volatility where invalidation and room can shift quickly.
• Situations where the user expects automatic entries or guaranteed outcomes.
🎛️ Key Inputs
• Swing Reaction Lookback → controls how selective the reaction references are.
• First Response Mode → controls how strict the first reaction filter is.
• Follow-Through Track Bars → controls how long the script evaluates continuation after the reaction.
• Minimum Planner Score → sets the threshold for continuation-ready context.
• Invalidation Buffer → controls how far beyond the reaction zone the invalidation edge sits.
• Fallback Target Room → estimates room when no clean opposite structure is nearby.
• Visual settings → control zones, optional start labels, outcome labels, failed-reaction label cap, optional failed markers, guides, density, and panel layout.
🖥️ Interface & Visual Design
The interface is built around a clean AGPro panel and chart-first visuals.
The panel gives the decision summary. The chart shows the defended reaction zone, follow-through track, invalidation edge, target room, and state labels.
The visual hierarchy is intentionally restrained: enough labels to make the chart alive, but not so many that the reaction workflow becomes noisy.
🧪 Practical Usage Workflow
1. Read the panel to see whether a reaction window is active.
2. Check the reaction zone and invalidation edge.
3. Watch whether the follow-through track expands away from the zone.
4. Compare the score with available target room.
5. Treat alerts as review prompts, not execution commands.
🔍 Interpretation Guidelines
A strong reaction is not automatically a strong follow-through.
A clean follow-through usually needs directional progress, defended invalidation, supportive participation, and enough remaining room.
If the panel says No Follow-Through, the reaction may still be interesting visually, but the script did not detect enough post-reaction continuation quality.
If the panel says Failed Reaction, the original reaction context is no longer valid according to the script rules.
🚫 What This Script Is NOT
• Not a prediction engine.
• Not financial advice.
• Not auto trading.
• Not guaranteed signals.
• Not a replacement for risk management.
• Not a generic support/resistance map.
• Not a rejection-block scanner.
⚠️ Limitations & Transparency
The script is rule-based and depends on confirmed swing references, ATR normalization, volume baselines, and selected sensitivity settings.
Different timeframes can produce different reaction windows.
High volatility can expand invalidation distance and reduce room quality.
Low-liquidity markets can create misleading wick behavior.
🧠 Market Context Notes
Reaction follow-through is strongest when the first response is supported by participation and clean progress away from the defended zone.
It is weaker when price reacts but stalls near the zone, repeatedly revisits invalidation, or lacks target room.
The script is designed to help traders think in terms of reaction quality, not certainty.
🧾 Use Case Examples
When price reacts from a swing low and the next bars defend the reaction zone with rising progress, the planner may shift from Bull Reaction Watch to Bull Follow-Through.
When price rejects a swing high but immediately reclaims the invalidation edge, the planner may mark Failed Reaction.
When price bounces but fails to expand before the tracking window expires, the panel may show No Follow-Through.
🧱 System Philosophy
The AGPro approach favors decision engines over simple signal indicators.
This script follows that philosophy by turning a reaction into a structured review process: strength, follow-through, invalidation, room, and action.
🔐 Non-Promise Statement
No score guarantees continuation.
No alert confirms a profitable outcome.
No visual state should be treated as certainty.
📉 Risk Disclosure
Trading involves risk.
Users are responsible for their own decisions, risk management, position sizing, and market interpretation.
This script is for educational and analytical purposes only and does not provide financial advice.
📚 Educational Note
Use this script to study how reactions behave after the first response.
The goal is to improve interpretation discipline, not to replace a complete trading plan.
Indicator

Indicator

Gap Continuation Planner [AGPro Series]TITLE
Gap Continuation Planner
🧠 Core Idea
Is the active gap being accepted for continuation, or is it losing the structure needed for a clean plan?
📌 Overview / What it does
Gap Continuation Planner is a chart-first gap planning tool built to evaluate what happens after a gap appears. Instead of treating every gap as an automatic fill candidate, it asks whether price is accepting the gap edge, following through away from the gap, and preserving a measurable defense line.
The script produces a gap defense zone, a continuation corridor, an acceptance edge, a defense line, a target guide, compact labels, alerts, and a clean AGPro decision panel. The panel converts the live context into a 0-100 continuation score, fill-risk reading, and next-action state.
It does not predict future price, automate trades, or tell the user to buy or sell. It organizes observable gap behavior into a more disciplined continuation-planning framework.
🎯 Purpose & Design Philosophy
This script was built for traders who do not want to reduce every gap to a simple fill-or-fade idea.
Many gaps initially look strong, but the important question is whether the market continues to accept the gap after the first reaction. Gap Continuation Planner focuses on that middle layer: gap acceptance, follow-through, volatility load, defense quality, fill pressure, and forward room.
The design supports a planner mindset. The goal is to slow the decision process down and review whether the structure is valid enough to deserve attention.
⚡ Why This Script Is Different
Most gap tools focus on gap detection, gap fill percentage, or historical gap zones.
This script does NOT work as a generic gap-fill reaction tool, support/resistance map, imbalance catalog, or automatic signal generator.
Instead, it treats the latest gap as a continuation planning object. The model studies whether price is accepting the continuation side of the gap, whether follow-through is developing, whether the defense line remains intact, whether fill risk is rising, and whether there is enough forward room for the plan to remain clean.
⚙️ Methodology
1. Context Detection
The script detects classic opening gaps, wick gaps, body-separation gaps, and controlled continuation launch windows when adaptive mode is enabled.
2. Reference Mapping
Each accepted gap creates a gap defense zone, an acceptance edge, a defense line, and a target guide.
3. Reaction Evaluation
The engine scores gap size, open acceptance, follow-through, volatility load, fill risk, and forward room.
4. Visual Output
The chart displays a centered gap-zone label, a centered continuation-corridor label, event labels, planner lines, and a compact AGPro panel.
🗺️ How to Read the Chart
Zones = the detected gap defense area.
Continuation corridor = the forward planning area between the accepted gap edge and target guide.
Acceptance edge = the side of the gap that price should hold for continuation structure to remain stronger.
Defense line = an ATR-buffered invalidation reference beyond the far side of the gap.
Labels = state changes such as new gap, acceptance watch, continuation ready, defense review, or failed acceptance.
Colors = bullish continuation context uses teal, bearish continuation context uses pink, watch states use indigo, and caution states use amber.
Panel = summarizes gap state, continuation score, defense line, fill risk, and next action.
🚦 Signals & States
• New Gap → a fresh gap continuation window has been detected.
• Acceptance Watch → price is holding the continuation side of the gap, but follow-through still needs confirmation.
• Continuation Ready → the gap has stronger acceptance, follow-through, room, and risk structure.
• Defense Test → price is retesting the gap edge or defense area.
• Fill Risk → the gap is being penetrated enough to reduce continuation quality.
• Gap Failed → the active gap has lost continuation acceptance.
🔔 Alerts Logic
Alerts trigger when a new gap continuation window appears, when the gap reaches READY state, when acceptance watch begins, when defense review becomes relevant, or when gap acceptance is lost.
Alerts are attention markers. They are not trade instructions and do not guarantee that continuation will occur.
🧩 Confluence Logic
The strongest continuation context appears when gap size, gap-edge acceptance, follow-through distance, stable volatility, low fill pressure, and enough forward room align.
When these elements align, the continuation score improves. When fill pressure rises or volatility becomes too hot, the score weakens.
📊 When to Use
• After opening gaps in stocks, indices, futures, or session-based markets
• During continuation attempts after a strong gap
• When reviewing whether a gap is holding acceptance or losing structure
• Around breakout continuation sessions where risk and target references need to be visible
⚠️ When NOT to Use
• Extremely low-liquidity markets
• Very noisy or overlapping session opens
• News-driven gaps with unstable spreads
• Markets where volume and session structure behave unusually
• Environments where price is already far beyond a reasonable risk reference
🎛️ Key Inputs
• Sensitivity → adjusts how strict the gap and score requirements are.
• Gap Mode → controls whether the script reads classic gaps only or adaptive continuation windows.
• Acceptance Bars → changes how many bars must hold the continuation side of the gap.
• Follow-Through ATR → controls the preferred travel away from the gap edge.
• Defense Buffer → sets the ATR spacing for the defense line.
• Forward Room Lookback → helps estimate whether nearby structure limits continuation room.
• Minimum Continuation Score → sets the READY threshold.
• Visual settings → control zones, corridors, lines, labels, object limits, and panel appearance.
• Show Failed / Stale Objects → controls whether old failed corridors remain visible. It is disabled by default for a cleaner publication view.
🖥️ Interface & Visual Design
The interface is built for quick planner-style review. The chart carries the structural map, while the panel provides the decision summary.
The first panel row follows the AGPro merged blue header standard. The remaining rows focus only on the practical planning fields: state, score, defense, fill risk, and action.
The visual hierarchy is intentionally restrained so the gap, corridor, and labels are readable without turning the chart into a crowded signal map.
By default, failed or stale gap objects are hidden after they lose live planning value. Event labels remain available so the chart keeps context without carrying too many old failed boxes.
🧪 Practical Usage Workflow
1. Read the panel state and continuation score.
2. Check whether price is holding the gap acceptance edge.
3. Review the continuation corridor and target guide.
4. Compare fill risk against the defense line.
5. Use alerts as review markers, not execution commands.
6. Confirm the context with broader market structure, liquidity, and personal risk rules.
🔍 Interpretation Guidelines
A high continuation score means the active gap has stronger structure inside this model. It does not mean the move must continue.
Low fill risk supports continuation structure. Rising fill risk means price is starting to challenge the gap.
The defense line is a planning reference. It is not a guaranteed stop level and should not replace the user's own risk process.
Continuation corridors are visual planning areas, not promised target zones.
🚫 What This Script Is NOT
This script is not a prediction engine.
This script is not financial advice.
This script is not an auto-trading system.
This script does not provide guaranteed signals.
This script does not replace independent confirmation, risk management, or execution discipline.
⚠️ Limitations & Transparency
Gap behavior varies heavily across asset classes, sessions, and timeframes.
Adaptive launch windows can help continuous markets, but they should still be interpreted as structured gap-like planning areas rather than classic exchange-session gaps.
High volatility can make defense and target references wider.
Low liquidity can distort gap quality, label timing, and fill-risk readings.
No rule-based script can fully account for news, slippage, spread changes, or sudden liquidity shifts.
🧠 Market Context Notes
Gap continuation is often more meaningful when it aligns with trend pressure, session participation, volatility structure, and clean forward room.
A gap is not important simply because it exists. It becomes more useful when price accepts one side of it and maintains a measurable defense structure.
🧾 Use Case Examples
When price gaps up, holds above the gap edge, and the continuation score improves, the script can help review whether the gap is being defended.
When price gaps down and repeatedly rejects back below the gap edge, the panel can help evaluate bearish continuation structure.
When fill risk rises quickly, the script highlights that the gap may be losing acceptance rather than continuing cleanly.
🧱 System Philosophy
AGProLabs tools are built around structured interpretation. The goal is not to add more signals to the chart. The goal is to turn market behavior into a cleaner review process.
Gap Continuation Planner follows that approach by converting a raw gap into a measurable planning object.
🔐 Non-Promise Statement
No indicator can remove uncertainty.
No score can guarantee continuation.
No planner can replace the trader's responsibility to manage risk.
📉 Risk Disclosure
Trading involves risk.
This script is provided for educational and analytical use only.
It does not provide financial advice, investment advice, trading advice, or guaranteed outcomes.
Users remain responsible for their own decisions, risk management, position sizing, and execution.
📚 Educational Note
The strongest use of this tool is to study whether a gap is being accepted or rejected as structure develops. It is designed to support review, patience, and disciplined interpretation.
Indicator

Session Range Expansion Planner [AGPro Series]Session Range Expansion Planner
🧠 Core Idea
Is the session expanding from balance into a valid range extension, or is the break still too weak to trust as context?
📌 Overview / What it does
Session Range Expansion Planner is a 1H-focused intraday execution-readiness tool built around one clear workflow: define the early-session balance, track expansion beyond that range, and score whether the move has enough acceptance, volume support, volatility fit, and target room to deserve attention.
The script produces a session range box, accepted target-room bands, acceptance/rejection context, alerts, and a premium AGPro panel with a 0-100 planner score. The default visual preset is optimized for 1H and lower charts. Higher intraday charts such as 4H are intentionally kept clean by default.
It does not predict the next candle, automate entries, or issue buy/sell commands. It organizes session behavior into a structured decision layer so the user can evaluate the setup within their own plan.
🎯 Purpose & Design Philosophy
This script was built to fill the gap between simple session boxes and generic breakout indicators.
Most tools show where the session range is. Fewer tools explain whether the break from that range is actually being accepted, whether participation supports it, and whether there is usable room beyond the range.
Session Range Expansion Planner supports a planning mindset: define balance first, wait for expansion, check acceptance, evaluate room, then decide whether the context is worth further review.
⚡ Why This Script Is Different
Most session tools focus on marking opens, coloring sessions, or printing a breakout label as soon as price crosses a high or low.
This script does NOT act as a generic session high/low map, generic support/resistance tool, or broad session reaction scanner.
Instead, it treats the first part of the session as a balance structure and asks whether the later expansion has enough quality to become actionable context. The decision layer is built around acceptance bars, volume support, ATR regime, obstacle distance, and target-room quality.
⚙️ Methodology
1. Context Detection
The script reads the selected intraday session and builds an initial balance range from the first user-defined number of bars.
2. Reference Mapping
The session balance high and low become the only active expansion boundaries. The tool does not use PDH, PDL, weekly open, order blocks, FVGs, or generic swing zones.
3. Reaction Evaluation
When price breaks beyond the balance range, the engine measures acceptance closes, volume support, ATR regime quality, break distance, and nearby obstacle room.
4. Visual Output
The script displays a centered session range label, directional expansion labels, target-room band, acceptance/rejection labels, alerts, and a premium panel with score and next-action state.
🗺️ How to Read the Chart
Session Range Box = the early-session balance area.
Expansion Labels = the side where price first expands beyond the balance high or low.
Target-Room Band = the projected room beyond the broken boundary after expansion has been accepted, scaled by session range or ATR.
Acceptance Labels = confirmation that price has sustained closes beyond the range for the configured number of bars.
Rejection Labels = warning that price has failed back through the broken boundary.
Colors:
• Teal = upside expansion context
• Pink = downside expansion context
• Amber = neutral, warning, or rejection context
• Indigo = AGPro visual accent and target-room support
Panel = the decision cockpit showing planner score, session range, expansion side, acceptance, room score, and next action.
🚦 Signals & States
• Range Set → the initial balance window has completed.
• Expansion Up → price expanded above the session balance high.
• Expansion Down → price expanded below the session balance low.
• Accepted → the expansion held beyond the range for the required acceptance bars.
• Rejection Risk → price failed back through the broken boundary.
• Room Check Reached → price reached the projected target-room area.
🔔 Alerts Logic
Alerts trigger when:
• Upside range expansion is detected
• Downside range expansion is detected
• Expansion becomes accepted
• Rejection risk appears after expansion
Alerts are attention markers. They are not trade instructions and should be interpreted together with broader market context.
🧩 Confluence Logic
The strongest context appears when expansion direction, sustained acceptance, volume support, balanced ATR regime, and clean target room align at the same time.
When those conditions stack together, the planner score rises and the panel moves toward a review-ready state.
📊 When to Use
• 1H intraday charts with clear session behavior
• Opening balance or early-session range workflows
• Breakout quality review
• Volatility expansion planning
• Session continuation evaluation
The script is most useful when a trader wants to know whether a session range break is actually being accepted, not just whether a line was crossed.
⚠️ When NOT to Use
• Very low-liquidity symbols
• Extremely noisy micro timeframes
• Markets with unreliable volume
• Sessions with irregular trading hours
• News-driven candles where range expansion is disorderly
In weak conditions, reduce sensitivity or require stricter acceptance.
🎛️ Key Inputs
• Session Timezone → defines how the selected session is interpreted.
• Expansion Session → sets the active intraday window. The default full-day session is designed to work cleanly on crypto and other 24-hour symbols.
• Visual Timeframe Preset → controls which intraday timeframes show chart objects. The default is 1H and lower because 4H session expansion charts can become too compressed.
• Balance Window Bars → controls how many early-session bars define the range.
• Acceptance Bars → defines how much sustained closing behavior is required.
• Sensitivity → adjusts how fast the script recognizes expansion.
• Confirmation Mode → controls wick, close, or strict acceptance confirmation.
• Minimum Planner Score → sets the score threshold for review-ready context.
• ATR Length → controls volatility normalization and label spacing.
• Obstacle Lookback → estimates nearby structure that may reduce room quality.
• Target Room Multiplier → controls the projected target-room distance.
• Visual Settings → control range boxes, centered range label limit, rails, accepted target-room band, minimum visual score, optional expansion labels, optional room-check labels, optional range-set labels, label size, and object limits.
• Panel Settings → control panel visibility, location, theme, and font size.
🖥️ Interface & Visual Design
The interface is chart-first. The range box and target-room band carry the main visual story, while labels explain state transitions only when meaningful events occur.
The panel is intentionally compact. It gives a fast read of expansion quality without forcing the user to decode many separate plots.
The first panel row follows the AGPro standard: a single merged blue header row with only the script name.
🧪 Practical Usage Workflow
1. Apply the script to an intraday chart.
2. Confirm the correct session and timezone.
3. Let the initial balance window complete.
4. Watch for expansion beyond the balance high or low.
5. Check whether acceptance bars confirm sustained behavior.
6. Read the planner score and room score.
7. Use the next-action state as context for your own execution plan.
🔍 Interpretation Guidelines
A clean expansion is not just a break beyond the range. It should show acceptance, participation, reasonable volatility, and enough room before nearby obstruction.
Low scores usually mean the break is early, unsupported, too noisy, too extended, or too close to an obstacle.
The best use is comparative: review which sessions and symbols repeatedly produce clean accepted expansions versus weak false breaks.
🚫 What This Script Is NOT
• Not a prediction engine
• Not financial advice
• Not auto trading
• Not guaranteed signals
• Not a buy/sell command system
• Not a generic support/resistance map
• Not an order block, FVG, or liquidity sweep scanner
⚠️ Limitations & Transparency
Session behavior can vary across assets, timeframes, exchanges, and trading hours.
ATR regime and volume support are rule-based approximations, not certainty models.
On very low timeframes, labels may appear more frequently. On higher intraday timeframes, fewer but more meaningful events are expected.
Markets can expand cleanly and still reverse later. The tool measures context quality, not future certainty.
🧠 Market Context Notes
Session range expansion often becomes more meaningful when it is read together with broader trend, liquidity, volatility, and higher-timeframe structure.
The script deliberately stays focused on session balance and expansion quality. Users can combine it with their own broader framework without duplicating other AGPro tools.
🧾 Use Case Examples
When price breaks above the session range, holds above the balance high for the required acceptance bars, and room score remains strong, the panel may shift into review-ready continuation context.
When price breaks the range but quickly closes back inside the balance, the script marks rejection risk and the panel moves away from continuation review.
🧱 System Philosophy
AGPro tools are built to help traders organize context into clear decision layers.
Session Range Expansion Planner follows that philosophy by turning a common intraday event into a structured planning process: balance, expansion, acceptance, room, action.
🔐 Non-Promise Statement
No script can guarantee future price movement.
The score is a structured context model, not a certainty model.
📉 Risk Disclosure
Trading involves risk. Market conditions can change quickly, and historical session behavior does not guarantee future outcomes.
Users are responsible for their own decisions, risk management, and position sizing.
This script is provided for educational and analytical use only and does not provide financial advice.
📚 Educational Note
Use the script to study how different markets expand from early-session balance. The most valuable insight is not a single label, but the repeated relationship between range quality, acceptance, room, and market context.
Indicator

TP_Ephem_LibLibrary "TP_Ephem_Lib"
Cowan-tailored heliocentric ephemeris (VSOP87D) for PulseWire.
@description Returns heliocentric ecliptic longitudes for Mercury through Neptune
@description (tropical or sidereal/Lahiri), synodic phases between any two planets,
@description and Cowan-canon helpers: 3-Step Astro cumulative advance (V4:L5079),
@description pentagram vertex dates (V4:L449), and cube-face boundary dates
@description (V1:L2106-2114, V1:L2962-2997). All math validated to <0.01 deg vs
@description Swiss Ephemeris (DE441) across 1899-2026. Frame: ecliptic of date.
jd_to_t_millennia(jd)
Parameters:
jd (float)
jd_from_timestamp(unix_ms)
Parameters:
unix_ms (int)
timestamp_from_jd(jd)
Parameters:
jd (float)
normalize_longitude(deg)
Parameters:
deg (float)
get_ayanamsa(jd)
Parameters:
jd (float)
get_helio_longitude(planet, jd, useSidereal)
Parameters:
planet (simple Planet)
jd (float)
useSidereal (simple bool)
get_sun_geo_longitude(jd, useSidereal)
Parameters:
jd (float)
useSidereal (simple bool)
get_synodic_phase(p1, p2, jd)
Parameters:
p1 (simple Planet)
p2 (simple Planet)
jd (float)
get_aspect_angle(p1, p2, jd)
Parameters:
p1 (simple Planet)
p2 (simple Planet)
jd (float)
average_speed_deg_per_day(planet)
Parameters:
planet (simple Planet)
speed_deg_per_day(planet, jd)
Parameters:
planet (simple Planet)
jd (float)
is_retrograde(planet, jd)
Parameters:
planet (simple Planet)
jd (float)
cumulative_advance_deg(planet, origin_jd, target_jd, useSidereal)
Parameters:
planet (simple Planet)
origin_jd (float)
target_jd (float)
useSidereal (simple bool)
cumulative_synodic_advance_deg(p1, p2, origin_jd, target_jd)
Parameters:
p1 (simple Planet)
p2 (simple Planet)
origin_jd (float)
target_jd (float)
find_advance_jd(planet, origin_jd, target_advance_deg, useSidereal)
Parameters:
planet (simple Planet)
origin_jd (float)
target_advance_deg (float)
useSidereal (simple bool)
find_synodic_advance_jd(p1, p2, origin_jd, target_synodic_advance_deg)
Parameters:
p1 (simple Planet)
p2 (simple Planet)
origin_jd (float)
target_synodic_advance_deg (float)
pentagram_vertex_jd(planet, origin_jd, n, useSidereal)
Parameters:
planet (simple Planet)
origin_jd (float)
n (simple int)
useSidereal (simple bool)
cube_face_boundary_jd(origin_jd, face_n)
Parameters:
origin_jd (float)
face_n (simple int) Library

Indicator

Volatility Hull Ribbon [BackQuant]Volatility Hull Ribbon
Overview
Volatility Hull Ribbon is a trend-following overlay built from a Hull-style moving average that replaces traditional volume weighting with volatility weighting . Instead of weighting price by traded volume, this indicator weights price by the absolute True Range of each bar, meaning bars with larger range expansion have more influence on the final trend estimate.
The goal is to create a smoother but responsive trend line that pays more attention to bars where the market actually moved with force. It then plots this volatility-weighted Hull structure as either a clean line or a ribbon-style band, with gradient fill, candle coloring, and long/short flip markers.
At a high level, the indicator does three things:
Builds a volatility-weighted moving average using True Range as the weighting source.
Applies Hull-style lag reduction to produce a faster trend-following curve.
Visualizes trend direction using slope, ribbon fill, candles, and flip signals.
Core idea
Most moving averages treat each bar equally or weight only by time. That means a quiet candle and a high-range expansion candle can have similar influence depending on the MA type.
Volatility Hull Ribbon takes a different approach:
Bars with larger True Range are treated as more important.
Bars with smaller True Range have less influence.
Recent bars are also weighted more heavily than older bars.
This creates a trend estimate that responds more strongly when the market expands, while remaining smoother during lower-energy movement.
What “volatility-weighted” means here
The custom weighting function uses:
Price source
Absolute True Range
A decreasing time weight
For each bar inside the lookback:
Weighted price contribution = source * abs(True Range ) * recency weight
Weight contribution = abs(True Range ) * recency weight
Then:
Volatility-weighted average = weighted price sum / weighted True Range sum
So price movement on wide-range bars matters more than price movement on quiet bars.
Why True Range is used
True Range captures more than just high-low movement. It accounts for gaps and previous close displacement. This makes it a broader volatility proxy than simple candle range.
Using True Range as the weight means the filter gives more importance to bars where:
Range expanded,
Price displaced aggressively,
Volatility increased,
Market participation likely intensified.
This is useful because strong trend moves often occur during volatility expansion, not during quiet drift.
Hull-style construction
The indicator then applies a Hull-style transformation to the volatility-weighted average.
The structure is:
VWHMA = VWMA_TR( 2 * VWMA_TR(src, len / 2) - VWMA_TR(src, len), sqrt(len) )
Where VWMA_TR means the custom True-Range-weighted moving average.
This follows the same logic as the classic Hull Moving Average:
Use a faster half-length average.
Use a slower full-length average.
Subtract the lagging component.
Smooth the result with sqrt(length).
The difference is that every smoothing step is volatility-weighted instead of standard weighted-average based.
Why this matters
A classic Hull Moving Average is already designed to reduce lag. This version modifies the internal weighting so the curve becomes more sensitive to volatility-backed price movement .
That means:
Large expansion bars can pull the filter faster.
Weak low-range chop has less effect.
Trend changes during strong movement can be reflected more clearly.
Trend detection
Trend direction is based on the slope of the VWHMA:
Bullish when VWHMA > VWHMA
Bearish when VWHMA < VWHMA
This is a simple but effective regime definition:
Rising volatility-weighted Hull = bullish trend pressure.
Falling volatility-weighted Hull = bearish trend pressure.
The script uses this slope state to color:
The main line,
The ribbon fill,
Optional candles,
Signal markers.
Ribbon mode
When “Plot as Band?” is enabled, the script creates a second line:
onebar_off = WMA(VWHMA , 10)
This is a delayed and smoothed version of the VWHMA. The area between the current VWHMA and this offset line becomes the ribbon.
Interpretation:
Ribbon expansion shows separation between current trend structure and its delayed reference.
Ribbon compression shows trend slowing or flattening.
A clean flip in the ribbon often coincides with trend transition.
The ribbon is not a volatility band. It is a trend displacement ribbon built from the difference between the current VWHMA and its delayed smoothed version.
Gradient fill logic
The fill is directional:
If VWHMA is above the offset line, fill intensity is stronger near the VWHMA and fades toward the offset.
If VWHMA is below the offset line, the gradient reverses.
This creates a cleaner visual than a flat fill because it emphasizes the active side of the ribbon.
In practice:
Strong bright ribbon = trend line leading the delayed reference.
Faded/narrow ribbon = weaker separation.
Ribbon reversal = trend pressure has shifted.
Signal logic
Signals are generated when the VWHMA slope changes direction:
Long signal: crossover(VWHMA, VWHMA )
Short signal: crossunder(VWHMA, VWHMA )
This means:
A long signal prints when the current VWHMA turns upward relative to the previous value.
A short signal prints when the current VWHMA turns downward.
These are slope-flip signals, not price crossover signals.
Important interpretation
A signal does not mean “buy blindly” or “sell blindly.” It means the volatility-weighted trend estimate has changed direction. The quality of the signal depends on:
Market structure,
Higher timeframe trend,
Volatility conditions,
Whether the ribbon is expanding or compressing.
Candle coloring
When enabled, candles are painted according to the VWHMA slope:
Bullish slope = long color.
Bearish slope = short color.
This makes the indicator easier to read as a regime overlay. You can quickly see when the market is consistently aligned with the volatility-weighted trend.
How to use it
1) Trend filter
Use the VWHMA color as a bias filter:
Only favor longs when the VWHMA is rising.
Only favor shorts when the VWHMA is falling.
2) Trend transition tool
Slope flips can identify early trend shifts:
Long marker = VWHMA has turned upward.
Short marker = VWHMA has turned downward.
Because the filter is Hull-style and volatility-weighted, it can react faster than slower trend filters while still suppressing some low-range noise.
3) Ribbon strength reading
The ribbon gives additional context:
Expanding ribbon = stronger separation and cleaner trend pressure.
Contracting ribbon = momentum weakening.
Ribbon flattening = chop or transition risk.
4) Pullback structure
In strong trends, price often respects the VWHMA or ribbon area:
Bull regime: pullbacks into the ribbon can act as support.
Bear regime: rallies into the ribbon can act as resistance.
5) Volatility-backed trend confirmation
Because large True Range bars influence the calculation more, this tool is useful for identifying whether trend changes are being supported by actual range expansion.
If price moves but the VWHMA does not respond strongly, the move may lack volatility-backed confirmation.
Input guide
Price Source
Defines the input series used for the calculation. Close is standard, but hl2, hlc3, or ohlc4 can be used for smoother structural behavior.
Lookback Period
Controls the smoothing length:
Lower values = faster response, more signals, more noise.
Higher values = smoother trend, fewer flips, more lag.
Plot as Band
Enables the ribbon view using the delayed smoothed VWHMA reference.
Line Width
Controls the main line thickness when not relying heavily on band mode.
Show Trend Candles
Paints candles by current trend state.
Show Signals
Toggles the long/short slope-flip markers.
Strengths
Uses volatility-weighted smoothing instead of equal weighting.
Combines volatility sensitivity with Hull-style lag reduction.
Clean ribbon visualization for trend displacement.
Simple slope-based regime interpretation.
Works well as a trend overlay or bias filter.
Limitations
Slope flips can still whipsaw in sideways markets.
Large wick bars can influence the filter strongly because True Range is used as weight.
It does not measure volume, despite using a VWMA-style internal function.
It is a trend tool, not a complete trading system.
Best use case
Volatility Hull Ribbon works best when used as a visual trend structure layer:
Use color for bias.
Use ribbon expansion/compression for strength.
Use slope flips for regime transitions.
Use price interaction with the ribbon for pullback context.
Summary
Volatility Hull Ribbon is a Hull-style trend overlay that replaces traditional weighting with True Range weighting, making the moving average more responsive to volatility-backed price movement. It builds a low-lag volatility-weighted Hull curve, compares it to a delayed smoothed reference to form a ribbon, and uses slope changes to define trend direction and signals. The result is a clean, responsive trend ribbon that highlights when volatility-backed trend pressure is rising, fading, or reversing. Indicator

Indicator

Indicator

Centro de Mando Quant: Z-Score & F*cking Sortino RatioWhat the f*ck is up, traders? Listen to me. If you are looking for a magical indicator that paints little green and red arrows to tell you when to buy and sell like a toddler, keep walking. This tool is not for you.
90% of retail traders get absolutely slaughtered in the markets because they trade based on emotions, hope, and imaginary lines drawn blindly on a chart. This script was forged with a strictly military and quantitative mindset. We don't guess here; we calculate probabilities, standard deviations, and asymmetric risk.
I present to you the Quant Command Center, a rolling tactical dashboard designed specifically to measure the guts of any highly volatile crypto, without cluttering your price action.
⚙️ THE QUANTITATIVE ARSENAL (Under the Hood)
This panel does NOT give automated signals. It gives you raw data so YOU can make the decision to pull the trigger.
Price Z-Score (Statistical Anomalies): Calculates how many standard deviations the current price is from its mean. If the Z-Score breaks +2.5 or drops below -2.5, you are looking at an unsustainable parabolic move. It tells you exactly when the market is overextended so you stop buying the top out of pure FOMO.
Volume Z-Score: Confirms if the current move is backed by heavy artillery (institutional money) or if it's just a weekend skirmish with zero real volume.
Rolling Sharpe Ratio: Measures the performance of price action against total volatility over the selected period.
The Sortino Ratio (Asymmetric Risk): The real survival filter. Unlike the Sharpe ratio, Sortino ONLY penalizes downside volatility. If the Sortino is red, the trend will tear you apart. If it's green, the bullish momentum has a clear, clean path.
🛠️ TACTICAL INSTRUCTIONS
Apply the indicator on 1H or 4H timeframes to filter out market noise.
Keep your eyes locked on the Statistical Context in the bottom right panel.
Use extreme Z-Scores to hunt for Mean Reversions or to lock in your profits.
Use positive Sortino ratios to confirm your entries on Breakouts.
"In war and in the markets, hope is not a tactical strategy. Cold data and discipline are your only salvation."
If you aren't willing to manage your risk, this dashboard won't save you. But if you have the discipline to read the numbers, plan your trade, and execute without hesitation, this tool will give you an unfair statistical advantage over the rest of the market.
Lock and load. Do your backtesting, execute your plan, and stop giving your money away to the market. Dismissed! Indicator

Risk Exposure Compass [AGPro Series]Risk Exposure Compass
🧠 Core Idea
Is the current chart exposing the trader to balanced risk, or is price already stretched, blocked, or too early?
📌 Overview / What it does
Risk Exposure Compass is a chart-first risk planning tool designed to evaluate the current exposure quality of a setup before the trader treats it as actionable.
Instead of printing generic buy or sell signals, the script studies ATR stretch, range position, distance from the exposure mean, trend maturity, target-edge room, and invalidation distance. These components are converted into a 0-100 Risk Exposure Score and a clear next-action state.
The script produces a risk compass band, invalidation shelf, target-edge guide, exposure heat labels, alerts, and a clean AGPro planning panel. It does not predict price direction, automate execution, calculate position size, or guarantee that a setup will follow through.
🎯 Purpose & Design Philosophy
This script was built for traders who want to ask a practical pre-decision question: is the chart still offering clean exposure, or has the move become too stretched to evaluate cleanly?
The gap it fills is different from a manual risk/reward visualizer, position planner, or risk runway tool. Risk Exposure Compass focuses on the current chart location itself: how far price is from mean, how mature the move is, whether volatility load is normal, whether target room is open, and whether invalidation distance is controlled.
The design supports a disciplined review mindset. It helps users avoid treating every active move as equal by separating balanced exposure, watch context, stretched risk, blocked room, and reset conditions.
⚡ Why This Script Is Different
Most tools focus on entries, support/resistance zones, take-profit ladders, or manual risk/reward boxes.
This script does NOT build a full trade plan, does NOT calculate position size, does NOT create a TP ladder, and does NOT become a dashboard-only stress meter.
Instead, it draws a live risk compass directly on the chart and scores whether the current price location is balanced, extended, blocked by nearby target structure, or too early for clean planning.
⚙️ Methodology
1. Context Detection
The script reads automatic long-side or short-side exposure using mean and trend context, or lets the user force the exposure side manually.
2. Reference Mapping
It maps an exposure mean, active range, structural invalidation shelf, target-edge obstruction, and a projected compass band.
3. Reaction Evaluation
The model scores five core components: ATR stretch, range position, distance from mean, trend maturity, and target obstruction. Invalidation distance and volatility load refine the final state.
4. Visual Output
The output is shown through a centered compass band label, invalidation and target guide lines, compact exposure labels, deterministic alerts, and a premium AGPro panel.
🗺️ How to Read the Chart
Zones = the risk compass band where price is considered more balanced relative to the active exposure mean.
Labels = compact state markers showing BALANCED, WATCH, STRETCHED, BLOCKED, or RESET context.
Colors = teal marks cleaner exposure, pink marks blocked or failed context, amber marks stretched risk, and indigo marks watch or transition states.
Panel = the panel summarizes Exposure State, Risk Score, Volatility Load, Distance Risk, and Action.
🚦 Signals & States
• BALANCED → exposure is inside the compass band with a strong enough score.
• WATCH → exposure quality is developing but not yet clean enough for balanced status.
• STRETCHED → price is extended from mean, late in range position, volatility is overloaded, or invalidation distance is too wide.
• BLOCKED → nearby target-edge room is limited relative to current exposure.
• RESET → the chart is early, unclear, or below the minimum quality threshold.
🔔 Alerts Logic
Alerts trigger when exposure moves into BALANCED, WATCH, STRETCHED, BLOCKED, or RESET state.
These alerts are attention markers. They are not trade instructions, entry signals, exit signals, or automated strategy commands.
🧩 Confluence Logic
The strongest exposure context appears when ATR stretch is controlled, price is not at an extreme range edge, distance from mean is balanced, trend maturity is not too early or too late, and target room remains open.
When these conditions align, the Risk Exposure Score rises and the panel state becomes easier to interpret.
📊 When to Use
• Before evaluating a discretionary setup
• During pullbacks or pauses where risk location matters
• Around continuation attempts after a trend has already moved
• Before breakouts where price may already be extended
• When comparing whether one chart has cleaner exposure than another
⚠️ When NOT to Use
• Extremely low-liquidity symbols
• Very noisy micro-timeframes
• News-driven volatility spikes
• Non-standard chart types that distort candle range and ATR behavior
• Situations where the user expects a signal-only entry tool
🎛️ Key Inputs
• Exposure Side → controls Auto, Long Exposure, or Short Exposure evaluation.
• Range Lookback → defines the range used for price-location scoring.
• ATR Length → normalizes stretch, distance risk, target room, and label offsets.
• Exposure Mean EMA → defines the mean used for the compass band and distance scoring.
• Target Obstruction Lookback → controls how nearby target-edge room is estimated.
• Invalidation Shelf Lookback → controls the structural invalidation reference.
• Sensitivity → adjusts how strict the exposure model is.
• Visual settings → control compass band, guides, candle heat, labels, panel location, theme, and font sizes.
🖥️ Interface & Visual Design
The interface is built around one primary chart object: the risk compass band.
The panel follows the AGPro public-release standard with one merged blue header row containing only the script name. The rows are kept compact so the tool stays readable without becoming dashboard-heavy.
Labels are intentionally short, offset away from candles, and controlled with cooldown and maximum-visible settings.
🧪 Practical Usage Workflow
1. Read the panel Exposure State and Risk Score.
2. Check whether price is inside, below, or beyond the risk compass band.
3. Review Distance Risk to see whether invalidation is controlled, fragile, or too wide.
4. Check target-edge room before treating exposure as clean.
5. Use alerts as review prompts, not as automated trading instructions.
🔍 Interpretation Guidelines
A high score means the chart is closer to balanced exposure according to the script's rule-based model.
A low score means price may be too early, too stretched, blocked by nearby structure, or unclear relative to mean and range position.
The best interpretation comes from reading score, state, volatility load, distance risk, and target room together instead of relying on one label.
🚫 What This Script Is NOT
• Not a prediction engine
• Not financial advice
• Not auto trading
• Not guaranteed signals
• Not a position sizing calculator
• Not a manual risk/reward visualizer
• Not a take-profit ladder
⚠️ Limitations & Transparency
The model is rule-based and depends on recent structure, ATR, moving averages, candle range, and target-edge mapping.
Different timeframes can produce different exposure states because range, trend maturity, and invalidation shelves change with timeframe.
Fast volatility expansion can move the script quickly from balanced to stretched, while low-volatility environments can keep exposure in reset or watch state for longer.
No rule-based tool can know a user's actual execution plan, account risk, broker rules, or broader market thesis.
🧠 Market Context Notes
Risk exposure is not the same as direction.
A chart can be bullish but stretched, bearish but blocked, or directionally interesting while still offering poor exposure quality.
This script is designed to keep that distinction visible.
🧾 Use Case Examples
When price is above the exposure mean, inside the compass band, with controlled invalidation distance and enough target room, the panel can shift toward BALANCED.
When price accelerates far beyond the compass band with hot volatility and a late range position, the script can mark STRETCHED risk.
When price is close to a prior target edge and the room score is weak, the script can mark BLOCKED even if the broader trend still looks strong.
🧱 System Philosophy
The AGPro approach is to turn chart information into structured decision context.
Risk Exposure Compass follows that approach by converting price location into a cleaner review framework: mean, range, volatility, invalidation, target room, score, and next state.
🔐 Non-Promise Statement
This script does not provide certainty.
It does not guarantee that balanced exposure will lead to follow-through.
It only organizes current chart conditions so exposure quality is easier to review.
📉 Risk Disclosure
Trading involves risk.
Users are responsible for their own analysis, execution, risk management, and decisions.
This script is for educational and analytical purposes only and does not provide financial advice.
📚 Educational Note
Use the tool to study how price moves from reset to watch, from watch to balanced, and from balanced to stretched or blocked as market context changes.
Indicator

Invalidation Quality Planner [AGPro Series]Invalidation Quality Planner
🧠 Core Idea
Is the active invalidation shelf meaningful enough to build a plan around, or is it fragile, distant, weak, or already violated?
📌 Overview / What it does
Invalidation Quality Planner is a chart-first risk planning tool designed to evaluate the quality of the level that would invalidate a setup idea.
Instead of drawing generic support/resistance zones or printing buy/sell signals, the script studies one active invalidation shelf and converts its structure into a 0-100 quality score. It measures swing clarity, defended reactions, prior violations, wick pressure, volatility buffer, forward room, and violation risk.
The output is a focused planning workflow: an invalidation shelf zone, shelf and violation guides, forward-room reference, compact event labels, alerts, and a clean AGPro decision panel. It does not predict future price movement, automate decisions, or guarantee that any shelf will hold.
🎯 Purpose & Design Philosophy
This script was built for traders who want to judge whether their risk reference is structurally meaningful before relying on it.
Many tools show entries, targets, support/resistance zones, or stop distances. This tool focuses on the deeper planning question: is the invalidation level itself strong enough to deserve trust?
The design supports a disciplined setup-review mindset. It helps users separate a clean invalidation shelf from a weak, noisy, overextended, or already violated one.
⚡ Why This Script Is Different
Most tools focus on signals, stop-loss placement, support/resistance mapping, or risk/reward drawings.
This script does NOT become a generic S/R zone map, a stop-loss optimizer, a position-size calculator, a target ladder, or an entry signal tool.
Instead, it evaluates the quality of the invalidation reference. The core output is not a trade command. It is a planning state that helps users decide whether the current shelf is VALID, on WATCH, FRAGILE, DISTANT, DEFENDED, WEAK, or VIOLATED.
⚙️ Methodology
1. Context Detection
The script detects the active planning side using trend context and range location, or allows the user to force long-context or short-context evaluation.
2. Reference Mapping
It maps the active invalidation shelf from confirmed swing pivots, with a fallback structure reference when no fresh pivot is available.
3. Reaction Evaluation
The model scores swing clarity, defended shelf reactions, clean history, wick pressure, ATR-normalized shelf distance, volatility context, violation risk, and forward room.
4. Visual Output
The output is shown through an invalidation shelf zone, violation guide, forward-room guide, compact labels, deterministic alerts, and a premium AGPro panel.
🗺️ How to Read the Chart
Zones = the active invalidation shelf used by the planner. It is a risk reference, not a generic support/resistance zone.
Labels = compact state markers showing VALID, WATCH, DEFENDED, FRAGILE, DISTANT, WEAK, or VIOLATED context.
Colors = teal marks cleaner planning context, pink marks violation or weak context, amber marks caution, and indigo marks watch/transition context.
Panel = the panel summarizes Invalidation Quality, Distance, Structure Support, Violation Risk, and Action.
🚦 Signals & States
• VALID → the active invalidation shelf has enough structure and quality to deserve review.
• WATCH → the shelf is improving but not clean enough for VALID state.
• DEFENDED → price tested the shelf and closed back in favor of the active planning side.
• FRAGILE → price is too close to the shelf, making normal noise more important.
• DISTANT → the shelf is too far from price for clean planning context.
• WEAK → the shelf lacks enough structure, reaction memory, or clean history.
• VIOLATED → price crossed the active violation guide and the context should be rebuilt.
🔔 Alerts Logic
Alerts trigger when the planner enters VALID state, enters WATCH state, detects a defended shelf reaction, marks a weak/fragile/distant shelf, or detects a shelf violation.
These alerts are attention markers. They are not trade instructions, entry signals, exit commands, or automated strategy actions.
🧩 Confluence Logic
The strongest invalidation context appears when swing clarity, defended reactions, clean violation history, controlled wick pressure, balanced ATR distance, and sufficient forward room align.
When those factors align, the quality score rises and the panel can move from WATCH to VALID. If the shelf becomes too close, too distant, noisy, or violated, the state downgrades.
📊 When to Use
• Before evaluating a discretionary setup
• During pullbacks where a structural invalidation shelf is forming
• Around continuation setups where risk needs a clean reference
• Before breakout or reclaim attempts where the failure point matters
• When comparing whether one setup has a cleaner invalidation reference than another
⚠️ When NOT to Use
• Extremely low-liquidity symbols
• Very noisy micro-timeframes with unstable wicks
• News-driven volatility spikes
• Markets where recent structure is distorted and no useful invalidation shelf exists
• Situations where the user expects a signal-only entry tool
🎛️ Key Inputs
• Planning Side → controls Auto, Long Context, or Short Context evaluation.
• Shelf Pivot Left / Right → controls how strict the confirmed swing shelf detection is.
• Shelf Fallback Lookback → defines the backup structure reference when no fresh pivot exists.
• Reaction Memory Lookback → controls how far back defended reactions and violations are counted.
• Shelf Zone Buffer ATR → controls the width of the invalidation shelf zone.
• Violation Buffer ATR → controls when price is treated as crossing beyond the shelf.
• VALID / WATCH Thresholds → adjust how selective the planner is.
• Visual settings → control shelf zones, guide lines, memory zones, labels, panel location, theme, and font sizes.
🖥️ Interface & Visual Design
The interface is built around one primary chart object: the invalidation shelf zone.
The panel follows the AGPro public-release standard with one merged blue header row containing only the script name. The layout keeps the key planning information readable without turning the script into a dashboard-heavy overlay.
Labels are compact, offset away from candles, and controlled with cooldown and maximum-visible settings.
🧪 Practical Usage Workflow
1. Read the panel Invalidation Quality and Action state.
2. Check whether price is respecting, approaching, or violating the shelf zone.
3. Review the Distance row to see whether the shelf is balanced, fragile, or distant.
4. Compare Structure Support with Violation Risk.
5. Treat alerts as review prompts and confirm the broader market context before making any decision.
🔍 Interpretation Guidelines
A higher score means the planner sees stronger alignment between shelf structure, reaction memory, clean history, distance quality, violation risk, and forward room.
VALID does not mean a trade must be taken. It means the invalidation shelf is meaningful enough to deserve attention.
WATCH means the shelf may be developing but still needs stronger evidence.
FRAGILE, DISTANT, WEAK, and VIOLATED are caution states that help users avoid building a plan around a poor invalidation reference.
🚫 What This Script Is NOT
• Not a prediction engine
• Not financial advice
• Not auto trading
• Not guaranteed signals
• Not a generic support/resistance mapper
• Not a stop-loss optimizer
• Not a position sizing calculator
• Not a take-profit planner
⚠️ Limitations & Transparency
Pivot-based shelves are confirmed after the selected pivot strength completes, so the script is intentionally reactive rather than predictive.
Different timeframes can create different shelf references, reaction counts, and violation-risk readings.
Volatility changes can alter ATR-normalized distance, shelf width, and forward-room conditions.
The script is rule-based and should be interpreted as an analytical planning layer, not as certainty.
🧠 Market Context Notes
Invalidation quality is not only about distance. A shelf can be close but meaningful, distant but inefficient, or visually obvious but already weakened by violations.
The planner is most useful when it helps the user ask better questions before trusting a setup idea.
🧾 Use Case Examples
When price pulls back toward a clean swing shelf, defends it, and still has enough forward room, the planner may show DEFENDED or VALID context.
When price is sitting directly on the shelf with heavy wick pressure, the planner may mark FRAGILE even if the level looks visually interesting.
When price crosses beyond the violation guide, the planner marks VIOLATED so the old risk reference is not treated as still clean.
🧱 System Philosophy
Invalidation Quality Planner follows the AGPro Series decision-engine approach:
Context first.
Risk reference before target.
Structure before signal.
Attention markers instead of promises.
🔐 Non-Promise Statement
No indicator can remove uncertainty.
No state, score, label, alert, or visual zone should be interpreted as guaranteed market direction.
📉 Risk Disclosure
Trading involves risk.
All decisions remain the responsibility of the user.
This script is for educational and analytical chart review only and does not provide financial advice.
📚 Educational Note
Use the tool to study how invalidation references form, defend, weaken, or fail across different market conditions.
Indicator

Indicator

L-TPI Correlation Assets# L-TPI Correlation Assets
A composite trend-probability indicator that scores the current asset's directional bias and **scales that score by its rolling correlation to Bitcoin (INDEX:BTCUSD)**. The result is a single weighted signal that strengthens when the asset is moving with BTC and fades toward neutral when the relationship breaks down.
---
## Concept
Most trend indicators tell you *what* an asset is doing. This one asks a second question: *how much does that signal matter right now, given the asset's relationship to the broader crypto market?*
The script does this in three stages:
1. **Trend Probability Index (TPI)** — a 4-filter composite that produces a normalized trend score in the range ` `.
2. **Multi-Period Correlation Weight** — a weighted average of the asset's price correlation to BTC across five lookback windows.
3. **Final Weighted Score** — the TPI multiplied by the correlation weight, with a configurable neutral zone around zero.
---
## 1. Trend Probability Index (TPI)
Four independent filters each cast a vote of `+1` (bullish) or `-1` (bearish):
| Filter | Logic | Bullish When |
|---|---|---|
| **f1 — ROC** | Rate of Change over *N* bars | ROC > 1 |
| **f2 — RSI** | Relative Strength Index | RSI > 50 |
| **f3 — EMA Cross** | Fast EMA vs. Slow EMA | Fast > Slow |
| **f4 — SMA** | Price vs. long SMA | Close > SMA |
- **Raw Trend Score** = `f1 + f2 + f3 + f4` → integer in ` `
- **Avg Trend Score** = `Raw / 4` → normalized to ` `
The Avg Trend Score is the TPI value passed forward.
---
## 2. Correlation Weight (vs. INDEX:BTCUSD)
The script computes the **Pearson correlation coefficient** between the chart asset's close and BTC's close across **five user-defined lookback windows** (default 30, 60, 90, 180, 365 bars). Each window has its own user weight (default 1, 2, 3, 4, 5 — favoring longer horizons).
For each window:
- Validity is checked: a window must have at least *Min valid obs ratio* (default 80%) of aligned, non-`na` bars.
- Invalid windows are excluded from the weighted average.
The final weight is a clamped weighted mean:
```
weight = clamp( Σ(corr_i × user_weight_i) / Σ(user_weight_i), -1, +1 )
```
BTC is fetched via `ticker.modify` so dividend/session adjustments on the chart propagate to the comparison series.
---
## 3. Final Weighted Score
```
final_weighted_score = avg_trend_score × weight
```
- **Range:** ` `
- **Strong bullish:** TPI is bullish *and* asset moves with BTC → score pushes toward +1
- **Strong bearish:** TPI is bearish *and* asset moves with BTC → score pushes toward −1
- **Neutral / decoupled:** TPI is mixed *or* correlation is weak → score collapses toward 0
A configurable **neutral zone** (default `±0.02`) flags conditions where the signal is too weak to act on.
---
## Visual Output
- **Final Weighted Score** — bold line; green above 0, red below, yellow in the neutral zone.
- **Correlation Weight** — stepline showing the current BTC-correlation multiplier.
- **Raw / Avg Trend Score** — the underlying TPI before correlation weighting.
- **Per-window correlations** — optional plots for the 30/60/90/180/365-bar `r` values.
- **Neutral zone** — optional background tint, threshold lines, and diamond marker.
- **Underlying filters** — ROC, RSI, EMAs, SMA can each be plotted individually.
### Tables
- **Signal Table** — every filter's state, raw/avg trend, correlation weight, final score, and overall bull/bear/neutral state.
- **Correlation Diagnostic Table** — per-window `r`, user weight, validity status, and resolved comparison symbol.
- **Final Score Table** — large display of the final weighted score for clean screenshots / streaming.
All tables have configurable positions.
---
## Inputs Overview
| Group | Key Inputs |
|---|---|
| Global | Timeframe |
| Neutral Zone | Low / High thresholds |
| ROC, RSI, EMA, SMA | Lengths for each filter |
| Correlation Weight | 5 × (period, weight), min valid obs ratio |
| Plot Toggles | Per-component visibility |
| Tables | Show/hide and positioning |
---
## How to Read It
- **Score > 0, rising, green:** trend filters and BTC correlation both supportive.
- **Score < 0, falling, red:** trend filters and BTC correlation both negative.
- **Score in yellow zone:** either filters are split, or the asset has decoupled from BTC — treat as no-trade.
- **Correlation weight near 0:** asset is currently uncorrelated with BTC; the trend signal is being intentionally muted.
---
## Notes & Limitations
- Comparison is hardcoded to `INDEX:BTCUSD`. Most useful on crypto and crypto-adjacent assets.
- Correlation is computed on **raw closes**, not returns. This produces smoother, more persistent `r` values that emphasize co-movement of price levels rather than short-term return co-movement.
- The TPI uses a fixed equal-weight blend of ROC, RSI, EMA cross, and SMA. It's a deliberately simple base; the correlation weighting is where the differentiation comes from.
- Designed for higher timeframes (default 1D). Works on lower TFs but the long correlation windows (e.g. 365 bars) become short in calendar time.
---
*Not financial advice. Always backtest and validate on your own instruments and timeframe before using any indicator for live decisions.* Indicator
