Candlestick FootprintsThis layer builds the structural backbone of the indicator using confirmed market pivots.
Code behavior:
ta.pivothigh() detects swing highs
ta.pivotlow() detects swing lows
Both require confirmation (pivotLen delay), so they are non-repainting but lagging
Memory system:
The variables:
p1, p2, p3, p4
store the last four pivot points in sequence.
Each new pivot shifts the structure forward:
p1 → p2 → p3 → p4
Purpose:
This creates a market structural memory, allowing the system to analyze movement sequences instead of single candles.
2. CORE PROJECTION LAYER
This layer generates a directional projection based on the last impulse.
Core logic:
move = p4 - p3
proj = p4 + move
Interpretation:
The system assumes that:
the last impulse leg may repeat in magnitude
So it projects a mirrored movement forward from the last pivot.
Nature of this model:
This is a mirror impulse projection model, not a predictive statistical model.
It assumes structural repetition in price behavior.
3. CLUSTERING LAYER (CORE INTELLIGENCE)
This is the most important layer of the system.
It groups similar projected levels into liquidity zones.
Data structures:
bullMid / bullCnt → bullish clusters
bearMid / bearCnt → bearish clusters
Clustering logic:
If a new projection is close to an existing one:
abs(proj - old) < ATR * tolerance
Then:
the cluster count increases
the zone center is recalculated (averaged)
the liquidity zone becomes stronger
Outcome:
Repeated projections create:
liquidity magnet zones (price attraction areas)
4. VISUALIZATION LAYER
This layer is purely graphical.
Tools used:
box.new() for zones
label.new() for cluster information
Bull zones:
Aqua = weak bullish flow
Lime = strong bullish accumulation
Bear zones:
Red = bearish pressure zones
Important:
This layer does NOT generate trading signals.
It only visualizes clustered market structure.
5. DIRECTION LOGIC LAYER
Direction is determined by projection comparison:
isBull = proj > p4
isBear = proj < p4
Meaning:
If projection is above last pivot → bullish structure
If below → bearish structure
This is a structural direction classifier, not a momentum oscillator.
6. SYSTEM PHILOSOPHY
This indicator is not based on traditional technical indicators.
It does NOT use:
Moving averages
RSI
MACD
Instead, it focuses on:
structural repetition
pivot-based memory
clustering of projected price levels
Core idea:
Markets tend to revisit structurally repeated zones rather than random levels.
7. FINAL SYSTEM OUTPUT
The system produces:
Liquidity zones
Cluster strength (count-based)
Directional bias (bull/bear)
Visual heatmap of price memory
Final interpretation:
This is a structural probability map of where price tends to accumulate and react.
🇹🇷 TÜRKÇE AÇIKLAMA (TAM KATMANLI)
1. PIVOT YAPISI KATMANI
Bu katman sistemin iskeletini oluşturur ve piyasa pivotlarını kullanır.
Çalışma mantığı:
ta.pivothigh() swing high noktalarını bulur
ta.pivotlow() swing low noktalarını bulur
Pivotlar onaylıdır, bu yüzden gecikmelidir ama repaint yapmaz
Hafıza sistemi:
p1, p2, p3, p4
son 4 pivotu saklar.
Her yeni pivot geldiğinde yapı kayar:
p1 → p2 → p3 → p4
Amaç:
Bu yapı, tek mum değil:
piyasanın hareket dizisini analiz eden bir hafıza sistemi oluşturur
2. PROJEKSİYON KATMANI
Bu katman son hareketi baz alarak ileri projeksiyon üretir.
Temel hesap:
move = p4 - p3
proj = p4 + move
Mantık:
Sistem şunu varsayar:
son impuls hareket tekrar edebilir
Bu yüzden aynı hareketi ileri taşır.
Model tipi:
Bu bir:
ayna hareket projeksiyon modelidir
3. CLUSTER (KÜMELEME) KATMANI
Sistemin en önemli kısmıdır.
Benzer projeksiyonları aynı bölgede toplar.
Veri yapıları:
bullMid / bullCnt → bullish bölgeler
bearMid / bearCnt → bearish bölgeler
Çalışma mantığı:
Eğer yeni proje eski bölgeye yakınsa:
abs(proj - old) < ATR toleransı
Şunlar olur:
cluster sayısı artar
merkez yeniden hesaplanır
bölge güçlenir
Sonuç:
Tekrarlanan fiyat bölgeleri:
likidite mıknatıs alanları oluşturur
4. GÖRSELLEŞTİRME KATMANI
Bu katman sadece görsel sunum yapar.
Araçlar:
box.new() → zone çizimi
label.new() → bilgi etiketi
Bull bölgeler:
Aqua = zayıf bullish akış
Lime = güçlü bullish birikim
Bear bölgeler:
Red = satış baskısı
Önemli:
Bu katman sinyal üretmez.
Sadece yapıyı görselleştirir.
5. YÖN MANTIĞI KATMANI
Yön projeksiyona göre belirlenir:
isBull = proj > p4
isBear = proj < p4
Anlamı:
yukarı projeksiyon → bullish yapı
aşağı projeksiyon → bearish yapı
Bu bir momentum değil:
yapısal yön sınıflandırmasıdır
6. SİSTEM FELSEFESİ
Bu indicator klasik teknik analiz değildir.
Şunları kullanmaz:
MA (hareketli ortalama)
RSI
MACD
Bunun yerine:
piyasa tekrarları
pivot hafızası
cluster davranışı
kullanır.
Temel fikir:
Piyasa rastgele değil:
belirli yapısal bölgeleri tekrar ziyaret eder
7. SONUÇ
Sistem şunları üretir:
likidite bölgeleri
cluster gücü
yön biası (bull/bear)
fiyatın hafıza haritası
Final yorum:
Bu sistem fiyatın nerede reaksiyon verme ihtimalinin yüksek olduğunu gösteren yapısal bir olasılık haritasıdır. Indicator

Indicator

Risk Management [odnac]📌 Overview
This indicator helps you visually manage risk — the most critical aspect of trading. By entering your total capital, risk percentage, and leverage, it automatically calculates the optimal position size, required margin, and risk-to-reward ratio (R:R), and displays everything directly on the chart.
⚙️ Key Features
Automatic Position Size Calculation — Calculates the optimal entry size based on your configured risk % and stop loss distance.
R:R Visualization — Displays entry, stop loss, and take profit levels on the chart with colored fill zones and ratio labels at the center.
Real-time PnL Tracking — Shows live profit/loss (% and amount) with leverage applied in the info table after entry.
Market/Limit Entry Detection — Automatically displays B/S signals and triggers alerts when price reaches the entry level.
Multi-Currency Support — Choose from 15 currency symbols including USD, EUR, JPY, and BTC.
UI Customization — Freely adjust line colors, table position, and transparency to match your chart theme.
📋 Input Parameters
Total Capital Total trading capital
Risk % Maximum loss allowed per trade
Leverage Leverage multiplier
Entry / Stop / TP Set prices by clicking directly on the chart
💡 Tips
Set your levels in order: Entry → Stop Loss → Take Profit by clicking on the chart.
It is recommended to only consider trades where R:R is at least 1:2 or higher.
Always check the position size and required margin to avoid over-leveraging.
Enable the B/S Signal alert condition to receive notifications at entry and exit points.
⚠️ Important Notes
Please review the entry detection logic below before using this indicator.
1. Entry signals are triggered by high/low touch, not by candle close.
If the entry price falls within the high-to-low range of the current forming candle, a signal may fire even if the closing price has not yet reached the entry level. Always verify actual order fills manually.
2. A ⚠️ Market Entry warning is shown when a market order is detected.
If the following conditions are met, the indicator assumes a market entry has likely already occurred and displays a warning on the entry label.
Long position — The current candle opened below the entry price
Short position — The current candle opened above the entry price
B/S signals are not displayed when a market entry is detected. Additionally, the actual fill price may differ from the configured entry price, so always confirm directly.
3. B/S Signal Label Behavior
B (Buy) or S (Sell) signals are only displayed on the chart when limit entry conditions are met. When the indicator detects a market entry (Warning state), it considers the position already entered and therefore no B/S signal label is generated.
🛠️ How to Set Up
Capital & Risk — Enter your total capital and the risk percentage you are willing to accept per trade.
Position Settings — Click on the chart in order: Entry Price → Stop Loss → Take Profit to define your range, then confirm.
UI & Colors — Adjust colors and table position to match your personal chart theme. Indicator

Price*Volume Z-Score OscillatorUseful for finding statistically significant order blocks for OTM options on stocks. Used to find "informed traders".
To understand the math behind this indicator, we have to break it down into three distinct layers: the **Variable Construction**, the **Central Limit Theorem application**, and the **Z-Transformation**.
---
### 1. The Variable: Dollar Volume ( BMV:PV $)
Instead of looking at Price or Volume in isolation, we create a composite variable:
$$PV_t = P_t \times V_t$$
* **$P_t$**: The closing price at time $t$.
* **$V_t$**: The number of shares/contracts traded at time $t$.
This represents the total **nominal value** flowing through the asset. It is a more rigorous measure of market conviction than volume alone because it accounts for the capital required to move the price at that specific level.
---
### 2. The Moving Window (Rolling Statistics)
We don't compare the current BMV:PV $ to the beginning of time; we compare it to a **lookback window** ($n=20$).
#### The Arithmetic Mean ($\mu$)
We calculate the Simple Moving Average of the BMV:PV $ product:
$$\mu_{PV} = \frac{1}{n} \sum_{i=0}^{n-1} PV_{t-i}$$
This establishes the "expected" liquidity environment for the current regime.
#### The Standard Deviation ($\sigma$)
We measure the dispersion (volatility) of the BMV:PV $ product over that same window:
$$\sigma_{PV} = \sqrt{\frac{1}{n} \sum_{i=0}^{n-1} (PV_{t-i} - \mu_{PV})^2}$$
This tells us how much the "Dollar Volume" typically fluctuates. If $\sigma$ is high, the market is erratic; if $\sigma$ is low, the market is consistent.
---
### 3. The Z-Score Transformation
The Z-score is a "dimensionless" number. It strips away the dollar signs and the share counts, leaving only a pure measure of **distance in units of volatility**.
$$Z = \frac{PV_{current} - \mu_{PV}}{\sigma_{PV}}$$
* **If $Z = 0$**: The current Dollar Volume is exactly average.
* **If $Z = 1$**: The current Dollar Volume is 1 Standard Deviation above average.
* **If $Z = 4$**: The current Dollar Volume is an extreme outlier.
---
### 4. The "4 StDev" Threshold (Statistical Significance)
Why is $Z \ge 4$ significant? We use the **Empirical Rule** and **Chebyshev’s Inequality** to understand the probability:
| Z-Score | Probability (Normal Dist.) | Frequency of Occurrence |
| --- | --- | --- |
| **1.0** | 68.2% | Common |
| **2.0** | 95.4% | Significant (95th percentile) |
| **3.0** | 99.7% | Rare (The "Three-Sigma" event) |
| **4.0** | **99.993%** | **Extreme Outlier** |
In a perfectly normal distribution, a Z-score of 4 should only happen roughly **once every 15,000 bars**.
> **The Reality of "Fat Tails":** Financial data is not perfectly normal; it has "leptokurtosis" (fat tails). This means 4 StDev events happen more often than 0.01% in trading. When you see $Z > 4$, you aren't seeing random noise; you are seeing a **non-random liquidity shock**—likely institutional block trades or massive delta-hedging rebalancing.
### Why this matters for your 0DTE research:
In 0DTE options, Gamma is at its peak. A $Z > 4$ event in the underlying BMV:PV $ product suggests a sudden burst of activity that can force market makers to hedge aggressively. Since $Z$ is rolling, the "average" adapts to the day's volatility, ensuring that a "spike" in the morning is measured differently than a "spike" during the slow lunch hour.
Indicator

Liquidity Magnet [FEELS]A scoring engine for liquidity zones. Every active pool (swing high,
swing low, or equal-level cluster) gets ranked by probability of being
reached. The highest-probability zone is marked as the top magnet —
the single most likely target right now.
OVERVIEW
Liquidity Magnet is a composite probability scoring system for liquidity zones —
the price levels where resting orders cluster around swing highs, swing lows,
and equal levels. The script ranks every active zone by likelihood of being
reached by price and highlights the single most probable target as the
"top magnet". This is a probabilistic analysis tool, not a predictive signal
generator.
WHAT MAKES IT ORIGINAL
Most existing liquidity tools simply plot pivots or equal highs/lows as static
lines. This script does three things differently:
1. Probability ranking, not binary detection.
Each zone receives a composite score from four independent factors and is
converted into a percentage probability relative to all other active zones.
The result is a relative ranking instead of an undifferentiated list of
levels.
2. Logarithmic distance filtering with timeframe auto-scaling.
Distance to price is measured in log space, which makes the filter
symmetric across price decades. A pool 50% below price has the same
"distance weight" as a pool 50% above. The acceptable distance range
also auto-adjusts to the chart timeframe — weekly charts use a wider
range than 1-minute charts.
3. Transparent track record.
When the top magnet changes, the previous one is recorded and its outcome
tracked over a configurable window. Each historical magnet is marked as
"touched" (price reached it) or "expired" (window passed without reaching).
The dashboard shows the rolling touch rate so users can evaluate the
scoring behavior on the instrument and timeframe they actually trade.
HOW IT WORKS
Liquidity zone detection
The script identifies confirmed swing highs and swing lows using a
configurable pivot lookback. Pivots in the same direction that fall within
a tolerance band are merged into a single "equal liquidity" zone. The
tolerance band auto-scales to timeframe (wider on higher timeframes where
each bar covers more range, narrower on intraday).
Composite probability score
Every active zone receives a raw score combining four weighted components:
- Strength : volume at the pivot bar normalized against a 50-bar volume SMA,
multiplied by a clustering bonus if the zone was formed by merged pivots.
- Proximity : an inverted-U curve over the logarithmic distance to price,
peaking around 2% from current price and decaying symmetrically in both
directions.
- Age : a maturity curve. Very fresh zones are discounted (the market has
not had time to confirm them), mature zones get full weight, and very
old zones decay gradually.
- Momentum : a directional alignment factor. If short-term EMA momentum
points toward a zone, that zone's score is boosted; if momentum points
away, the score is reduced.
All zone scores are then divided by their sum to produce a probability
percentage. The highest-percentage zone is the top magnet.
Magnet Pull direction
The dashboard's Magnet Pull metric reports the direction toward the top
magnet (bullish if the top zone is above price, bearish if below), weighted
by the share of total score on that side. This is a direction indicator,
not a momentum signal.
Pruning
Zones are removed when one of three things happens: price reaches the zone
(swept), the zone exceeds the maximum age in bars, or the zone moves outside
the log-distance filter as price evolves.
HOW TO USE IT
The intended workflow is contextual, not signal-based:
1. Open the chart on your trading timeframe. Auto-scale picks reasonable
defaults for clustering tolerance and distance filter; both can be
overridden manually.
2. Read the dashboard. The top target price and probability give you the
single most likely magnet. The Magnet Pull and Pull Intensity describe
directional bias. The proximity progress bar shows how close price
currently is to the top magnet in log space.
3. Use Top 3 targets for alternatives. The probability gap between rank 1
and ranks 2-3 tells you how dominant the top magnet is. A 40% / 38% /
22% spread is much less decisive than a 60% / 25% / 15% spread.
4. Enable Historical Track to evaluate behavior. Past top magnets are
marked with their outcome on the chart. The rolling Historical Touch %
in the dashboard summarizes the script's recent behavior on the current
instrument and timeframe. This is observational data, not a guarantee.
5. Treat outputs as context, not signals. The script highlights where
liquidity is concentrated and which target the composite model considers
most probable. Trade entries, stop placement, and position sizing remain
the user's responsibility.
PARAMETERS
Pivot Lookback — bars on each side used to confirm a swing point. Higher
values produce fewer but more significant zones.
Equal H/L Tolerance % — clustering threshold. Pivots within this percentage
in the same direction merge into a single zone. Auto-scaled by default.
Log-Distance — maximum allowed distance in log space between price and any
active zone. Auto-scaled by default. Symmetric: covers both above and below
price.
Weight inputs (Strength, Proximity, Age, Momentum) — relative influence of
each scoring component. Default values are calibrated for crypto and equity
intraday/swing usage. Adjusting weights changes the character of the ranking.
Tracking Window (bars) — how long a former top magnet stays "pending" before
being marked as expired.
UI Sizing controls — dashboard position, dashboard text size, zone label
sizes, magnet marker size, historical marker size, all independently
adjustable for personal screen and screenshot preferences.
QUICK START
1. Add the script to any chart
2. Auto-scale handles parameters automatically
3. Look at "Top Target" in the dashboard — that's the most likely magnet
4. Look at "Magnet Pull" — that's the directional bias
5. Turn on "Show Historical Top Magnets" to see past behavior
No setup required. All defaults are calibrated.
TESTED ACROSS
Verified visually on multiple instruments and timeframes:
- Cryptocurrency: BTCUSD, ETHUSD, SOLUSD on 1H to 1W
- Equity indices: NQ, ES on 4H to 1D
- Forex majors: EURUSD, GBPUSD on 1H to 1D
- Commodities: Gold (XAUUSD), Crude Oil on 1D
Auto-scale parameters cover all these instruments and timeframes without
manual tuning. Manual override is available for specific instrument behavior.
NOTES AND LIMITATIONS
- The script is non-repainting on confirmed bars. Pivot detection uses a
fixed forward lookback, which means zones appear after the pivot is
confirmed (lookback bars after the high/low), not in real-time at the
exact bar of the high/low. This is intentional.
- Probability percentages are relative weights inside the active zone set,
not absolute statistical probabilities. They describe the composite
model's ranking, not a calibrated forecast.
- The Historical Touch % is a descriptive statistic over a rolling window.
It reflects observed behavior and does not project future performance.
- Bar Replay is supported: scoring updates on every confirmed bar and
historical markers are placed at the recorded positions, so the chart
behaves consistently when scrubbing through history.
- The script does not generate buy/sell signals. There is no entry/exit
logic, no stop/target output, and no strategy() conversion. It is a
visual analysis tool.
This script is original work. The composite scoring formula, the log-distance
filtering approach, the pool merging algorithm, the directional Magnet Pull
metric, and the historical tracking logic are all custom implementations
written specifically for this script. Indicator

MA200 + RSI Pullback + Hard Close A long-only swing-trading indicator that signals entries when an
uptrending stock pulls back to oversold levels — but only during a
confirmed bullish market regime. Force-exits all signals when SPY
breaks its 200-day MA ("hard close").
═══ RULES ═══
• Entry: Close > MA200 AND RSI(14) < 40 AND SPY > SPY MA200 AND VIX < 30
• Exit : RSI > 70 OR Close < MA200 OR 2×ATR(14) trailing stop
• Hard close: exit ALL signals when SPY < SPY MA200 (regime kill switch)
═══ BACKTEST (499 S&P 500 stocks, 2008–2025, 0.1% commission) ═══
• Sharpe ratio: 1.25
• CAGR: 18.6%
• Max drawdown: -17.2%
• Trades: 1,719
• Win rate: 45.8%
• Avg hold: 18.7 days
═══ WALK-FORWARD VALIDATION ═══
• In-sample (2008–2018) Sharpe: 1.59
• Out-of-sample (2018–2025) Sharpe: 1.11
• IS → OOS degradation: ~30% (acceptable; classic edges often degrade 50%+)
• The hard-close filter cuts max drawdown ~9pp vs. the same strategy
without it — and makes IS/OOS more consistent (less regime-dependent).
═══ HOW TO USE ═══
• Daily timeframe, one ticker at a time (S&P 500 large-caps work best)
• Green triangle below bar = LONG signal
• Red triangle above bar = EXIT signal
• Red background = hard-close regime active (SPY in downtrend)
• Status table top-right = current state at a glance
• Five alert conditions provided (entry, all four exits)
═══ WHY IT WORKS ═══
The MA200 filter avoids catching falling knives. RSI < 40 in an uptrend
catches institutional panic that mean-reverts. The market filter and
hard close prevent participation in broad bear markets where mean-
reversion edges break down (2008, 2020, 2022).
═══ HONEST CAVEATS ═══
• Past performance ≠ future results.
• Backtested with ~10bps round-trip costs; higher costs degrade results.
• This is an INDICATOR, not an auto-executing strategy.
• Tested on US large-caps only. Behavior on small-caps, international,
ETFs, or crypto is untested or shown to underperform.
Not financial advice. Trade your own account. DYOR. Indicator

Indicator

CyberMarketLib# CyberMarketLib v2
CyberMarketLib provides market structure analysis combining swing point detection, Break of Structure (BoS) / Change of Character (CHoCH) identification, session classification, and volatility regime tracking.
## What it does
Delivers four core capabilities: swing point tracking (configurable left/right bar lookback), market structure events (BoS/CHoCH for trend continuation vs reversal), session classification (Asia/London/NY via UTC bucketing), and volatility regimes (LOW/NORMAL/HIGH/EXTREME via ATR percentiles). Build context-aware indicators that adapt to market conditions.
Outputs FractalData structs, StructureEvent/Session/VolRegime enums. All pivots use confirmed swing points (requires right_len bars validation), preventing repainting.
## How it works
Swing detection: `high < high > high `. Stores pivots in SwingHistory circular buffers with automatic capacity management.
BoS/CHoCH follows Smart Money Concepts:
- BOS_UP/DOWN: Price breaks recent swing (trend continuation)
- CHOCH_UP/DOWN: Pivot break after opposite swing (reversal)
Sessions via UTC hours: ASIA (00-08), LONDON (08-13), NY_OVERLAP (13-17), NY_AFTERNOON (17-21), OFF_HOURS (21-24).
Volatility regimes via ATR percentiles (100-bar window): LOW (<25th), NORMAL (25-75th), HIGH (75-90th), EXTREME (>90th).
## Why this is original
Only PulseWire library combining BoS/CHoCH, sessions, and volatility regimes. Existing SMC indicators lack reusable libraries.
Unique features:
- Confirmed pivots only (no repainting)
- CHoCH sequence analysis (pivot pattern detection)
- UTC-based sessions (exchange-agnostic, DST-safe)
- Percentile volatility (asset-adaptive)
- Circular buffer (O(1) operations, memory-efficient)
Designed for composability: sessions → conditional logic, regimes → stop multipliers, BoS/CHoCH → entry/exit signals.
## How to use it
```pine
//@version=6
indicator("CyberMarketLib Demo", overlay=true)
import cybermediaboy/CyberMarketLib/2 as ML
// Swing points + BoS/CHoCH detection
var swing_hist = ML.f_swing_history_new(max_n=20)
var fractal = ML.f_detect_pivot(left_len=5, right_len=5)
if not na(fractal)
swing_hist.push(fractal)
var event = ML.f_detect_structure_event(swing_hist, close)
// event: BOS_UP, BOS_DOWN, CHOCH_UP, CHOCH_DOWN, NONE
// Session + volatility regime
session = ML.f_current_session() // ASIA, LONDON, NY_OVERLAP, etc.
vol_regime = ML.f_volatility_regime(14, 100) // LOW, NORMAL, HIGH, EXTREME
// Adaptive stops
atr = ta.atr(14)
stop_mult = vol_regime == ML.VolRegime.EXTREME ? 3.0 : 1.5
plot(close - atr * stop_mult, "Stop", color.red)
```
## Key functions
- `f_detect_pivot()` - Confirmed swing points (no repainting)
- `f_detect_structure_event()` - BoS/CHoCH detection
- `f_current_session()` - UTC-based session classification
- `f_volatility_regime()` - ATR percentile regimes
- `f_htf_for()` - Higher timeframe string generation
- SwingHistory UDT - Circular buffer for pivot storage
## Limitations
- Swing detection: `right_len` bars confirmation delay (lag vs repainting indicators)
- BoS/CHoCH: Assumes trending markets (false signals in choppy ranges)
- Sessions: UTC-only (no exchange-native or DST-aware sessions)
- Volatility: ATR-based only (may lag on sudden spikes)
- SwingHistory: Fixed capacity at initialization
- CHoCH: Requires manual state tracking to avoid duplicate signals
Library

CyberSignalLib# CyberSignalLib v2
CyberSignalLib provides advanced signal processing tools for Pine Script traders, combining Kalman filtering, entropy-based changepoint detection, and market microstructure analysis in a single dependency.
## What it does
SignalLib delivers three core capabilities: N-dimensional Kalman filters for multi-feature state estimation (price, velocity, z-scores), entropy-based changepoint detectors for regime shifts (NIS, CUSUM, BOCPD), and microstructure metrics for order flow analysis (delta, aggression, volume imbalance). Traders use these tools to build adaptive indicators that respond to market regime changes—for example, a Kalman filter tracking price and volatility simultaneously, with automatic parameter adjustment when a changepoint detector signals a structural break.
The library outputs filtered state estimates (smoothed price, velocity, Mahalanobis distance), changepoint probabilities (0-1 scores indicating regime shift likelihood), and microstructure features (signed delta, aggression ratio, volume-weighted imbalance). All functions support real-time bar-by-bar updates with minimal memory overhead via circular buffers and packed covariance matrices.
## How it works
The Kalman filter implementation uses an N-dimensional state vector with upper-triangular packed covariance storage, reducing memory from O(N²) to O(N(N+1)/2). The filter supports diagonal process noise (Q) and scalar measurement noise (R), both adaptive via innovation tracking. The update step follows the standard predict-correct cycle: predict state using transition matrix F, compute innovation (measurement - prediction), update state and covariance via Kalman gain. Normalized Innovation Squared (NIS) is computed as `innovation² / (H·P·H' + R)` to detect outliers and trigger adaptive R adjustments.
Changepoint detection uses three methods:
1. **NIS-based**: Flags regime change when NIS exceeds a threshold (e.g., 9.0 for 99% confidence under chi-squared distribution)
2. **CUSUM**: Cumulative sum of log-likelihood ratios, resets when crossing upper/lower bounds
3. **BOCPD (Bayesian Online Changepoint Detection)**: Maintains run-length distribution, computes changepoint probability via hazard function
Entropy calculations support four modes: binary (up/down), ternary (up/flat/down), combo (binary + ternary), and composite (weighted average). Shannon entropy is computed as `-Σ p_i log₂(p_i)` where p_i are empirical frequencies over a rolling window. High entropy (near maximum) indicates unpredictable price action; low entropy signals trending or mean-reverting regimes.
Microstructure metrics derive from tick-level order flow:
- **Delta**: Signed volume (buy volume - sell volume)
- **Aggression**: Ratio of aggressive orders (market orders) to total volume
- **Imbalance**: `(buy_vol - sell_vol) / (buy_vol + sell_vol)`, range
These metrics are computed via request.security calls to lower timeframes (1-minute typical) and aggregated to the chart timeframe.
## Why this is original
CyberSignalLib is the only PulseWire library combining Kalman filtering, changepoint detection, and microstructure analysis in a unified interface. Existing Kalman filter libraries are limited to 1D or 2D state spaces and lack adaptive noise parameters. No public library offers BOCPD or CUSUM changepoint detection. Microstructure metrics typically require manual request.security calls with hardcoded timeframes—SignalLib abstracts this into reusable functions with configurable lookback windows.
Unique features:
- **Tri-packed covariance**: Memory-efficient N-dimensional Kalman filter (supports up to 16 features on PulseWire's memory limits)
- **Adaptive Q/R**: Automatic process/measurement noise tuning based on innovation statistics, eliminating manual parameter tweaking
- **Trajectory store**: Circular buffer for Kalman state history, enabling lookback analysis (e.g., "was price above Kalman estimate 5 bars ago?")
- **Mahalanobis distance**: 3D analytic formula with shrinkage regularization for outlier detection in multi-feature space
- **Unified changepoint API**: Single enum-based interface for NIS/CUSUM/BOCPD, simplifying regime-switching indicator logic
No other Pine library provides this combination of statistical rigor (Kalman optimality, Bayesian changepoint inference) and practical usability (adaptive parameters, memory-efficient storage, microstructure integration).
## How to use it
```pine
//@version=6
indicator("CyberSignalLib Demo", overlay=true)
import cybermediaboy/CyberSignalLib/2 as SL
import cybermediaboy/NumLib/5 as N
// Example 1: 2D Kalman filter (price + velocity)
var kal = SL.f_kalman_init(nfeat=2, P0=1.0, Q0=0.01, R0=0.1, innov_window=20)
if not na(close)
kal.update_scalar(0, close, 1.0) // Measure price (feature 0)
kal.predict(SL.f_transition_identity(2))
kal.adapt_Q(Q_min=0.001, Q_max=0.1, gain=1.5)
kal.adapt_R(high_thresh=9.0, low_thresh=1.0, R_step=0.1)
float price_est = array.get(kal.x, 0)
float velocity_est = array.get(kal.x, 1)
plot(price_est, "Kalman Price", color.blue, linewidth=2)
plot(close + velocity_est * 10, "Velocity Offset", color.orange)
// Example 2: NIS-based changepoint detection
bool changepoint = kal.lastnis > 9.0 // 99% confidence threshold
bgcolor(changepoint ? color.new(color.red, 80) : na, title="Regime Change")
// Example 3: Entropy calculation (ternary mode)
var ent_buf = array.new(50, 0)
int direction = close > close ? 1 : (close < close ? -1 : 0)
array.push(ent_buf, direction)
if array.size(ent_buf) > 50
array.shift(ent_buf)
float entropy = SL.f_entropy_ternary(ent_buf)
plot(entropy, "Ternary Entropy", color.green)
// Example 4: Mahalanobis distance (3D outlier detection)
var z_vec = array.from(close, volume, ta.rsi(close, 14))
var mu_vec = array.from(ta.sma(close, 50), ta.sma(volume, 50), 50.0)
var cov_tri = array.from(1.0, 0.0, 0.0, 1.0, 0.0, 1.0) // Identity covariance
float maha = SL.f_mahalanobis_3d(z_vec, mu_vec, cov_tri, shrinkage=0.1)
plot(maha, "Mahalanobis Distance", color.purple)
```
## Inputs, outputs, expected behavior
**Kalman filter** (`f_kalman_init`, `update_scalar`, `predict`):
- **Inputs**: `nfeat` (int, 1-16 typical), `P0/Q0/R0` (float, initial noise estimates), `measurement` (float), `H` (float, observation matrix row)
- **Outputs**: Updated state vector `x` (array), NIS value `lastnis` (float, unbounded), ready flag `ready` (bool)
- **Edge cases**: Returns unmodified state if measurement is NA, requires ≥20 bars for adaptive Q/R to stabilize
**Changepoint detection** (`f_changepoint_nis`, `f_changepoint_cusum`, `f_changepoint_bocpd`):
- **Inputs**: `nis` (float, typically from Kalman filter), `threshold` (float, 9.0 for 99% confidence), `hazard` (float, 0.01-0.1 for BOCPD)
- **Outputs**: Changepoint probability (float, ) or binary flag (bool)
- **Edge cases**: CUSUM resets on boundary crossing, BOCPD requires ≥10 bars for stable run-length distribution
**Entropy functions** (`f_entropy_binary`, `f_entropy_ternary`, `f_entropy_combo`):
- **Inputs**: `data` (array, direction codes: -1/0/1), `window` (int, 20-100 typical)
- **Outputs**: Shannon entropy (float, ), max entropy = 1.0 for binary, 1.585 for ternary
- **Edge cases**: Returns 0.0 if all elements identical, handles empty arrays gracefully
**Microstructure metrics** (`f_get_micro_state`, `f_get_scientific_delta`, `f_get_aggregated_volume`):
- **Inputs**: `timeframe` (string, "1" for 1-minute), `lookback` (int, bars to aggregate)
- **Outputs**: Delta (float, signed volume), aggression (float, ), imbalance (float, )
- **Edge cases**: Returns NA if lower timeframe data unavailable, requires Premium/Pro account for intraday request.security
**Trajectory store** (`f_trajectory_new`, `push`, `read`):
- **Inputs**: `snap_dim` (int, state vector length), `capacity` (int, max snapshots), `offset` (int, 0=latest)
- **Outputs**: Snapshot array (array, length `snap_dim`)
- **Edge cases**: Returns NA-filled array if offset exceeds filled count, circular overwrite after capacity reached
## Limitations
1. **Kalman filter assumes linear dynamics**: The transition matrix F is diagonal (no cross-feature coupling). For non-linear systems (e.g., price-volatility feedback loops), the filter may diverge. Extended Kalman Filter (EKF) or Unscented Kalman Filter (UKF) variants are not implemented.
2. **Changepoint detection requires tuning**: NIS threshold (default 9.0) assumes Gaussian measurement noise. In heavy-tailed distributions (crypto, low-liquidity assets), false positives increase. CUSUM and BOCPD require manual hazard/boundary tuning per asset and timeframe.
3. **Microstructure functions require lower timeframe data**: `f_get_micro_state` and related functions call request.security with `timeframe="1"` (1-minute). This fails on daily/weekly charts or for symbols without intraday data. Users must handle NA returns or pre-filter symbols.
4. **Memory overhead for high-dimensional Kalman**: An N=16 feature Kalman filter requires 136 floats for packed covariance (16×17/2) plus state vector. On PulseWire's 50,000 float limit per script, this restricts other arrays. Reduce `nfeat` or use sparse feature selection.
5. **Entropy calculations assume discrete states**: Binary/ternary entropy requires pre-discretized input (direction codes -1/0/1). Continuous price data must be manually binned. The library does not auto-discretize or suggest bin counts.
6. **No multi-step prediction**: The Kalman filter supports one-step-ahead prediction only. For multi-bar forecasts (e.g., "predict price 5 bars ahead"), users must manually iterate the predict step, which compounds uncertainty without re-measurement.
7. **Adaptive Q/R convergence time**: Adaptive noise parameters require 20-50 bars to stabilize after initialization or regime change. During this period, filter estimates may be suboptimal. Consider using fixed Q/R for the first 50 bars, then enabling adaptation.
Library

CyberLearningLib# CyberLearningLib v4
CyberLearningLib provides online learning primitives for Pine Script traders building adaptive machine learning indicators, including circular training buffers, feature scaling, stochastic gradient descent (SGD), and distance metrics for k-nearest neighbors (kNN) algorithms.
## What it does
LearningLib delivers four core components: circular training buffers for memory-efficient sample storage (O(1) push/read), feature scalers with exponentially weighted moving average (EWMA) normalization, SGD optimizers with gradient clipping and multiple loss functions (squared, hinge, logistic, Huber), and distance metrics for kNN classification (Euclidean, Manhattan, Cosine, Mahalanobis, Chebyshev). Traders use these tools to build indicators that learn from historical price patterns—for example, a kNN classifier predicting next-bar direction based on the 10 most similar historical setups, with features auto-scaled via EWMA to handle non-stationary markets.
The library outputs trained model weights (SGD state vector), scaled feature vectors (normalized to or z-scores), distance matrices for kNN queries, and sample metadata (timestamp, sample type, trade direction). All data structures use circular buffers to maintain constant memory usage regardless of training duration, critical for long-running indicators on PulseWire's 50,000 float limit.
## How it works
The training buffer uses a circular array with write-head indexing: when capacity is reached, new samples overwrite the oldest. Each sample stores a feature vector (array), label (float, regression target or {-1,+1} for classification), weight (float, for importance sampling), timestamp (bar_index), sample type (enum: LIVE/SIMULATED/SHADOW/BACKFILL), trade direction (LONG/SHORT/FLAT), and two free metadata integers for custom categorization. The `read(offset)` method retrieves samples in reverse chronological order (0 = most recent), while `read_chrono(pos)` accesses samples in insertion order (0 = oldest).
Feature scaling supports three methods:
1. **EWMA normalization**: Maintains running mean/variance via `μ_t = (1-α)μ_{t-1} + αx_t`, scales features to z-scores
2. **Min-max scaling**: Tracks rolling min/max over window, normalizes to
3. **Percentile-based**: Uses IQR (interquartile range) for outlier-resistant scaling
SGD updates follow the standard formula `w_t = w_{t-1} - η∇L(w)` where η is learning rate and ∇L is loss gradient. Supported loss functions:
- **Squared**: `0.5(y - ŷ)²`, gradient = `-(y - ŷ)`
- **Hinge**: `max(0, 1 - y·ŷ)` for y ∈ {-1,+1}, gradient = `-y` if margin violated
- **Logistic**: `log(1 + exp(-y·ŷ))`, gradient = `-y / (1 + exp(y·ŷ))`
- **Huber**: Squared loss for small errors (|err| ≤ δ), linear for large errors (robust to outliers)
Gradient clipping prevents exploding gradients: `g_clipped = g / max(1, ||g|| / threshold)`. The library also provides gated SGD updates that skip parameter changes when innovation (measurement error) is below a threshold, reducing overfitting to noise.
Distance metrics compute similarity between feature vectors for kNN:
- **Euclidean**: `√Σ(x_i - y_i)²`
- **Manhattan**: `Σ|x_i - y_i|`
- **Cosine**: `1 - (x·y) / (||x|| ||y||)` (angle-based, scale-invariant)
- **Mahalanobis**: `√((x-y)'Σ⁻¹(x-y))` where Σ is covariance (accounts for feature correlations)
- **Chebyshev**: `max_i |x_i - y_i|` (L∞ norm)
## Why this is original
CyberLearningLib is the only PulseWire library providing a complete online learning toolkit with memory-efficient circular buffers and production-ready SGD implementations. Existing ML libraries either use linear arrays (memory grows unbounded), lack feature scaling (assume stationary data), or implement only Euclidean distance (ignoring feature correlations).
Unique features:
- **Circular training buffers**: O(1) push/read with constant memory, critical for indicators running 24/7 on crypto markets. No other Pine library offers circular indexing with chronological/reverse-chronological access.
- **Sample type tracking**: LIVE/SIMULATED/SHADOW/BACKFILL enum enables mixed training sets (e.g., "train on LIVE samples only, use SIMULATED for validation"). Essential for walk-forward optimization and out-of-sample testing.
- **Gated SGD updates**: Skip weight updates when innovation < threshold, preventing overfitting during low-volatility regimes. Based on Kalman filter innovation gating, not found in standard ML libraries.
- **Huber loss with configurable δ**: Robust regression loss that transitions from squared (δ-sensitive) to linear (outlier-resistant). Most Pine implementations use fixed δ=1.0; this library exposes δ as parameter.
- **Mahalanobis distance with shrinkage**: Accounts for feature correlations via inverse covariance, with Ledoit-Wolf shrinkage to prevent singular matrix errors. No other Pine library implements this (most use Euclidean only).
The library is designed for composition: training buffers feed into feature scalers, scaled features feed into SGD or kNN, distances feed into weighted voting. This modular design enables complex workflows (e.g., "scale features via EWMA, train linear SVM via hinge loss, classify new samples via kNN with Mahalanobis distance") without code duplication.
## How to use it
```pine
//@version=6
indicator("CyberLearningLib Demo", overlay=false)
import cybermediaboy/CyberLearningLib/4 as LL
import cybermediaboy/NumLib/5 as N
// Example 1: Circular training buffer
var tb = LL.f_buffer_new(capacity=100, nfeat=3)
if not na(close)
var features = array.from(ta.rsi(close, 14), ta.atr(14), volume)
float label = close < close ? 1.0 : -1.0 // Next-bar direction
var sample = LL.f_sample_new(features, label, LL.SampleType.LIVE,
LL.TradeDirection.LONG, meta_a=0, meta_b=0)
tb.push(sample)
// Read most recent sample
var recent = tb.read(0)
if not na(recent)
plot(recent.label, "Last Label", color.blue)
// Example 2: Feature scaling (EWMA)
var scaler = LL.f_scaler_new(nfeat=3, alpha=0.1)
if not na(close)
var raw_features = array.from(close, volume, ta.rsi(close, 14))
var scaled = scaler.scale(raw_features)
plot(array.get(scaled, 0), "Scaled Close", color.orange)
// Example 3: SGD training (hinge loss for binary classification)
var sgd = LL.f_sgd_new(nfeat=3, learning_rate=0.01, loss=LL.LossKind.HINGE)
if tb.filled >= 10
var train_sample = tb.read(0)
if not na(train_sample)
sgd.update(train_sample.features, train_sample.label, clip_threshold=5.0)
float prediction = sgd.predict(train_sample.features)
plot(prediction, "SGD Prediction", color.green)
// Example 4: kNN distance calculation
if tb.filled >= 2
var s1 = tb.read(0)
var s2 = tb.read(1)
if not na(s1) and not na(s2)
float dist_euclidean = LL.f_distance(s1.features, s2.features, LL.DistanceKind.EUCLIDEAN)
float dist_cosine = LL.f_distance(s1.features, s2.features, LL.DistanceKind.COSINE)
plot(dist_euclidean, "Euclidean Dist", color.red)
plot(dist_cosine, "Cosine Dist", color.purple)
```
## Inputs, outputs, expected behavior
**Training buffer** (`f_buffer_new`, `push`, `read`, `read_chrono`):
- **Inputs**: `capacity` (int, 50-1000 typical), `nfeat` (int, feature dimension), `offset/pos` (int, sample index)
- **Outputs**: TBSample (struct with features, label, metadata) or na if index out of bounds
- **Edge cases**: Returns na for invalid offsets, overwrites oldest sample at capacity, `filled` count saturates at capacity
**Feature scaler** (`f_scaler_new`, `scale`, `update`):
- **Inputs**: `nfeat` (int), `alpha` (float, EWMA decay 0.01-0.3 typical), `features` (array)
- **Outputs**: Scaled feature vector (array, z-scores or normalized)
- **Edge cases**: Returns unscaled features on first call (no history), handles NA elements via nz()
**SGD optimizer** (`f_sgd_new`, `update`, `predict`):
- **Inputs**: `nfeat` (int), `learning_rate` (float, 0.001-0.1 typical), `loss` (enum), `features/label` (float), `clip_threshold` (float, 1.0-10.0)
- **Outputs**: Prediction (float, unbounded for regression, {-1,+1} for classification after sign()), updated weights (internal state)
- **Edge cases**: Gradient clipping prevents exploding weights, returns 0.0 prediction before first update
**Distance metrics** (`f_distance`, `f_distance_mahalanobis`):
- **Inputs**: `x/y` (array, same length), `kind` (enum), `cov_inv` (array, tri-packed inverse covariance for Mahalanobis)
- **Outputs**: Distance (float, ≥0 for Euclidean/Manhattan/Chebyshev, for Cosine, unbounded for Mahalanobis)
- **Edge cases**: Returns NA if array lengths mismatch, Mahalanobis requires non-singular covariance (use shrinkage if needed)
**Sample filtering** (`by_type`, `by_direction`):
- **Inputs**: `tb` (TrainingBuffer), `st` (SampleType enum), `dir` (TradeDirection enum)
- **Outputs**: Filtered array (subset of buffer matching criteria)
- **Edge cases**: Returns empty array if no matches, preserves chronological order
## Limitations
1. **Fixed feature dimension**: Training buffers and scalers require `nfeat` declared at initialization. Changing feature count mid-stream requires creating a new buffer/scaler. Dynamic feature sets (e.g., "use 3 features on stocks, 5 on crypto") are not supported.
2. **No automatic hyperparameter tuning**: Learning rate, loss function, gradient clip threshold, and EWMA alpha must be manually specified. The library does not provide grid search, cross-validation, or adaptive learning rate schedules (e.g., Adam, RMSprop). Users must tune via backtesting.
3. **SGD assumes i.i.d. samples**: Stochastic gradient descent converges optimally when samples are independent and identically distributed. Financial time series violate this (autocorrelation, regime changes). For non-stationary data, consider using gated updates or periodically resetting weights.
4. **Mahalanobis distance requires covariance matrix**: Computing inverse covariance for N features requires O(N³) operations and N(N+1)/2 storage. For high-dimensional features (N > 10), this becomes computationally expensive. Use Euclidean or Cosine distance for N > 10, or apply PCA to reduce dimensionality first.
5. **No mini-batch SGD**: The library implements single-sample (online) SGD only. Mini-batch updates (averaging gradients over K samples) are not supported. For noisy gradients, increase EWMA alpha in feature scaling or use Huber loss instead of squared loss.
6. **Circular buffer overwrites without warning**: When capacity is reached, `push()` silently overwrites the oldest sample. If you need to preserve all historical data, implement external archiving (e.g., export to CSV via log.info) before buffer fills.
7. **Distance metrics do not handle missing features**: If a feature vector contains NA, distance functions return NA. The library does not impute missing values (mean, median, forward-fill). Users must handle NA via nz() or filtering before calling distance functions.
Library

CyberCausalityLib# CyberCausalityLib v17
CyberCausalityLib provides information-theoretic and econometric causality detection for identifying directional influence between price series, filtering spurious correlations, and detecting lead-lag relationships across assets.
## What it does
Delivers 15+ causality functions in three categories: Transfer Entropy (information-theoretic directional causality), Granger Causality (econometric lagged correlation), and PCMCI filtering (partial correlation mediation for spurious causality detection). Answers questions like "Does Bitcoin volume predict Ethereum price?" and "Is Asset A→B correlation direct or mediated by Asset C?"
Outputs causality scores, directional indicators, and optimal lag values for multi-basket aggregation, lead-lag pair trading, and filtering false correlations driven by common factors.
## How it works
Transfer Entropy measures directional information flow: `TE(X→Y) = H(Y_t | Y_{t-1}) - H(Y_t | Y_{t-1}, X_{t-lag})` using Shannon entropy. Discretizes price data into 4-8 bins, calculates joint/conditional entropies. Higher TE = X predicts future Y beyond Y's own history.
Granger Causality aggregates lagged correlations: `Granger = Σ(w_i × corr(Y_t, X_{t-i}))` with weights `w_i = |corr_i| / Σ|corr_j|`. Supports Pearson/Spearman/Kendall. Returns magnitude + directional coefficient.
PCMCI filtering detects spurious causality via partial correlation: `ρ(X,Y|Z)`. If partial << raw correlation, Z mediates X→Y (indirect causality). Reduces score proportionally.
## Why this is original
First PulseWire library with information-theoretic causality. Pine has no native entropy, Granger tests, or partial correlation. Existing libraries offer only basic correlation without directionality or lag optimization.
Unique features:
- Transfer Entropy with Shannon entropy discretization
- Granger Causality with auto-lag search (1-10)
- PCMCI filtering (up to 4 mediators)
- Ensemble aggregation (5 baskets)
- Möbius transformation state tracking
No other Pine library combines information theory, econometrics, and graph-based causality with NA guards and graceful degradation.
## How to use it
```pine
//@version=6
indicator("CyberCausalityLib Demo", overlay=false)
import cybermediaboy/CyberCausalityLib/17 as C
import cybermediaboy/NumLib/4 as N
// Transfer Entropy: Does volume predict price?
var price_buf = array.new()
var vol_buf = array.new()
if bar_index >= 99
array.clear(price_buf)
array.clear(vol_buf)
for i = 0 to 99
array.push(price_buf, close )
array.push(vol_buf, volume )
= C.f_calculate_te_score_v2(
price_buf, vol_buf, 100, 5, 2
)
// te_score > 0.15 → volume predicts price
plot(te_score, "TE Score", color.blue)
// Granger Causality: Lead-lag detection
var x_buf = array.new()
var y_buf = array.new()
// ...populate buffers...
= C.f_calculate_granger_score(
y_buf, x_buf, 100, 5, "Pearson"
)
// granger > 0.3 → X Granger-causes Y
// PCMCI Filtering: Remove spurious correlation
= C.f_calculate_granger_score(y_buf, x_buf, 100, 5, "Pearson")
filtered = C.f_pcmci_filter_score(
raw, y_buf, x_buf, mediator_buf,
array.new(), array.new(), array.new(), 100
)
// filtered << raw → indirect causality
```
## Key functions
- `f_calculate_te_score_v2()` - Transfer Entropy (recommended)
- `f_calculate_granger_score()` - Granger Causality with lag search
- `f_pcmci_filter_score()` - Spurious correlation filtering
- `f_compute_te_ensemble()` - Multi-basket aggregation
- `f_shannon_entropy()` - Shannon entropy calculation
- `MobiusState` UDT - Non-linear state tracking
## Dependencies
Requires NumLib v4 for correlation functions (Pearson/Spearman/Kendall).
```pine
import cybermediaboy/CyberCausalityLib/17 as C
import cybermediaboy/NumLib/4 as N
```
## Version history
- **v17** (2026-04-17): Added HAR-RV forecast, Durbin-Watson autocorrelation test, PCA explained variance, improved entropy discretization (v2 algorithm)
- **v16** (2026-03-xx): Added PCMCI filtering, Möbius state tracking UDT
- **v15** (2026-02-xx): Added Granger causality, multi-lag search, correlation at lag
- **v14** (2026-01-xx): Initial release with Transfer Entropy, ensemble aggregation
## License
Mozilla Public License 2.0
## Author
© cybermediaboy
## Support
For questions, bug reports, or feature requests, comment on the library publication page or reference the source code documentation.
Library

CyberNumLib# CyberNumLib v5
CyberNumLib provides stateless numerical primitives for Pine Script traders who need advanced statistical calculations, robust normalization methods, and mathematical functions not available in PulseWire's native library.
## What it does
NumLib delivers 56 pure functions covering five categories: mathematical polyfills (hyperbolic functions, normal distribution CDF/inverse, error function), advanced smoothing filters (Ehlers Super Smoother, Butterworth, Savitzky-Golay), robust statistics (median-MAD, IQR-based scaling, Winsorized bounds), normalization methods (z-scores, percentile ranks, min-max scaling), and correlation analysis (Pearson, Spearman, Kendall, Hurst exponent). Traders use these functions to build custom indicators requiring statistical rigor beyond Pine's built-in ta.* namespace—for example, calculating confidence intervals from normal quantiles, applying outlier-resistant smoothing to noisy price data, or measuring non-linear correlation between assets.
The library outputs standardized numerical values ready for downstream indicator logic: z-scores for mean-reversion signals, normalized coefficients for ML feature engineering, correlation matrices for multi-asset analysis, and smoothed series for trend detection. All functions are stateless (no internal state variables), making them composable and predictable across different timeframes and symbols.
## How it works
NumLib implements well-documented statistical algorithms with explicit citations. The normal CDF uses the Abramowitz & Stegun 26.2.17 polynomial approximation (max error ~7e-8), while the inverse normal CDF employs the Beasley-Springer-Moro rational approximation for converting probabilities to z-scores with ~1e-10 precision—critical for quantile-based risk calculations. Hyperbolic tangent (tanh) is computed via the numerically stable identity `(e^(2x) - 1) / (e^(2x) + 1)` with argument clamping to ±20 to prevent math.exp overflow.
Smoothing filters follow Ehlers' DSP methodology: the Super Smoother is a 2-pole IIR Butterworth-equivalent with coefficients derived from `exp(-1.414π/len)`, providing lag reduction vs simple moving averages while suppressing high-frequency noise. The Savitzky-Golay filter uses fixed polynomial coefficients (order 2, length 13) for edge-preserving smoothing without phase shift.
Robust statistics leverage percentile-based methods resistant to outliers. The median-MAD estimator computes scale as `(Q75 - Q25) / 0.7413`, where 0.7413 is the IQR-to-standard-deviation conversion factor for normal distributions. Correlation functions implement textbook formulas: Pearson via covariance normalization, Spearman via rank transformation, Kendall via concordant-discordant pair counting. The Hurst exponent uses rescaled range (R/S) analysis to detect mean-reversion (H < 0.5) vs trending (H > 0.5) regimes.
## Why this is original
NumLib fills critical gaps in Pine Script's native math library. PulseWire provides no hyperbolic functions (tanh, sinh, cosh), no normal distribution quantile functions, no Savitzky-Golay smoothing, and no robust statistics beyond basic percentiles. Existing public libraries either bundle these functions with unrelated indicator logic (mixing calculation with rendering) or implement simplified versions without numerical stability guards.
This library is the only PulseWire publication offering:
- **Numerically stable implementations**: tanh with overflow clamping, normal CDF with Abramowitz-Stegun precision, inverse CDF with Beasley-Springer-Moro accuracy
- **Robust statistics suite**: median-MAD, IQR normalization, Winsorization—essential for outlier-resistant indicators in volatile markets
- **Ehlers DSP filters**: Super Smoother and Butterworth implementations with exact coefficient formulas from Ehlers' published work
- **Comprehensive correlation toolkit**: Pearson, Spearman, Kendall, plus Hurst exponent for regime detection—all in one dependency-free library
No other Pine library combines these four categories with explicit algorithm citations and edge-case handling (NA guards, zero-division checks, warmup period validation).
## How to use it
```pine
//@version=6
indicator("CyberNumLib Demo", overlay=false)
import cybermediaboy/CyberNumLib/5 as N
// Example 1: Z-score with robust median-MAD scaling
= N.f_basis_median_mad(close, 50)
plot(z_robust, "Robust Z-Score", color.blue)
// Example 2: Smooth price with Ehlers Super Smoother
smooth_close = N.f_supersmoother(close, 20)
plot(smooth_close, "Super Smooth", color.orange)
// Example 3: Calculate correlation between two assets
// (Assumes you have arrays x_data and y_data populated)
var x_arr = array.new(50)
var y_arr = array.new(50)
array.push(x_arr, close)
array.push(y_arr, volume)
if array.size(x_arr) > 50
array.shift(x_arr)
array.shift(y_arr)
corr_pearson = N.f_pearson(x_arr, y_arr, 50)
plot(corr_pearson, "Pearson Correlation", color.green)
// Example 4: Convert confidence level to z-score
conf_95 = 0.95
z_95 = N.f_norm_inv((1.0 + conf_95) / 2.0) // Returns ~1.96
plot(z_95, "95% Confidence Z", color.red)
```
## Inputs, outputs, expected behavior
**Smoothing functions** (`f_supersmoother`, `f_buttersmooth`, `f_savgol_2_13`):
- **Inputs**: `src` (float, typically close/high/low), `len` (int, window size 5-100 typical)
- **Outputs**: Smoothed float value, range matches input series
- **Edge cases**: Returns input value on first bar (no warmup), handles NA via nz()
**Statistical functions** (`f_zscore`, `f_basis_median_mad`, `f_percentile_bands`):
- **Inputs**: `src` (float series), `len` (int, minimum 10 for stability)
- **Outputs**: Z-scores (unbounded float), percentiles (price units), scale factors (positive float)
- **Edge cases**: Returns 0.0 for z-score if stdev = 0, returns NA for insufficient data (bar_index < len)
**Correlation functions** (`f_pearson`, `f_spearman`, `f_kendall`, `f_hurst_rs`):
- **Inputs**: `array` (length ≥ 10), `len` (int, sample size)
- **Outputs**: Correlation coefficient for Pearson/Spearman/Kendall, Hurst
- **Edge cases**: Returns 0.0 if array size < len, handles NA elements via filtering
**Math polyfills** (`f_tanh`, `f_norm_cdf`, `f_norm_inv`, `f_erf`):
- **Inputs**: Float values (unbounded for tanh/erf, for norm_inv, any for norm_cdf)
- **Outputs**: Bounded floats (tanh: , sigmoid: , norm_cdf: , norm_inv: unbounded)
- **Edge cases**: Clamps extreme inputs to prevent overflow (tanh at ±20, norm_inv at )
**Normalization functions** (`f_normalize`, `f_iqr_normalize`, `f_tanh_norm`):
- **Inputs**: `value` (float), `minval/maxval` (float bounds) or `len` (int window)
- **Outputs**: Normalized float in for f_normalize, for tanh-based methods
- **Edge cases**: Returns 0.0 if range is zero, handles NA inputs gracefully
## Limitations
1. **No dynamic array sizing**: Correlation functions require pre-allocated arrays of fixed size. If your data stream length varies, you must manage array resizing externally (e.g., via array.push + array.shift pattern). The library does not auto-resize or buffer data.
2. **Warmup period required**: Statistical functions (z-score, percentile bands, correlation) return unreliable values during the first `len` bars. Indicators using NumLib should display a warmup warning (e.g., "Insufficient data: need 50 bars") or gate signals until `bar_index >= len`.
3. **Precision limits on extreme inputs**: Math polyfills use polynomial approximations with documented error bounds (e.g., normal CDF ~7e-8, erf ~1.5e-7). For applications requiring higher precision (e.g., options pricing), these approximations may be insufficient. Extreme inputs (|x| > 20 for tanh, p < 1e-10 for norm_inv) are clamped to prevent overflow, which can distort tail probabilities.
4. **Correlation functions assume stationarity**: Pearson, Spearman, and Kendall correlations are computed over rolling windows without detrending. In strongly trending markets, these measures may overstate correlation due to common trend components. For non-stationary data, consider differencing the series first or using Hurst exponent to detect regime changes.
5. **No built-in significance testing**: The library returns raw correlation coefficients without p-values or confidence intervals. Traders must implement their own significance tests (e.g., t-test for Pearson correlation) or use rule-of-thumb thresholds (|r| > 0.7 for strong correlation).
6. **Single-threaded execution**: All functions execute sequentially on each bar. For indicators calling multiple NumLib functions per bar (e.g., computing 10 correlations), execution time may exceed PulseWire's script timeout on lower timeframes with large datasets. Optimize by caching results or reducing calculation frequency.
Library

CyberAssetLib# CyberAssetLib v2
CyberAssetLib provides a typed asset registry for Pine Script traders managing multi-asset indicators, offering centralized metadata for asset classes, trading hours, parent blockchains, and venue selection across spot, perpetual, and futures markets.
## What it does
CyberAssetLib delivers a single source of truth for asset metadata, replacing scattered hardcoded lookups with a structured registry. Traders use this library to build cross-asset indicators that adapt behavior based on asset type—for example, applying different volatility filters to 24/7 crypto vs 9:30-16:00 US equities, or aggregating volume across multiple venues (Binance spot + Coinbase + CME futures) with liquidity-tier weighting. The library supports symbol aliasing (e.g., "BINANCE:BTCUSDT" → "BTC"), parent chain lookups (e.g., "MATIC" → "ETH" for Polygon), and venue filtering by kind (spot/perp/fut) and liquidity tier (T1/T2/T3).
The library outputs AssetRecord structs containing asset class (CRYPTO_MAIN, ALTS, SHARES, COMMODITY, INDEX, FX), trading hours regime (24x7, 23x5, EU, US), parent chain symbol, and arrays of Venue objects with exchange, ticker, kind, and tier. Traders query the registry via canonical symbol ("BTC") or full ticker alias ("BINANCE:BTCUSDT"), receiving structured metadata for downstream logic (e.g., "if asset.hours == H_24X7, disable session filters").
## How it works
The registry uses two hash maps: `bysymbol` (canonical symbol → AssetRecord) and `byalias` (full ticker → canonical symbol). Initialization populates these maps with hardcoded entries for major assets (BTC, ETH, SOL, SPX, GOLD, etc.). The `byalias` map enables O(1) ticker normalization: "BINANCE:BTCUSDT" → "BTC", eliminating 66-iteration if-else chains from prior implementations.
Each AssetRecord stores:
- **symbol**: Canonical key (e.g., "BTC")
- **cls**: AssetClass enum (CRYPTO_MAIN, ALTS, SHARES, COMMODITY, INDEX, FX)
- **subtype**: Fine-grained label (e.g., "bitcoin", "sp500-fut", "natgas-cfd")
- **chain**: Parent L1 blockchain symbol (e.g., "ETH" for MATIC, "SOL" for BONK)
- **isl1**: Boolean flag (true if asset IS its own chain, e.g., BTC, ETH, SOL)
- **hours**: TradingHours enum (H_24X7 for crypto, H_US for NYSE, H_EU for DAX)
- **venues**: Array of Venue objects (spot, perp, fut combined)
- **aliases**: Array of full ticker strings for byalias map population
Venue objects contain:
- **ticker**: Full PulseWire ticker (e.g., "BINANCE:BTCUSDT")
- **kind**: VenueKind enum (SPOT, PERP, FUT)
- **exchange**: Exchange name (e.g., "BINANCE", "CME")
- **tier**: LiquidityTier enum (T1 for Binance/Coinbase/CME, T2 for OKX/Bybit, T3 for others)
The `f_build_venue` function auto-detects venue kind from ticker patterns: ".P" or "PERP" → PERP, "1!" or "FUT" → FUT, else SPOT. Exchange is extracted via string split on ":".
Volume aggregation uses AggregationPolicy to filter venues: `include_spot/perp/fut` (booleans), `max_tier` (1=T1 only, 3=all), `max_venues` (cap on returned venues). The VolumeAggregator struct stores selected venues with normalized weights (e.g., T1 venues get 2x weight vs T2).
## Why this is original
CyberAssetLib is the only PulseWire library providing a typed, enum-based asset registry with multi-venue support. Existing solutions use hardcoded if-else chains (unmaintainable for 100+ assets), string-based classification (error-prone, no type safety), or single-venue assumptions (ignore liquidity fragmentation across exchanges).
Unique features:
- **Enum-typed fields**: AssetClass, TradingHours, VenueKind, LiquidityTier are frozen enums (backward-compatible with kNN integer casts), preventing typos and enabling exhaustive switch statements
- **Parent chain tracking**: `chain` field links L2 tokens to L1 blockchains (e.g., MATIC → ETH), enabling cross-chain correlation analysis
- **Multi-venue aggregation**: Single asset can have 10+ venues (Binance spot, Coinbase, Kraken, CME futures, Bybit perp), with policy-based filtering and liquidity-tier weighting
- **Alias normalization**: O(1) ticker → canonical symbol lookup (e.g., "BINANCE:BTCUSDT" → "BTC"), eliminating regex parsing or 66-iteration if-else chains
- **Trading hours metadata**: Enables session-aware indicators (e.g., "disable mean-reversion signals during US market close for equities, but keep active for 24/7 crypto")
The library is designed for extensibility: adding a new asset requires one AssetRecord entry, not scattered updates across multiple functions. Enum ordering is frozen (P11 convention) to ensure backward compatibility with indicators that serialize enum values to integers for kNN training data.
## How to use it
```pine
//@version=6
indicator("CyberAssetLib Demo", overlay=false)
import cybermediaboy/CyberAssetLib/2 as AL
// Example 1: Initialize registry and lookup asset by symbol
var reg = AL.f_registry_new()
AL.f_registry_init(reg) // Populate with default assets
var btc = reg.bysymbol.get("BTC")
if not na(btc)
label.new(bar_index, high, "BTC Class: " + str.tostring(btc.cls),
color=color.blue, textcolor=color.white)
// Example 2: Normalize ticker to canonical symbol
string current_ticker = syminfo.tickerid
string canonical = reg.byalias.get(current_ticker)
if not na(canonical)
label.new(bar_index, low, "Canonical: " + canonical,
color=color.orange, textcolor=color.white)
// Example 3: Filter venues by kind (get all perpetual venues for BTC)
if not na(btc)
var perp_venues = btc.venues_of(AL.VenueKind.PERP)
if array.size(perp_venues) > 0
var first_perp = array.get(perp_venues, 0)
label.new(bar_index, close, "First Perp: " + first_perp.ticker,
color=color.green, textcolor=color.white)
// Example 4: Build volume aggregator with policy
if not na(btc)
var policy = AL.AggregationPolicy.new(
include_spot=true, include_perp=true, include_fut=false,
max_tier=2, max_venues=5)
var agg = AL.f_build_aggregator(btc, policy)
if array.size(agg.selected) > 0
string venues_str = ""
for i = 0 to math.min(array.size(agg.selected) - 1, 2)
var v = array.get(agg.selected, i)
venues_str += v.ticker + " "
label.new(bar_index, high * 1.01, "Top Venues: " + venues_str,
color=color.purple, textcolor=color.white)
// Example 5: Check trading hours and adapt indicator behavior
if not na(btc)
bool is_24x7 = btc.hours == AL.TradingHours.H_24X7
bgcolor(is_24x7 ? color.new(color.green, 90) : color.new(color.red, 90),
title="24x7 Market")
```
## Inputs, outputs, expected behavior
**Registry initialization** (`f_registry_new`, `f_registry_init`):
- **Inputs**: None (uses hardcoded asset definitions)
- **Outputs**: AssetRegistry with populated `bysymbol` and `byalias` maps
- **Edge cases**: `f_registry_init` must be called once before lookups, idempotent (safe to call multiple times)
**Asset lookup** (`bysymbol.get`, `byalias.get`):
- **Inputs**: `symbol` (string, canonical like "BTC") or `ticker` (string, full like "BINANCE:BTCUSDT")
- **Outputs**: AssetRecord or na if not found
- **Edge cases**: Returns na for unknown symbols (no silent fallback to "ETH" like prior versions), case-sensitive keys
**Venue filtering** (`venues_of`, `venues_t1`, `venues_spot`):
- **Inputs**: `rec` (AssetRecord), `kind` (VenueKind enum)
- **Outputs**: array (filtered subset)
- **Edge cases**: Returns empty array if no venues match, preserves insertion order
**Venue builder** (`f_build_venue`):
- **Inputs**: `ticker` (string, e.g., "BINANCE:BTCUSDT.P"), `tier` (LiquidityTier enum)
- **Outputs**: Venue with auto-detected kind and exchange
- **Edge cases**: Defaults to SPOT if no perp/fut pattern detected, exchange is empty string if ticker lacks ":"
**Aggregation policy** (`f_build_aggregator`, `AggregationPolicy`):
- **Inputs**: `rec` (AssetRecord), `policy` (include_spot/perp/fut bools, max_tier int, max_venues int)
- **Outputs**: VolumeAggregator with selected venues and normalized weights
- **Edge cases**: Returns empty selected array if no venues match policy, weights sum to 1.0 (or 0.0 if no venues)
**Parent chain lookup** (`rec.chain`, `rec.isl1`):
- **Inputs**: AssetRecord
- **Outputs**: `chain` (string, parent L1 symbol), `isl1` (bool, true if asset IS its own chain)
- **Edge cases**: For L1 assets (BTC, ETH, SOL), `chain == symbol` and `isl1 == true`
## Limitations
1. **Hardcoded asset list**: The library ships with ~50 pre-defined assets (major crypto, indices, commodities). Adding new assets requires library source modification and republishing. No runtime registration API exists (Pine Script limitations on dynamic map population).
2. **No real-time venue discovery**: Venue lists are static (defined at library publication). If Binance launches a new BTC perpetual contract, the library won't auto-detect it. Users must manually update the library or use custom venue builders.
3. **Liquidity tier assignments are subjective**: T1/T2/T3 classifications are based on typical volume rankings (Binance/Coinbase/CME = T1, OKX/Bybit = T2, others = T3). Actual liquidity varies by asset and time. The library does not query real-time volume data to adjust tiers.
4. **No support for exotic derivatives**: The library covers spot, perpetual, and dated futures. Options, structured products, and leveraged tokens are not classified. VenueKind.FUT assumes CME-style dated contracts, not perpetual futures with funding rates.
5. **Trading hours are regime-level, not session-precise**: `TradingHours.H_US` means "US market hours" but doesn't encode exact open/close times (9:30-16:00 ET). Indicators needing precise session boundaries must implement additional logic (e.g., via `time()` and timezone offsets).
6. **Alias map requires exact ticker match**: `byalias.get("BINANCE:BTCUSDT")` works, but `byalias.get("binance:btcusdt")` (lowercase) returns na. The library does not auto-normalize case. Use `str.upper(syminfo.tickerid)` before lookup.
7. **No FIGI or ISIN support**: The library uses PulseWire ticker strings as identifiers. Financial Instrument Global Identifiers (FIGI) or International Securities Identification Numbers (ISIN) are not supported. Cross-platform symbol mapping (e.g., Bloomberg → PulseWire) requires external tools.
8. **Parent chain field is single-valued**: Assets with multi-chain deployments (e.g., USDC on Ethereum, Solana, Polygon) store only one parent chain. The library does not model multi-chain tokens or cross-chain bridges.
Library

Online Logistic Forecaster [forexobroker]Online Logistic Forecaster trains a single-feature logistic regression in real time via stochastic gradient descent. The feature is the standardised price-EMA distance; the target is "next bar closes higher". Each bar updates weight w := w - eta * (sigmoid(w * x) - y) * x. Forecast probability of next-bar up = sigmoid(w * x). Adaptive learning without batch training.
🔶 ALGORITHM
1. EMA = ema(close, len); ATR = atr(14).
2. Feature x = (close - EMA) / ATR (ATR-normalised distance).
3. Online SGD step: y_prev = (close > close ); w := w - eta * (sigmoid(w * x ) - y_prev) * x .
4. Forecast: p_up = sigmoid(w * x).
5. Bull bias when p_up >= upper threshold; bear bias when <= lower threshold.
🔶 SIGNAL LOGIC
- Buy: bull bias edge (cross above upper threshold) AND not already long AND cooldown elapsed AND barstate.isconfirmed.
- Sell: bear bias edge.
- Position-lock state machine.
🔶 INPUTS
- Feature EMA Length (default 20)
- Learning Rate eta (default 0.05)
- Buy Probability (default 0.60)
- Sell Probability (default 0.40)
- Cooldown Bars (default 4)
- Visual: dashboard, glow, sigmoid line, buy / sell colors
🔶 ALERTS
OLF Buy, OLF Sell, OLF Any Signal, OLF Bull Edge, OLF Bear Edge, OLF High Conf Up, OLF High Conf Dn, OLF Strong Weight, OLF Webhook JSON.
🔶 LIMITATIONS
- One feature gives a 1D logistic forecast; multi-feature models would be more powerful but require explicit weight management.
- SGD with high eta can oscillate; defaults (eta = 0.05) balance convergence vs adaptation.
- The model needs warm-up of dozens of bars before w stabilises; early bars produce noisy forecasts.
- The "sigmoid line" visual is anchored at the EMA and scaled by ATR — purely informational.
Indicator

MAD Z Robust Burst [forexobroker]MAD Z Robust Burst computes a Median Absolute Deviation z-score: MAD-Z = (close - median) / (1.4826 * MAD), where MAD = median(|x - median|). The 1.4826 factor makes MAD a consistent estimator of stdev under normality. Robust to outliers — a single price spike does not inflate the divisor like ordinary stdev does. Visual signature: outlined-only square markers (no fill), MAD bands.
🔶 ALGORITHM
1. window = last N closes.
2. med = median(window).
3. abs_dev = |close - med|.
4. MAD = median(abs_dev).
5. MAD-Z = (close - med) / (1.4826 * MAD).
6. Burst regime when |MAD-Z| > threshold.
7. Return-from-burst entry: signal fires when MAD-Z comes back below the return threshold from a burst.
🔶 SIGNAL LOGIC
- Buy: prior burst-down AND MAD-Z >= -return-threshold AND not already long AND cooldown elapsed AND barstate.isconfirmed.
- Sell: prior burst-up AND MAD-Z <= +return-threshold.
- Position-lock state machine.
🔶 INPUTS
- MAD Window (default 40)
- Burst Z entry start (default 2.0)
- Return Z entry fire (default 1.0)
- Cooldown Bars (default 4)
- Visual: dashboard, glow, MAD bands, outlined markers, buy / sell colors
🔶 ALERTS
MZB Buy, MZB Sell, MZB Any Signal, MZB Burst Up, MZB Burst Down, MZB Extreme, MZB Return Up, MZB Return Down, MZB Webhook JSON.
🔶 LIMITATIONS
- MAD is robust but slower-reacting than stdev; bursts may persist a bit longer before being detected.
- The 1.4826 normalisation assumes Gaussian-like distributions; for heavy-tailed assets the conversion is approximate.
- Outlined squares (no glow stack) is a deliberate visual choice — the indicator looks unique but has slightly lower visibility than filled markers.
- Return-from-burst entry is mean-reversion oriented; not for breakout players.
Indicator

DTW Template Tracker [forexobroker]DTW Template Tracker uses simplified Dynamic Time Warping with a Sakoe-Chiba band (width 2) to align recent z-scored closes against monotone bull (linear rise) and bear (linear fall) templates. DTW allows time stretching that cosine similarity does not. Lower distance = closer match; signal fires when one template's distance is materially lower than the other and below an absolute threshold.
🔶 ALGORITHM
1. Z-score the recent N closes using rolling mean and stdev.
2. Build templates: bull = linspace(-1, +1) over N points; bear = -bull.
3. DTW with Sakoe-Chiba band W = 2: cost matrix D is filled only within |i - j| <= W. D = |x - t | + min(D , D , D ).
4. Bull and bear distances = D under each template.
5. Match when one distance < other AND <= threshold.
🔶 SIGNAL LOGIC
- Buy: bull match edge AND not already long AND cooldown elapsed AND barstate.isconfirmed.
- Sell: bear match edge.
- Position-lock state machine.
🔶 INPUTS
- Template Length (default 15)
- DTW Distance Threshold (default 2.0)
- Cooldown Bars (default 4)
- Visual: dashboard, glow (flag with "match"), template overlay, buy / sell colors
🔶 ALERTS
DTT Buy, DTT Sell, DTT Any Signal, DTT Bull Match, DTT Bear Match, DTT Bull Tight, DTT Bear Tight, DTT Strong, DTT Webhook JSON.
🔶 LIMITATIONS
- DTW cost grows ~ N * W per bar; defaults (N = 15, W = 2) keep compute reasonable. Larger N exceeds Pine compute budget.
- Sakoe-Chiba band W = 2 limits stretch to +/- 2 bars; useful for 1:1 matching with minor jitter.
- Monotone templates only — V-shaped or W-shaped patterns require additional template definitions.
- Z-scoring removes scale; the indicator is invariant to absolute price level.
Indicator

Amihud Illiquidity Surge [forexobroker]Amihud Illiquidity Surge computes the canonical Amihud (2002) illiquidity ratio: |return| / volume. High value = price moves a lot per unit of volume traded = illiquid market = price-impact dominated regime. Z-scored over a rolling window to detect surges. Signals fire on EMA cross during a surge, gold-and-red palette unique to this indicator.
🔶 ALGORITHM
1. AIS = |close - close | / max(volume, 1).
2. AIS-Z = (AIS - sma(AIS, N)) / stdev(AIS, N).
3. Surge regime when AIS-Z >= threshold.
4. EMA cross within surge fires entries in the prevailing direction.
🔶 SIGNAL LOGIC
- Buy: surge AND close crosses EMA up AND not already long AND cooldown elapsed AND barstate.isconfirmed.
- Sell: surge AND close crosses EMA down.
- Position-lock state machine.
🔶 INPUTS
- Z-Score Window (default 50)
- Surge Z Threshold (default 1.5)
- Pullback EMA Length (default 8)
- Cooldown Bars (default 4)
- Visual: dashboard (gold-themed double border), glow, dollar-symbol labels, buy / sell colors
🔶 ALERTS
AIS Buy, AIS Sell, AIS Any Signal, AIS Surge Start, AIS Surge End, AIS Extreme, AIS EMA Up, AIS EMA Down, AIS Webhook JSON.
🔶 LIMITATIONS
- Forex tick volume is broker-aggregated and noisy; futures, equities, and crypto produce cleaner illiquidity readings.
- The labels show "AIS$" — the dollar symbol is a visual cue, not a units claim.
- For very-low-volume bars (e.g., overnight or holiday sessions) the ratio inflates artificially; the volume floor of 1 mitigates but does not eliminate this.
- AIS surges precede price moves only loosely; pair with a directional gate.
Indicator

Cadence Reversion Cartography [JOAT]Cadence Reversion Cartography
Introduction
Cadence Reversion Cartography is an open-source mean-reversion and exhaustion overlay designed to locate stretched conditions around an EMA envelope and anchored VWAP framework. It focuses on mapping where price has moved too far from local balance, then grades whether a return toward value has enough supporting evidence to matter.
The problem this script solves is selective reversal timing. Price can stay overextended for longer than expected, so simple band-touch logic is not enough. Cadence Reversion Cartography combines envelope stretch, VWAP stretch, RSI exhaustion, volume impulse, rejection-candle behavior, reclaim logic, and projected response boxes so the user can distinguish weak touches from stronger reversion candidates.
Core Concepts
1. Dual Stretch Model
Price is compared to both an EMA deviation envelope and an anchored VWAP deviation layer. A long-side exhaustion condition requires price to stretch below both lower references. A short-side exhaustion condition requires price to stretch above both upper references.
2. Exhaustion Quality Filters
RSI can require oversold or overbought context, volume can require impulse relative to average participation, and candle structure can require a visible rejection profile.
3. Reclaim And Signal Grading
A setup becomes actionable only after price closes back inside the envelope on a confirmed bar. The script then scores the setup by counting how many filters aligned and promotes stronger signals to a prime grade.
4. Projection Mapping
When a setup forms, the script can draw a forward projection with a risk box, reward box, signal zone, and reclaim line. This is meant to show the structure of the reversion idea rather than acting as a promise of outcome.
Features
EMA reversion envelope: Basis plus statistical deviation bands
Anchored VWAP stretch layer: Secondary value reference around VWAP
RSI exhaustion filter: Optional momentum exhaustion gate
Volume impulse filter: Optional participation confirmation
Rejection-candle filter: Optional candle-structure confirmation
Signal grading: Standard and prime long or short responses
Signal zones and reclaim lines: On-chart response structure around the active setup
Risk and reward projection boxes: Optional forward mapping of stop and target structure
Context candle coloring: Candles can tint with stretch state
Dashboard: Displays stretch, setup bias, and active context
Input Parameters
Reversion Envelope:
Channel Length
Deviation Multiplier
VWAP Stretch Multiplier
Filters And Display:
RSI settings
Volume average and impulse multiplier
Rejection-candle requirement
Projection-box toggle, stop percent, reward multiple, projection length, and signal cooldown
Dashboard, background, candle-color, and signal-zone toggles
How to Use This Indicator
Step 1: Wait for price to stretch beyond both the EMA envelope and the VWAP stretch layer.
Step 2: Check whether RSI, volume, and rejection filters support the move.
Step 3: Wait for confirmed re-entry back inside the envelope instead of fading the first touch.
Step 4: Use the signal grade and projection structure to judge whether the setup is marginal or stronger.
Step 5: Use the basis and reclaim line as the first balance reference after entry.
Indicator Limitations
Strong directional trends can keep price stretched for extended periods and delay reversion
Volume-based confirmation is less meaningful on symbols with irregular volume reporting
Projection boxes are planning tools, not guaranteed outcomes
This script is designed for reversion analysis and is not intended to replace broader trend context
Originality Statement
Cadence Reversion Cartography is original in how it coordinates envelope stretch, VWAP stretch, filter-based exhaustion grading, and forward projection structure inside one reversion workflow. The components are combined to answer one analytical problem: not just whether price is stretched, but whether the stretch is mature enough to support a structured return toward value.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice. Reversion setups can fail during strong trends or regime expansion, so all signals should be used with independent confirmation and risk management.
-Made with passion by jackofalltrades
Indicator

Indicator

Indicator

Library

Session Bias Relay Map [AGPro Series]Session Bias Relay Map
🧠 Core Idea
Did Asia, London, and New York pass the same bias forward, or did the next session reject the market narrative?
📌 Overview / What it does
Session Bias Relay Map is an intraday session-structure tool built to visualize how directional bias moves from one major trading session to the next.
The script tracks Asia, London, and New York session ranges, scores each session's directional bias, and classifies whether the active session confirms, conflicts with, or reverses the previous session's narrative.
It does not predict price direction, automate trades, or claim that a session handoff must continue. It is a structured visualization and decision-support map for session bias, market narrative, and intraday context.
🎯 Purpose & Design Philosophy
Many session tools draw boxes, highs, lows, or kill zones.
This script was built to answer a more contextual question:
Did the next major session accept the prior session's directional story, or did it break the handoff?
The design goal is to help traders read sessions as a relay of market intent instead of isolated time windows. It supports discretionary market reading, session review, and intraday structure analysis.
⚡ Why This Script Is Different
Most session indicators focus on time blocks, session highs, and session lows.
This script does NOT stop at drawing session boxes.
Instead, it evaluates how each session behaves relative to the prior session. It scores bias strength, detects handoff confirmation, identifies conflict, and highlights reversal pressure when the active session builds a strong opposite narrative.
⚙️ Methodology
1. Session Detection
The script tracks configurable Asia, London, and New York session windows using the chart symbol's exchange timezone.
2. Session Range Mapping
For each session, it records open, high, low, close, midpoint, bar count, and live range behavior.
3. Bias Scoring
Session bias is scored using body pressure, close location inside the session range, and optional relative volume confirmation.
4. Relay Evaluation
London is compared against the completed Asia bias.
New York is compared against the completed London bias.
5. Visual Output
The chart displays session boxes, midpoint rails, centered session labels, relay event labels, right-side tags, alerts, and a compact AG Pro decision panel.
🗺️ How to Read the Chart
Session Boxes = the active session range built from each configured time window.
Centered Labels = the session name, current bias, relay state, and quality score.
Midpoint Rails = the middle of each session range, useful for reading control and balance.
Relay Event Labels = confirmation, conflict, or reversal events when a later session responds to the prior session.
Right-Side Tags = the current relay state and active session bias.
Panel = summarizes active session, relay state, bias score, prior session, session quality scores, next context, and timeframe scope.
🚦 Signals & States
• RELAY CONFIRMED → the active session supports the previous session's directional bias.
• RELAY REVERSAL → the active session builds strong bias opposite to the previous session.
• BIAS CONFLICT → the active session does not clearly confirm the previous session.
• FIRST LEG → Asia is building the first session bias for the daily relay.
• WAIT HANDOFF → the active handoff does not yet have enough evidence.
• BULLISH → the session is closing with bullish range pressure.
• BEARISH → the session is closing with bearish range pressure.
• NEUTRAL → the session does not have enough directional pressure.
🔔 Alerts Logic
Alerts trigger when a major relay state appears.
• Session Bias Relay Confirmed → the active session confirmed the directional bias passed from the previous session.
• Session Bias Conflict → the active session failed to confirm the previous session and is showing conflict.
• Session Bias Reversal → the active session built strong bias opposite to the previous session.
Alerts are attention markers, not trade instructions.
🧩 Confluence Logic
The context becomes stronger when:
• The previous session has a clear directional bias
• The active session has enough bars to evaluate
• The active session bias score is above the confirmation threshold
• Price closes with clear range position
• Relative volume supports participation
• The relay label and panel state agree
If these elements do not align, the script avoids forcing a strong directional interpretation.
📊 When to Use
• Intraday session analysis
• Forex, crypto, index futures, and liquid stock index products
• Asia-to-London handoff review
• London-to-New-York handoff review
• Market narrative tracking
• Session range and bias studies
• 15m, 30m, 1H, and 2H charts
⚠️ When NOT to Use
• Daily, weekly, or monthly charts
• Very low-liquidity symbols
• Markets with irregular or meaningless session windows
• Extremely noisy conditions where session closes do not carry useful information
• Situations where a single session should not be over-interpreted
• Symbols where the chart exchange timezone does not match the intended session model
🎛️ Key Inputs
• Asia Session → defines the first session window used to build the initial bias.
• London Session → defines the second session window used to evaluate the Asia handoff.
• New York Session → defines the third session window used to evaluate the London handoff.
• Max Chart TF Minutes → limits the largest timeframe that should build the relay map.
• Bias Confirmation Threshold → controls how strong a session must be before it can confirm a relay.
• Conflict Threshold → controls when a session is treated as weak or conflicted.
• Minimum Handoff Bars → prevents early-session noise from printing premature relay labels.
• Use Volume Confirmation → adds relative volume pressure to the bias score.
• Show Session Boxes → controls the main visual range boxes.
• Show Relay Event Labels → controls confirmation, conflict, and reversal labels.
• Label Font Size → controls chart label and tag text size.
• Panel Font Size → controls panel text size.
🖥️ Interface & Visual Design
The visual hierarchy is built around the session relay story.
Session boxes define the time windows.
Centered labels make each session readable without hunting through the chart.
Relay labels highlight the important handoff moments.
Right-side tags keep the current state visible.
The AG Pro panel summarizes the active session context in a clean, compact format.
🧪 Practical Usage Workflow
1. Choose session windows that match the market being studied.
2. Let Asia build the first bias leg.
3. Watch whether London confirms, conflicts with, or reverses Asia.
4. Watch whether New York confirms, conflicts with, or reverses London.
5. Use the panel to check relay state, active bias, quality score, and timeframe scope.
6. Interpret the result inside broader market structure, liquidity, and volatility context.
🔍 Interpretation Guidelines
A relay confirmation does not guarantee continuation. It means the active session is supporting the prior session's directional bias according to the script's rule set.
A relay reversal does not guarantee a full trend reversal. It means the active session is building strong opposite pressure relative to the previous session.
A bias conflict is not a failure. It is useful information that the market narrative is not clean.
The best use is contextual: combine the relay state with support, resistance, liquidity, volume, and higher-timeframe structure.
🚫 What This Script Is NOT
This script is not a prediction engine.
It is not financial advice.
It is not an auto-trading system.
It does not provide guaranteed entry or exit signals.
It is not a generic session box indicator.
It is not a kill-zone strategy.
⚠️ Limitations & Transparency
Session settings matter. Poorly selected session windows can produce weak or misleading context.
Timeframe differences can affect how session handoffs appear.
Low-liquidity markets can distort bias scores.
Markets with irregular trading hours may need custom session inputs.
Relative volume can help, but it does not guarantee better interpretation in every market.
🧠 Market Context Notes
Session behavior is often shaped by liquidity, regional participation, volatility expansion, and macro timing.
The same relay state can mean different things depending on whether the market is trending, ranging, or reacting to news.
The script is strongest when used as a narrative map, not as a standalone decision machine.
🧾 Use Case Examples
• If Asia builds a bullish range and London also closes with strong bullish pressure, the relay may show confirmation.
• If Asia builds bullish pressure but London quickly forms strong bearish pressure, the relay may show reversal.
• If London begins with weak movement and no clear range pressure, the relay may show conflict or wait for more evidence.
🧱 System Philosophy
Session Bias Relay Map is part of the AGPro Series approach to decision-support tools:
clear structure, premium chart readability, honest interpretation, and no promise of certainty.
The goal is to help traders see market context faster without turning analysis into signal spam.
🔐 Non-Promise Statement
No script can know the future.
No session handoff is guaranteed.
No signal should be interpreted without broader market context.
📉 Risk Disclosure
Trading involves risk.
Markets can move unpredictably.
This script is for educational and analytical purposes only.
It does not provide financial advice or guaranteed trading outcomes.
Users remain responsible for their own decisions.
📚 Educational Note
Use this script to study how market participation changes across sessions.
The value is not only in the label. The value is in learning how the session narrative develops, confirms, conflicts, or reverses over time.
Indicator

Prop Firm Shield - Challenger [Quiet Edge]Your prop firm's rules, enforced at the chart. Prop Firm Shield tracks your daily-loss budget, drawdown buffer, and position size in real time — so the limit is visible the moment you are near it.
This is the Challenger tier — free, no login required. Enter your account size, starting balance, and current balance. The dashboard does the rest.
What it tracks
Daily loss budget — how much you have left, in dollars and percent
Drawdown buffer — remaining room before breach
Position size calculator — enter entry, stop, and risk % to get a recommended lot size
SAFE / CAUTION / STOP status with chart background alert
Upgrade to Operator ($19/mo) for verified firm presets (FTMO, Topstep, The5ers, MyFundedFutures), trailing drawdown, consistency rule tracker, and session close countdown.
Upgrade to Principal ($39/mo) for lot size escalation guard and an Evaluation vs Funded phase toggle — the only on-chart tool that models intraday trailing drawdown for funded accounts.
quietedgelabs.com/indicators/risk-management/prop-firm-shield Indicator
