Multi-Contraction VCP DetectorThis indicator highlights low volume and contracted price movement prior to possible breakouts.
波动率
SMI Trigger System The SMI Trigger System is a lower-pane momentum indicator based on a Hull-smoothed Stochastic Momentum Index (SMI). It is designed to assist in identifying potential momentum shifts by highlighting signal alignment and level interactions.
This indicator is intended to be used as part of a broader analysis framework. Confluence between trend, structure, and higher-timeframe context defines the setup, while SMI signal behavior may be used for confirmation.
The script can be applied across multiple timeframes and markets. It does not generate trade signals on its own and should be used alongside additional analysis and risk management techniques.
For educational purposes only. Not financial advice.
Hybrid Strategy: Trend/ORB/MTFHybrid Strategy: Trend + ORB + Multi-Timeframe Matrix
This script is a comprehensive "Trading Manager" designed to filter out noise and identify high-probability breakout setups. It combines three powerful concepts into a single, clean chart interface: Trend Alignment, Opening Range Breakout (ORB), and Multi-Timeframe (MTF) Analysis.
It is designed to prevent "analysis paralysis" by providing a unified Dashboard that confirms if the trend is aligned across 5 different timeframes before you take a trade.
How it Works
The strategy relies on the "Golden Trio" of confluence:
1. Trend Definition (The Setup) Before looking for entries, the script analyzes the immediate trend. A bullish trend is defined as:
Price is above the Session VWAP.
The fast EMA (9) is above the slow EMA (21). (The inverse applies for bearish trends).
2. The Signal (The Trigger) The script draws the Opening Range (default: first 15 minutes of the session).
Buy Signal: Price breaks above the Opening Range High while the Trend is Bullish.
Sell Signal: Price breaks below the Opening Range Low while the Trend is Bearish.
3. The Confirmation (The Filter) A signal is only valid if the Higher Timeframe (default: 60m) agrees with the direction. If the 1m chart says "Buy" but the 60m chart is bearish, the signal is filtered out to prevent false breakouts.
Key Features
The Matrix Dashboard A zero-lag, real-time table in the corner of your screen that monitors 5 user-defined timeframes (e.g., 5m, 15m, 30m, 60m, 4H).
Trend: Checks if Price > EMA 21.
VWAP: Checks if Price > VWAP.
ORB: Checks if Price is currently above/below the Opening Range of that session.
D H/L: Warns if price is near the Daily High or Low.
PD H/L: Warns if price is near the Previous Daily High or Low.
Visual Order Blocks The script automatically identifies valid Order Blocks (sequences of consecutive candles followed by a strong explosive move).
Chart: Draws Green/Red zones extending to the right, showing where price may react.
Dashboard: Displays the exact High, Low, and Average price of the most recent Order Blocks for precision planning.
Risk Management (Trailing Stop) Once a trade is active, the script plots Chandelier Exit dots (ATR-based trailing stop) to help you manage the trade and lock in profits during trend runs.
Visual Guide (Chart Legend)
⬜ Gray Box: Represents the Opening Range (first 15 minutes). This is your "No Trade Zone." Wait for price to break out of this box.
🟢 Green Line: The Opening Range High. A break above this line signals potential Bullish momentum.
🔴 Red Line: The Opening Range Low. A break below this line signals potential Bearish momentum.
🟢 Green / 🔴 Red Zones (Boxes): These are Order Blocks.
🟢 Green Zone: A Bullish Order Block (Demand). Expect price to potentially bounce up from here.
🔴 Red Zone: A Bearish Order Block (Supply). Expect price to potentially reject down from here.
⚪ Dots (Trailing Stop):
🟢 Green Dots: These appear below price during a Bullish trend. They represent your suggested Stop Loss.
🔴 Red Dots: These appear above price during a Bearish trend.
🏷️ Buy / Sell Labels:
BUY: Triggers when Price breaks the Green Line + Trend is Bullish + HTF is Bullish.
SELL: Triggers when Price breaks the Red Line + Trend is Bearish + HTF is Bearish.
Settings
Session: Customizable RTH (Regular Trading Hours) to filter out pre-market noise.
Matrix Timeframes: 5 fixed slots to choose which timeframes you want to monitor.
Order Blocks: Adjust the sensitivity and lookback period for Order Block detection.
Risk: Customize the ATR multiplier for the trailing stop.
Disclaimer
This tool is for educational purposes only. Past performance does not guarantee future results. Always manage your risk properly.
USD Liquidity Regime IndexTrack global risk regimes with this USD Liquidity Composite —
It aims to be a daily macro indicator blending normalised DXY (50%), UUP (20%), 10Y Treasury yields (20%), and VIX (10%).
How to read:
When the blue index is above its red SMA: Strong USD, tightening liquidity → Risk-Off mode (often bearish for Nasdaq, BTC, and risk assets).
When the line is below: Weak USD, abundant liquidity → Risk-On (bullish environment).
Example: In 2022's bear market, the index stayed high above SMA most of the year, signalling persistent Risk-Off as USD surged.
Features on-chart table, regime background colors, and crossover alerts.
Great contextual tool for macro traders IMO.
Educational only — not financial advice.
Use at your own risk.
By @frank_vergaram
GARCH Adaptive Volatility & Momentum Predictor
💡 I. Indicator Concept: GARCH Adaptive Volatility & Momentum Predictor
-----------------------------------------------------------------------------
The GARCH Adaptive Momentum Speed indicator provides a powerful, forward-looking
view on market risk and momentum. Unlike standard moving averages or static
volatility indicators (like ATR), GARCH forecasts the Conditional Volatility (σ_t)
for the next bar, based on the principle of volatility clustering.
The indicator consists of two essential components:
1. GARCH Volatility (Level): The primary forecast of the expected magnitude of
price movement (risk).
2. Vol. Speed (Momentum): The first derivative of the GARCH forecast, showing
whether market risk is accelerating or decelerating. This component is the
main visual signal, displayed as a dynamic histogram.
⚙️ II. Key Features and Adaptive Logic
-----------------------------------------------------------------------------
* Dynamic Coefficient Adaptation: The indicator automatically adjusts the GARCH
coefficients (α and β) based on the chart's timeframe (TF):
- Intraday TFs (M1-H4): Uses higher α and lower β for quicker reaction
to recent shocks.
- Daily/Weekly TFs (D, W): Uses lower α and higher β for a smoother,
more persistent long-term forecast.
* Momentum Visualization: The Vol. Speed component is plotted as a dynamic
histogram (fill) that automatically changes color based on the direction of
acceleration (Green for up, Red for down).
📊 III. Interpretation Guide
-----------------------------------------------------------------------------
- GARCH Volatility (Blue Line): The predicted level of market risk. Use this to
gauge overall position sizing and stop loss width.
- Vol. Speed (Green Histogram): Momentum is ACCELERATING (Risk is increasing rapidly).
A strong signal that momentum is building, often preceding a breakout.
- Vol. Speed (Red Histogram): Momentum is DECELERATING (Risk is contracting).
Indicates momentum is fading, often associated with market consolidation.
🎯 IV. Trading Application
-----------------------------------------------------------------------------
- Breakout Timing: Look for a strong, high GREEN histogram bar. This suggests
the volatility pressure is increasing rapidly, and a breakout may be imminent.
- Consolidation: Small, shrinking RED histogram bars signal that market energy
is draining, ideal for tight consolidation patterns.
Adaptive RSI Pro# Adaptive RSI Pro / 自适应RSI专业版
[! (img.shields.io)](www.tradingview.com)
[! (img.shields.io)](www.tradingview.com)
[! (img.shields.io)](opensource.org)
Dynamic overbought/oversold thresholds + Multi-Timeframe analysis + Divergence detection + Signal statistics.
根据每个标的实际历史分布动态计算超买/超卖阈值,结合多时间框架分析、背离检测和信号统计。
**Pine Script v6** | **Last Update: 2025-12-17** | **v6.2**
---
## Emoji Legend / 信号图例
### Chart Signals / 图表信号
#### Buy Signals / 买入信号 (底部显示)
| Emoji | Signal Name | Condition | Priority | Action |
|-------|-------------|-----------|----------|--------|
| 🌟 | MTF + Extreme | 3+ timeframes oversold + Z<−2σ | ★★★★★ | **STRONG BUY** 强力买入 |
| 💎 | Divergence + Extreme | Bullish divergence in Z<−2σ zone | ★★★★☆ | **BUY** 买入 |
| 🔥 | Extreme Oversold | Z-Score crosses below −2σ (≈P2) | ★★★☆☆ | **BUY** 买入 |
| ⬆️ | Normal Oversold | Z-Score crosses below −1.5σ (≈P7) | ★★☆☆☆ | Consider buy 考虑买入 (默认隐藏) |
| ↗️ | Bullish Divergence | Price↓ RSI↑ (not in extreme zone) | ★☆☆☆☆ | Watch 观察 (潜在底部) |
#### Sell Signals / 卖出信号 (顶部显示)
| Emoji | Signal Name | Condition | Priority | Action |
|-------|-------------|-----------|----------|--------|
| 🌟 | MTF + Extreme | 3+ timeframes overbought + Z>+2σ | ★★★★★ | **STRONG SELL** 强力卖出 |
| 💎 | Divergence + Extreme | Bearish divergence in Z>+2σ zone | ★★★★☆ | **SELL** 卖出 |
| ❄️ | Extreme Overbought | Z-Score crosses above +2σ (≈P98) | ★★★☆☆ | **SELL** 卖出 |
| ⬇️ | Normal Overbought | Z-Score crosses above +1.5σ (≈P93) | ★★☆☆☆ | Consider sell 考虑卖出 (默认隐藏) |
| ↘️ | Bearish Divergence | Price↑ RSI↓ (not in extreme zone) | ★☆☆☆☆ | Watch 观察 (潜在顶部) |
> **Priority System / 优先级系统**: Only the highest priority signal is shown to prevent overlapping.
> 只显示最高优先级信号,避免叠加。
---
### Dashboard Status / 仪表盘状态
| Emoji | Status | Meaning |
|-------|--------|---------|
| 🟢 | EXTREME OVERSOLD | Z-Score < −2σ (≈P2.3), strong buy zone / 极端超卖区,强买区 |
| 🟡 | OVERSOLD | Z-Score < −1.5σ (≈P6.7), oversold / 超卖 |
| ⚪ | NEUTRAL | −1.5σ ≤ Z-Score ≤ +1.5σ, no signal / 中性,无信号 |
| 🟠 | OVERBOUGHT | Z-Score > +1.5σ (≈P93.3), overbought / 超买 |
| 🔴 | EXTREME OVERBOUGHT | Z-Score > +2σ (≈P97.7), strong sell zone / 极端超买区,强卖区 |
### MTF Status / 多周期状态
| Emoji | Meaning |
|-------|---------|
| 🟢 | Timeframe oversold / 该周期超卖 |
| 🔴 | Timeframe overbought / 该周期超买 |
| ⚪ | Timeframe neutral / 该周期中性 |
### Divergence Status / 背离状态
| Emoji | Meaning |
|-------|---------|
| 🟢 BULL DIV | Bullish divergence detected / 检测到看涨背离 |
| 🔴 BEAR DIV | Bearish divergence detected / 检测到看跌背离 |
| — | No divergence / 无背离 |
---
### Alert Emojis / 警报图标
| Emoji | Alert Type | Description |
|-------|------------|-------------|
| 🎯 | Smart Alert | V6 Unified Alert System / V6统一警报系统 |
---
## Overview / 概述
Traditional RSI uses fixed 30/70 thresholds, but different assets have different volatility characteristics.
传统RSI使用固定的30/70阈值,但不同标的有不同的波动特性。
**Solution**: Calculate thresholds using historical percentiles (P5-P95) + advanced features.
**解决方案**:使用历史百分位(P5-P95)计算阈值 + 高级功能。
---
## Features / 功能特性
### 🎯 Adaptive Thresholds / 自适应阈值
- **Z-Score Based Signals**: Uses statistical Z-Score (±2σ for extreme, ±1.5σ for normal) for consistent cross-asset performance
使用统计Z-Score(极端±2σ,普通±1.5σ)实现跨资产一致性
- **Percentile Lines**: Display P5/P10/P25/P50/P75/P90/P95 for visual reference
百分位线(P5-P95)作为视觉参考
- **Dual Display Modes**: Show Z-Score lines, Percentile lines, or both
双重显示模式:可选择显示Z值线、百分位线或两者
### 🔬 Auto-Adaptive Lookback / 自动自适应回看期
- **Statistical Formula**: Uses `n = (Z × σ / E)²` for optimal sample size calculation
统计公式:使用样本量公式自动计算最优回看期
- **Dual Volatility System**: Combines short-term (4× RSI length) and long-term volatility (configurable: 6M/1Y/2Y)
双重波动率系统:结合短期和长期波动率动态调整
- **Precision Control**: Choose High/Normal/Low precision (adjusts acceptable error margin)
精度控制:高/普通/低精度可选(调整统计误差容忍度)
- **Health Indicators**: Real-time validation of sample coverage, distribution spread, and statistical validity
健康度指标:实时验证样本覆盖率、分布宽度和统计有效性
### 📈 Auto-Adaptive Trend Filter / 自动自适应趋势过滤
- **Auto Mode**: Automatically selects optimal filter based on RSI volatility percentiles
自动模式:根据RSI波动率百分位自动选择最优过滤器
- **5 Filter Modes**: Fixed 50, Adaptive P50, SMA(RSI), BB(RSI), or Auto
5种过滤模式:固定50、自适应P50、RSI均线、布林带或自动
- **Smart Selection**: Low volatility → Fixed 50, Medium → Adaptive P50, High → BB(RSI)
智能选择:低波动→固定50,中波动→自适应P50,高波动→布林带
### 🌍 Multi-Timeframe RSI / 多时间框架RSI
- **3 Configurable Timeframes**: View RSI status across multiple timeframes (default: 1h/4h/D)
3个可配置时间框架:跨周期查看RSI状态(默认:1小时/4小时/日线)
- **Auto-Skip Duplicates**: Automatically detects and skips timeframes matching current chart
自动跳过重复:自动检测并跳过与当前图表相同的时间框架
- **Resonance Detection**: Triggers when 3+ valid timeframes agree (oversold/overbought)
共振检测:当3个以上有效时间框架一致时触发强信号
>
> **MTF Signal Confirmation Timing / 信号确认时机**
>
> - Current timeframe signals update in real-time, confirmed on bar close
> - Higher timeframe signals (e.g., Daily on 1H chart) only update after that timeframe's bar closes
> - **Best Practice**: Wait for current timeframe bar close before acting on MTF resonance signals
>
> - 当前图表周期的信号:实时更新,K线收盘确认
> - 高周期信号(如日线):仅在该周期K线收盘后更新
> - **最佳实践**:MTF共振信号建议在当前周期K线收盘后再做交易决策
### 💎 Auto-Adaptive Divergence Detection / 自动自适应背离检测
- **Auto Mode**: Automatically selects parameters based on asset volatility (using ATR)
自动模式:基于资产波动率(ATR)自动选择参数
- **4 Preset Modes**: Low Vol (3/40), Normal (5/60), High Vol (7/80), Crypto (10/120)
4种预设模式:低波动/普通/高波动/加密货币,分别对应不同的回看/范围参数
- **Extreme Zone Detection**: Distinguishes divergence in extreme zones (💎) vs normal zones (↗️↘️)
极端区域检测:区分极端区域背离(💎)和普通背离(↗️↘️)
- **Bullish/Bearish Divergence**: Price lower low + RSI higher low / Price higher high + RSI lower high
看涨/看跌背离:价格新低+RSI未新低 / 价格新高+RSI未新高
### 📊 Layered Signal Statistics / 分层信号统计
- **4-Tier Classification**: MTF Resonance (🌟) > Divergence+Extreme (💎) > Extreme Only (🔥❄️) > Normal (⬆️⬇️)
四层分级:多周期共振 > 背离+极端 > 仅极端 > 普通信号
- **Independent Tracking**: Each signal tier has separate count, average return, and win rate
独立跟踪:每层信号独立统计次数、平均收益、胜率
- **Signal Cooldown**: Optional cooldown period (default 5 bars) to prevent duplicate counting
信号冷却:可选冷却期(默认5根K线)防止重复计数
- **Real Forward Testing**: Calculates actual returns N bars after signal (configurable 5-100 bars)
真实前瞻测试:计算信号后N根K线的实际收益(可配置5-100)
---
## Z-Score 与 百分位:双重视角 / Dual Perspective
This indicator displays **both Z-Score and Percentile** to provide complementary views of the same RSI distribution.
本指标**同时显示Z-Score和百分位**,为同一RSI分布提供互补视角。
### Why Both? / 为什么同时显示?
**Fundamental Connection / 本质关联**:
两者都是描述RSI在历史分布中位置的统计方法。
Both are statistical methods describing RSI's position in historical distribution.
- **Z-Score(标准分数)**: `(RSI - 均值) / 标准差` - 基于正态分布假设
Based on normal distribution assumption.
- **百分位(Percentile)**: RSI在历史数据中的排名位置 - 不假设分布类型
RSI's ranking position in historical data - no distribution assumption.
**Complementary Advantages / 互补优势**:
| Dimension 维度 | Z-Score | Percentile 百分位 |
|------|---------|------------|
| **Cross-asset Consistency / 跨资产一致性** | ✅ Excellent 优秀 - BTC和SPY都用±2σ | ⚠️ Varies by volatility 因波动率不同而异 |
| **Statistical Rigor / 统计学严谨性** | ✅ Confidence intervals 置信区间、假设检验 | ⚠️ Non-parametric 非参数统计 |
| **Intuitive / 直观易懂** | ⚠️ Stats knowledge needed 需要统计学知识 | ✅ "Below 95% of history" "低于95%历史值" |
| **Use Case / 适用场景** | 📊 Quant backtesting 量化回测、信号触发 | 📈 Visualization 可视化、用户理解 |
### Conversion Reference / 转换对照表
**Quick Reference / 快速对照**(Assuming normal distribution / 假设正态分布):
| Z-Score | Percentile 百分位 | Meaning 含义 | Signal 信号类型 |
|---------|--------|---------------|----------|
| **±2.5σ** | **P0.6 / P99.4** | Extreme anomaly (outside 99% CI) / 极端异常(99%置信区间外) | Rare opportunity 罕见机会 |
| **±2.0σ** | **P2.3 / P97.7** | Extreme OB/OS (outside 95% CI) / 极端超买/超卖(95%置信区间外) | 🔥❄️ Extreme 极端信号 |
| ±1.5σ | P6.7 / P93.3 | Notable deviation / 显著偏离 | ⬆️⬇️ Normal 普通信号(默认) |
| ±1.0σ | P15.9 / P84.1 | Mildly strong/weak / 轻度偏强/偏弱 | — |
| 0σ | P50 | Median / 中位数 | — |
### Dashboard Dual Display / 仪表盘双重显示
**新版Dashboard已实现自动转换**:
```
┌─────────────────────────────────┐
│ ADAPTIVE RSI PRO 28.5 │
├─────────────────────────────────┤
│ Z-Score −2.15σ (≈P2) │ ← Z值 + 近似百分位
│ Percentile P5 (−1.5σ ~ −2σ) │ ← 百分位 + 对应Z值范围
│ Status 🟢 EXTREME OVERSOLD │
└─────────────────────────────────┘
```
**理解方式**:
- **从Z值看**:−2.15σ 表示超过95%置信区间,统计异常 → 对应约P2
- **从百分位看**:P5 表示低于95%历史值,极端超卖 → 对应约−1.5σ到−2σ之间
### Threshold Line Modes / 阈值线模式
**Unified Mode (Recommended) / Unified模式(推荐)** - Balances rigor and intuitiveness / 兼顾严谨性和直观性:
- Draws: Z-Score threshold lines (±2σ, ±1.5σ) / 绘制:Z-Score阈值线(±2σ、±1.5σ)
- Labels: Corresponding percentiles (≈P98, ≈P93, ≈P7, ≈P2) / 标注:对应百分位(≈P98、≈P93、≈P7、≈P2)
- Advantage: Instantly understand statistical meaning and historical position / 优势:一眼看懂统计意义和历史位置
**Other Modes / 其他模式**:
- `Z-Score`: Statistical threshold lines only / 仅显示统计学阈值线
- `Percentile`: Percentile lines only / 仅显示百分位线
- `Both`: Display both types (denser) / 同时显示两类线(较密集)
### Practical Examples / 实际应用示例
**Scenario 1: Identifying Extreme Opportunities / 场景1:识别极端机会**
```
Current RSI / 当前RSI: 25.3
Dashboard shows / Dashboard显示:
Z-Score: −2.35σ (≈P1)
Percentile: P5 (< −2σ)
Status: 🟢 EXTREME OVERSOLD
Interpretation / 解读:
• Statistical perspective / 统计学视角: Beyond 99% confidence interval (|Z| > 2.3) / 超过99%置信区间,极端异常
• Intuitive perspective / 直观视角: Lower than 99% of historical values / 低于99%的历史值都低,罕见超卖
• Conclusion / 结论: Strong buy signal 🔥 / 强力买入信号 🔥
```
**Scenario 2: Normal Signal Judgment / 场景2:普通信号判断**
```
Current RSI / 当前RSI: 63.8
Dashboard shows / Dashboard显示:
Z-Score: +1.52σ (≈P94)
Percentile: P90 (+1.5σ ~ +2σ)
Status: 🟠 OVERBOUGHT
Interpretation / 解读:
• Statistical perspective / 统计学视角: ~1.5 std dev, notably high but not extreme / 约1.5倍标准差,显著偏高但未极端
• Intuitive perspective / 直观视角: Higher than 90% of historical values / 高于90%的历史值,轻度超买
• Conclusion / 结论: Consider reducing position, not forced sell ⬇️ / 考虑减仓,非强制卖出 ⬇️
```
### Dashboard Display Logic / Dashboard显示逻辑
**Z-Score Row Display / Z-Score行显示**:
- Always shows current Z-value (2 decimal places) / 始终显示当前Z值(精确到2位小数)
- Auto-calculates approximate percentile: `≈P ` / 自动计算对应的近似百分位:`≈P `
- Uses Error Function for precise conversion / 使用误差函数(Error Function)精确转换
**Percentile Row Display / Percentile行显示**:
- Shows RSI's percentile range (P5, P10, P25, etc.) / 显示RSI所处的百分位区间(P5, P10, P25等)
- Labels corresponding Z-value range (e.g., `−1.5σ ~ −2σ`) / 标注对应的Z值范围(如:`−1.5σ ~ −2σ`)
- Helps understand what "P10" means statistically / 帮助理解"P10"的统计意义
**Color Association / 颜色关联**:
- Both rows use same status color (green/yellow/white/orange/red) / 两行使用相同的状态颜色(绿/黄/白/橙/红)
- Visually reinforces "same indicator, different expressions" / 视觉上强化"同一指标的不同表达"概念
---
### Dashboard Setups / 仪表盘配置
#### Full Mode (PC/Tablet)
Shows detailed stats, MTF status, and divergence info.
显示详细统计、MTF状态和背离信息。
#### Mobile Mode (Phone) / 手机模式
Simplified 3-row layout optimized for small screens.
极简3行布局,专为手机屏幕优化。
- Row 1: RSI Value / 第1行:RSI数值
- Row 2: Signal Status (Emoji) / 第2行:信号状态 (Emoji)
- Row 3: Trend/Filter Status / 第3行:趋势/过滤状态
### 📈 Dashboard Example / 面板示例
```
┌─────────────────────────────────┐
│ ADAPTIVE RSI PRO 35.2 │
├─────────────────────────────────┤
│ Status 🟢 EXTREME OVERSOLD │
│ Percentile P10 ↓ DOWN │
│ Lookback 456 ✅✅✅ │
├─────────────────────────────────├ (Full Mode Only)
│ ── MTF ── │
│ 1h | 4h | D 🟢 | ⚪ | 🟢 │
│ Resonance 🟢 3/4 OVERSOLD │
├─────────────────────────────────┤
│ Divergence 🟢 BULL (5/60) │
├─────────────────────────────────┤
│ ── STATS ── (20 bars) │
│ 🌟 MTF Buy(12) +4.2% | 83% │
│ 🌟 MTF Sell(8) +3.8% | 75% │
│ 💎 Div Buy(15) +3.5% | 80% │
│ 💎 Div Sell(11) +2.9% | 73% │
│ 🔥 Ext Buy(45) +2.1% | 67% │
│ ❄️ Ext Sell(38) +1.8% | 63% │
└─────────────────────────────────┘
```
**Health Indicators / 健康度指标**:
- ✅✅✅ = All healthy (所有健康): Sample coverage ≥ 80%, Distribution spread ≥ 15, Statistical validity ≥ 90%
- ⚠️ present = Warning (警告): One or more health checks failed, consider using Custom mode with larger lookback
---
## Chart Lines Guide / 图表线条指南
! (images/annotated_rsi_indicator.png)
### 📊 主要线条 / Main Lines
| 线条 | 颜色/样式 | 含义 | 作用 |
|------|----------|------|------|
| **RSI主线** | 黄色粗线 | 当前RSI值 | 实时跟踪相对强弱指标 |
| **P50 自适应中位数** | 白色阶梯线 | 动态中线 | 根据历史数据自动调整的中位数,比固定50更准确 |
### 🔴 超买阈值线 / Overbought Thresholds (上方红色)
| 线条 | Z-Score | 百分位 | 样式 | 信号 |
|------|---------|--------|------|------|
| **极端超买线** | +2σ | ≈P98 | 实线 | 触发 ❄️ 极端超买信号(强卖出) |
| **普通超买线** | +1.5σ | ≈P93 | 圆点虚线 | 触发 ⬇️ 普通超买信号(考虑卖出) |
### 🟢 超卖阈值线 / Oversold Thresholds (下方绿色)
| 线条 | Z-Score | 百分位 | 样式 | 信号 |
|------|---------|--------|------|------|
| **极端超卖线** | -2σ | ≈P2 | 实线 | 触发 🔥 极端超卖信号(强买入) |
| **普通超卖线** | -1.5σ | ≈P7 | 圆点虚线 | 触发 ⬆️ 普通超卖信号(考虑买入) |
### ⚪ 固定参考线 / Fixed Reference Lines
| 线条 | 位置 | 样式 | 作用 |
|------|------|------|------|
| **0线** | 底部 | 灰色点线 | RSI下边界 |
| **50线** | 中间 | 灰色点线 | 传统固定中线参考 |
| **100线** | 顶部 | 灰色点线 | RSI上边界 |
### 🎨 渐变填充区域 / Gradient Fill Zones
- **红色渐变**(上方):超买区域,颜色越深表示越极端
- P95-P90(深红)> P90-P75(中红)> P75-P50(浅红)
- **绿色渐变**(下方):超卖区域,颜色越深表示越极端
- P10-P5(深绿)> P25-P10(中绿)> P50-P25(浅绿)
### 💡 关键要点 / Key Points
**线条样式区分 / Line Style Distinction:**
- **实线** = 极端信号(±2σ),优先级高,统计上95%置信区间外
- **圆点虚线** = 普通信号(±1.5σ),优先级较低,显著偏离但未极端
**动态 vs 固定 / Dynamic vs Fixed:**
- **彩色线**(红/绿)= 根据历史波动动态调整,适应不同资产特性
- **灰色虚线** = 固定不变的参考线,用于传统RSI对比
**视觉层次 / Visual Hierarchy:**
- 线条粗细:RSI主线(最粗)> 极端阈值(粗)> 普通阈值(细)> 参考线(最细)
- 透明度:核心线条(不透明)> 百分位线(半透明)> 填充区(高透明)
---
## Settings / 设置
### RSI Settings / RSI设置
| Setting | Default | Description |
|---------|---------|-------------|
| RSI Length | 14 | RSI calculation period / RSI计算周期 |
| RSI Source | Close | Price source / 价格源 |
### Adaptive Settings / 自适应设置
| Setting | Default | Description |
|---------|---------|-------------|
| Lookback Mode | Auto | Auto (statistical formula) / Custom / 自动/自定义 |
| Custom Lookback | 252 | Only used in Custom mode / 仅自定义模式使用 |
| Precision | Normal | High/Normal/Low: Adjusts error tolerance / 精度等级 |
| History Depth | 1 Year | 6 Months / 1 Year / 2 Years for volatility calculation / 波动率历史深度 |
### Visual Settings / 视觉设置
| Setting | Default | Description |
|---------|---------|-------------|
| Threshold Line Mode | **Unified** | Unified(推荐)/Z-Score/Percentile/Both / 阈值线模式 |
| Show Gradient Fill | ON | Display background gradients / 显示背景渐变 |
| Show Dashboard | ON | Display dashboard panel / 显示仪表盘面板 |
| Dashboard Mode | Full | Full/Lite/Mobile(Phone) / 面板模式 |
| Dashboard Size | Normal | Tiny/Small/Normal/Large / 面板大小 |
| Dashboard Transparency | 30 | 0-100% transparency level / 透明度 |
| Bullish Color | #00E676 | Custom color for bullish signals / 牛市信号颜色 |
| Bearish Color | #FF5252 | Custom color for bearish signals / 熊市信号颜色 |
| RSI Line Color | #FFEB3B | RSI line color / RSI主线颜色 |
### Trend Filter / 趋势过滤
| Setting | Default | Description |
|---------|---------|-------------|
| Enable Trend Filter | OFF | Only trigger signals in trend direction / 趋势方向过滤 |
| Filter Mode | Auto | Auto/Fixed 50/Adaptive P50/SMA(RSI)/BB(RSI) / 过滤模式 |
### Alert Settings / 警报设置
| Setting | Default | Description |
|---------|---------|-------------|
| **🎯 Smart Alert** | **ON** | **V6 Unified Alert System** / V6统一警报系统 |
| Show Normal Signals | OFF | Display ⬆️⬇️ on chart / 图表显示普通信号 |
| Normal Signal Threshold | 1.5σ | Z-Score threshold (1.0-2.0σ) / 普通信号阈值 |
| Enable Signal Cooldown | ON | Prevent duplicate signal counting / 防止重复信号 |
| Cooldown Period | 5 bars | Bars between same signal type / 冷却K线数 |
### Multi-Timeframe / 多时间框架
| Setting | Default | Description |
|---------|---------|-------------|
| Enable | ON | Show MTF analysis / 显示MTF分析 |
| MTF Mode | **Auto** | **Auto** (Fractal Breakdown) / **Manual** (Fixed) / 自动/手动模式 |
| TF1/TF2/TF3 | 60/240/D | Timeframes (Manual mode only) / 时间框架(仅手动模式)|
### Signal Statistics / 信号统计
| Setting | Default | Description |
|---------|---------|-------------|
| Enable | ON | Track performance / 跟踪表现 |
| Forward Bars | 20 | Bars for return calculation / 收益计算K线数 |
### Divergence Detection / 背离检测
| Setting | Default | Description |
|---------|---------|-------------|
| Enable Detection | ON | Detect divergences / 检测背离 |
| Divergence Mode | Auto | Auto/Low Vol/Normal/High Vol/Crypto/Custom / 背离模式 |
| Custom Lookback | 5 | Only in Custom mode / 仅自定义模式使用 |
| Custom Range | 60 | Only in Custom mode / 仅自定义模式使用 |
**Auto Mode Presets / 自动模式预设**:
- Low Vol (蓝筹/ETF): Lookback 3, Range 40
- Normal (一般股票): Lookback 5, Range 60
- High Vol (成长股): Lookback 7, Range 80
- Crypto (加密货币): Lookback 10, Range 120
---
## Alerts / 警报
### 🎯 Smart Alert (V6 Unified System)
**The only alert method / 唯一的警报方式** - 自动聚合所有信号到一条富文本消息
Automatically aggregates all signals into a single rich-text message.
**Setup Steps / 设置方法**:
1. Keep "🎯 Smart Alert" enabled in indicator settings (default) / 指标设置中保持 "🎯 Smart Alert" 开启(默认)
2. When creating alert, select **"Any alert() function call"** / 创建警报时选择 **"Any alert() function call"**
3. Done! You'll receive real-time aggregated alerts / 完成!您会收到实时的聚合警报
**Message Example / 消息示例**:
```
AAPL: 🟢 BUY SIGNALS → 🌟MTF共振 💎背离 🔥极端 | RSI:25.3 Z:-2.1σ (≈P2)
AAPL: 🔴 SELL SIGNALS → ❄️极端 | RSI:78.5 Z:2.3σ (≈P98)
```
**Features / 特性**:
- ✅ **Real-time trigger / 实时触发** - Sends when condition met within bar / K线运行中触发条件即发送
- ✅ **Anti-flicker / 防闪烁** - Uses `varip` to prevent duplicate alerts from signal flickering within same bar / 使用 `varip` 防止信号闪烁导致同一K线内重复警报
- ✅ **Signal upgrade detection / 信号升级检测** - Alerts when stronger signal appears (e.g., 🔥Extreme → 🌟MTF) even on same bar / 同一K线内出现更强信号时也会触发(如:🔥极端 → 🌟MTF共振)
- ✅ **Full context / 完整上下文** - Includes RSI value, Z-Score, approximate percentile / 包含RSI值、Z-Score、近似百分位
- ✅ **Auto-aggregation / 自动聚合** - One message contains all triggered signals / 一条消息包含所有触发的信号
- ✅ **Buy/Sell independent tracking / 买卖独立追踪** - Buy and Sell alerts tracked separately / 买入和卖出警报独立追踪,互不干扰
**Signal Priority Levels / 信号优先级**:
| Level 等级 | Signal 信号 | Description 描述 |
|------------|-------------|------------------|
| 4 (Highest) | 🌟 MTF Resonance | Multi-timeframe agreement / 多周期共振 |
| 3 | 💎 Divergence | Divergence + Extreme zone / 背离+极端区 |
| 2 | 🔥❄️ Extreme | Extreme oversold/overbought / 极端超卖/超买 |
| 1 (Lowest) | ⬆️⬇️ Normal | Normal oversold/overbought / 普通超卖/超买 |
---
## Usage Tips / 使用建议
| Timeframe | Lookback | Use Case |
|-----------|----------|----------|
| Daily | 252 | Swing trading / 波段交易 |
| 4H | 1000 | Short-term / 短线 |
| 1H | 2000 | Day trading / 日内交易 |
**Best Practices / 最佳实践:**
1. Focus on 🌟 and 💎 signals (highest priority) / 优先关注 🌟 和 💎 信号(最高优先级)
2. Use MTF resonance for high-confidence entries / 使用 MTF 共振确认高置信度入场
3. Check win rate in stats before trading / 交易前查看统计胜率
---
## Changelog / 更新日志
### v6.2 - Smart Alert Anti-Flicker / 智能防抖警报 (Current / 当前版本)
- 🛡️ **Anti-flicker Mechanism / 防闪烁机制**: Fixed issue where signal flickering caused multiple duplicate alerts within same bar. Now uses `varip` to track alert status per bar. / 修复信号闪烁导致同一K线内发送多次重复警报的问题,使用 `varip` 追踪每根K线的警报状态。
- 📈 **Signal Upgrade Detection / 信号升级检测**: Tracks signal priority level (MTF=4, Divergence=3, Extreme=2, Normal=1). Sends new alert when stronger signal appears on same bar. / 追踪信号优先级等级。同一K线内出现更强信号时会发送新警报。
- 🔄 **Independent Buy/Sell Tracking / 买卖独立追踪**: Buy and Sell alerts are tracked independently, allowing direction changes within same bar. / 买入和卖出警报独立追踪,允许同一K线内捕捉方向变化。
### v6.1 - Mobile Experience / 移动端体验
- 📱 **Mobile Dashboard / 手机端面板**: Added simplified "Mobile" mode optimized for phone screens (RSI + Signal Emoji only). / 新增简化的"Mobile"模式,针对手机屏幕优化(仅显示RSI+信号Emoji)。
- 🔥 **Persistent Zone Status / 持续区域状态**: Mobile Dashboard now shows persistent extreme zone indicators when no new signal but RSI remains in zone: `🔥持续` (Extreme Oversold), `❄️持续` (Extreme Overbought), `⬆️区` (Oversold), `⬇️区` (Overbought). / 手机端面板现在显示持续极端区域指示器:无新信号但RSI仍在区域内时显示持续状态。
- 🔧 **UX Improvements / 用户体验优化**: Optimized font sizes and layout for small screens. / 优化字体大小和小屏幕布局。
### v6.0 - Alert System Simplification & V6 Optimization / 警报系统简化与V6优化
- 🎯 **Smart Alert System / 智能警报系统简化**:
- **Unified entry / 唯一警报入口**: Removed all legacy alertcondition, unified to V6 Smart Alert / 移除所有legacy alertcondition,统一为V6 Smart Alert
- **Real-time trigger / 实时触发**: Changed to `alert.freq_once_per_bar` for intra-bar response / 改为 `alert.freq_once_per_bar` 实现K线内实时响应
- **Smart dedup / 智能去重**: Rising edge detection (`signal and not signal `) / 上升沿检测,只在新信号出现时触发
- **Auto-aggregation / 自动聚合**: Single message with all signals + RSI + Z-Score + Percentile / 单条消息包含所有触发信号 + RSI + Z-Score + 百分位
- **Simplified settings / 简化设置**: Removed "Extreme Alerts" and "Normal Alerts", only Smart Alert toggle / 移除 "Extreme Alerts" 和 "Normal Alerts",只保留Smart Alert开关
- 🛠 **Performance Optimization / 性能优化**:
- Reduced `request.security` calls by 50% using Tuple Requests / 使用元组请求减少50%的`request.security`调用
- Implemented `str.format()` for cleaner and faster string processing / 实现`str.format()`使字符串处理更简洁高效
- 🧹 **Code Cleanup / 代码清理**:
- Refactored timeframe display and alert logic / 重构时间框架显示和警报逻辑
- Fixed plot limit issues and tuple assignment syntax / 修复绑点限制问题和元组赋值语法
- Unified plot titles with percentile annotations / 统一绑点标题与百分位标注
### v5.0 - Adaptive Fractal MTF / 自适应分形MTF
- 🧠 **Adaptive Fractal MTF / 自适应分形MTF**: New "Auto" mode automatically selects lower timeframes for precision structure analysis (Internal Fractal Resonance). / 新增"Auto"模式,自动选择更低时间框架进行精确结构分析(内部分形共振)。
- Daily Chart → Analyzes 1H & 4H / 日线图 → 分析1小时和4小时
- 1H Chart → Analyzes 5m & 15m / 1小时图 → 分析5分钟和15分钟
- 15m Chart → Analyzes 1m & 5m / 15分钟图 → 分析1分钟和5分钟
- 🛠 **Code Refactoring / 代码重构**: Implemented Pine Script v6 UDTs (Objects) and Methods for robust signal statistics. / 实现Pine Script v6 UDT(对象)和方法,增强信号统计的健壮性。
- 🎨 **Dashboard Optimization / 面板优化**: Enhanced string formatting using `str.format` for cleaner display. / 使用`str.format`优化字符串格式,显示更简洁。
### v4.0 - Pine Script v6 Upgrade / Pine Script v6升级
- 🚀 Upgraded entire codebase to **Pine Script v6** engine / 将整个代码库升级到 **Pine Script v6** 引擎
- ⚡ Optimization for better performance and future-proofing / 性能优化,面向未来
- 🛠 Maintenance updates for latest TradingView standards / 维护更新以符合最新TradingView标准
### v3.0 - Auto-Adaptive Systems / 自动自适应系统
- ✨ Auto-adaptive lookback using formula `n = (Z × σ / E)²` / 使用统计公式 `n = (Z × σ / E)²` 自动计算回看期
- ✨ Auto-adaptive trend filter with 5 modes / 5种模式的自动自适应趋势过滤器
- ✨ Auto-adaptive divergence detection with 4 presets / 4种预设的自动自适应背离检测
- ✨ Layered statistics (MTF/Divergence/Extreme/Normal) / 分层统计系统(MTF/背离/极端/普通)
- ✨ Signal cooldown to prevent duplicate counting / 信号冷却机制防止重复计数
- ✨ Health indicators for lookback validation / 回看期健康度指标验证
- ✨ Dashboard modes (Lite/Full) with customization / 面板模式(Lite/Full)支持自定义大小和透明度
- ✨ Dual volatility system (short + long-term) / 双重波动率系统(短期+长期)
### v2.1 - Signal Optimization / 信号优化
- ✨ Consolidated signals with priority system / 信号合并与优先级系统(无重叠)
- ✨ Emoji-based signal display / 基于Emoji的信号显示
- ✨ MTF timeframe auto-skip for duplicates / MTF时间框架自动跳过重复
### v2.0 - Pro Edition / 专业版
- ✨ Added Trend Filter, MTF RSI, Statistics, Divergence / 新增趋势过滤、MTF RSI、统计、背离检测
- ✨ Z-Score based signal triggering / 基于Z-Score的信号触发
### v1.0 - Initial Release / 初始发布
- ✨ Adaptive percentile-based thresholds / 自适应百分位阈值
---
## License
MIT License - Feel free to use, modify, and share.
Goldilocks Regime FilterGoldilocks Regime Filter is a lightweight market condition confirmation indicator engineered specifically for 1-minute Gold scalping.
Rather than generating trade signals, this tool focuses on identifying the current market regime—helping traders quickly determine whether price action is behaving in a directional (trending) or rotational (ranging) manner. This allows traders to align their existing entry strategies with appropriate market conditions and avoid applying momentum tactics in unfavorable environments.
The indicator synthesizes multiple aspects of market behavior—trend strength, volatility behavior, and price efficiency—into a simple, intuitive top-right table with a clear regime label and confidence reading. This makes it easy to assess market state at a glance without adding clutter to the chart.
Key Features
Designed specifically for 1-minute Gold charts
Clear Trending / Ranging / Neutral regime classification
Confidence score to gauge strength of the current condition
Non-repainting, confirmation-only logic
Minimalist table display that stays out of the way
Works alongside any strategy or discretionary approach
Intended Use
This indicator is designed to be used as a confirmation filter, not a standalone trading system. It is best applied to:
Confirm momentum-based setups during directional conditions
Avoid overtrading during low-efficiency, rotational markets
Improve discipline and context during fast intraday sessions
Goldilocks Regime Filter does not provide buy or sell signals and should be used in conjunction with proper risk management and a defined trading plan.
TTM Squeeze Candles (Custom Colors) with Dynamic Strength BarHere is my tribute, tip of the cap to one of the greatest traders of our generation John F. Carter
It was my goal to try and simply visualize the squeeze with candle sticks, dynamic momentum, and signals all on one chart in one indicator. Please study and master the squeeze setup before trying to apply this indicator . You must have a deep understanding of how to trade the squeeze. Read "Mastering The Trade " watch JC's videos etc, and practice with a simulated or paper account before ever trying out new strategies with real money. Not financial advice, I am not a financial advisor! DYOR- with that said - I hope you like it :)
TTM squeeze candles **custom TradingView Pine Script (v6)** indicator that visualizes the **TTM Squeeze** strategy — a popular volatility-based momentum system originally developed by John Carter of TradeTheMarkets (TTM). This version enhances the classic TTM Squeeze with **custom candle coloring**, **dynamic momentum strength**, **visual alerts**, and a **real-time strength meter**.
---
## OVERVIEW: What is the TTM Squeeze?
The **TTM Squeeze** identifies periods when **volatility is contracting** (price is consolidating), followed by a **potential explosive breakout** when volatility expands.
It combines:
1. **Bollinger Bands (BB)** – measure statistical volatility
2. **Keltner Channels (KC)** – measure average true range (ATR) volatility
3. **Momentum Oscillator** – determines direction and strength of potential breakout
> **Squeeze ON** = BB inside KC → Low volatility (consolidation)
> **Squeeze OFF** = BB outside KC → Volatility expanding (breakout possible)
## BEST USED ON
- **Timeframes**: 15m, 1H, 4H, Daily
- **Markets**: Stocks, Forex, Crypto, Futures
- **Pairs well with**: Volume, VWAP, Support/Resistance
---
## SUMMARY
> **This is a highly visual, trader-friendly squeeze candle indicator that:
> - **Colors candles** based on squeeze state and momentum strength
> - **Shows real-time momentum intensity** via histogram + strength bar
> - **Alerts on squeeze start/release**
> - **Normalizes momentum** for fair strength comparison
> - **Provides clean, actionable signals** for breakout trading
---
**Ideal for swing traders and day traders** looking to catch **high-momentum breakouts from low-volatility consolidations** with **clear entry signals and conviction levels**.
ADX Coloreado por AO + DI DifferenceKey ComponentsADX line: Measures overall trend strength (non-directional).
+DI line: Strength of upward movement.
-DI line: Strength of downward movement.
Trend direction is determined by which DI line is dominant:+DI > -DI: Bullish trend (upward pressure).
-DI > +DI: Bearish trend (downward pressure).
Crossovers between +DI and -DI can signal potential trend changes, but they are most reliable when ADX confirms sufficient strength.ADX Trend Strength Levels (Common Interpretations)ADX Value
Trend Strength
Recommendation
0–20
Weak or no trend (ranging/sideways market)
Avoid trend-following strategies; consider range-bound or oscillator-based trades.
20–25
Emerging or moderate trend (gray zone)
Monitor for confirmation; potential start of trend.
25–50
Strong trend
Ideal for trend-following strategies (e.g., moving averages, breakouts).
50–75
Very strong trend
High momentum; good for riding trends, but watch for exhaustion.
75–100
Extremely strong trend (rare)
Often overextended; risk of reversal or correction.
Rising ADX: Trend is strengthening.
Falling ADX: Trend is weakening (even if still high).
Session HeatmapIntraday Seasonality
Overview
Analyzes historical patterns by time of day. Identifies when volatility, volume, and open interest changes tend to be highest or lowest.
Features
Multiple Metrics: TR (volatility), Volume, and Open Interest changes
Flexible Grouping: View patterns by weekday or month to spot day-of-week or seasonal effects
Heatmap Visualization: Blue (low) to Red (high) color scale for quick pattern recognition
Percentile Mode: Reduces outlier impact by using 5th-95th percentile range
Timezone Support: Display in UTC alongside your local time
Metrics Explained
TR: Volatility - when markets move most
Volume: Liquidity - when participation is highest
OI Increase: When new positions are opened
OI Decrease: When positions are closed
OI Net: Net open interest change
Usage
Set your timezone and preferred slot size (30min/1H)
Choose a date range (relative or custom)
Select a metric to analyze
Use "Group By" to see weekday or monthly patterns
Switch to Percentile color scale if outliers dominate
Notes
Chart timeframe should be equal to or smaller than Slot Size
OI metrics require Binance Perpetual symbols
DST is not automatically adjusted; consider seasonal shifts for US/EU sessions
Session ATR Progression Tracker📊 Session ATR Progression Tracker - SIYL Regression Trading Tool
Track how much of your instrument's 7-day Average True Range (ATR) has been covered during the current trading session. This indicator is specifically designed for regression traders who follow the "Stay In Your Lane" (SIYL) methodology, helping you identify when the probability of mean reversion significantly increases. If you are interested in more on that check out Rod Casselli and tradersdevgroup.com.
🎯 Key Features:
• Real-time ATR Coverage Percentage - See at a glance what percentage of the 7-day ATR has been covered in the current session
• SIYL-Optimized Thresholds - See at a glance when the instrument has achieved 80% and 100% ATR coverage, the proven thresholds where mean reversion probability increases (customizable)
• Flexible Session Modes:
- Daily: Resets at calendar day change
- Session: Uses exchange-defined trading sessions
- Custom Session: Set your exact session start/end times (perfect for futures traders and international markets)
• Visual Alerts - Color-coded display (gray → orange → red) and optional background highlighting
• Repositionable Display - Choose from 9 screen positions to avoid chart clutter
• Session Markers - Green triangles mark the start of each new session
• Detailed Stats - View current range, ATR value, session high/low, and session status
💡 Why Use This Indicator?
This tool is built around a proven concept: regression trading becomes significantly more effective once a session has achieved at least 80% of its 7-day ATR. At this threshold, the probability of price reverting to mean increases substantially, creating higher-probability trade setups for SIYL practitioners.
Benefits for regression traders:
- Identify optimal entry points when mean reversion probability is highest (≥80% ATR coverage)
- Avoid premature regression entries before adequate range has been established
- Recognize when daily moves have "earned their range" and are ripe for reversal
- Time fade-the-move and counter-trend strategies with statistical backing
- Improve win rates by trading only after proven probability thresholds are met
⚙️ Setup Instructions:
1. Add the indicator to your chart
2. Select your preferred "Reset Mode" (recommend "Custom Session" for futures/international markets)
3. If using Custom Session, enter your session times in 24-hour format (e.g., 0930-1600 for US stocks, 1700-1600 for CME futures)
4. Adjust alert thresholds if desired (default: 80% and 100% - proven SIYL thresholds)
5. Position the display where it's most visible on your chart
📈 Works Across All Markets:
Stocks • Futures • Forex • Indices • Crypto • Commodities
Perfect for regression traders, mean reversion specialists, and SIYL practitioners who want to trade with probability on their side by entering only after the session has "earned its range."
---
Tip: For futures contracts with overnight sessions that span calendar days (like MES, MNQ, MYM), use "Custom Session" mode with your exchange's official session times for accurate tracking.
Bollinger Bands Forecast with Signals (Zeiierman)█ Overview
Bollinger Bands Forecast with Signals (Zeiierman) extends classic Bollinger Bands into a forward-looking framework. Instead of only showing where volatility has been, it projects where the basis (midline) and band width are likely to drift next, based on recent trend and volatility behavior.
The projection is built from the measured slopes of the Bollinger basis, the standard deviation (or ATR, depending on the mode), and a volatility “breathing” component. On top of that, the script includes an optional projected price path that can be blended with a deterministic random walk, plus rejection signals to highlight failed band breaks.
█ How It Works
⚪ Bollinger Core
The script first computes standard Bollinger Bands using the selected Source, Length, and Multiplier:
Basis = SMA(Source, Length)
Band width = Multiplier × StDev(Source, Length)
Upper/Lower = Basis ± Width
This remains the “live” (non-forecast) structure on the chart.
⚪ Trend & Volatility Slope Estimation
To project forward, the indicator measures directional drift and volatility drift using linear regression differences:
Basis slope from the Bollinger basis
StDev slope from the Bollinger deviation
ATR slope for ATR-based projection mode
These slopes drive the forecast bands forward, reflecting the market’s recent directional and volatility regime.
⚪ Projection Engine (Forecast Bands)
At the last bar, the indicator draws projected basis, upper, and lower lines out to Forecast Bars. The projected basis can be:
Trend (straight linear projection)
Curved (ease-in/out transition toward projected endpoints)
Smoothed (extra smoothing on projected basis/width)
⚪ Price Path Projection + Optional Random Walk
In addition to projecting the bands, the script can draw a price forecast path made of a small number of zigzag swings.
Each swing targets a point offset from the projected basis by a multiple of the projected half-width (“width units”).
Decay gradually reduces swing size as the forecast deepens.
The Optional Random Walk Blend adds a deterministic drift component to the zigzag path. It’s not true randomness; it’s a stable pseudo-random sequence, so the drawing doesn’t jump around on refresh, while still adding “natural” variation.
⚪ Rejection Signals
Signals are based on failed attempts to break a band:
Bear Signal (Down): price tries to push above the upper band, then falls back inside, while still closing above the basis.
Bull Signal (Up): price tries to push below the lower band, then returns back inside, while still closing below the basis.
█ How to Use
⚪ Forward Support/Resistance Corridors
Treat the projected upper/lower bands as a future volatility envelope, not a guarantee:
The upper projection ≈ is likely a resistance level if the regime persists
The lower projection ≈ is likely a support level if the regime persists
Best used for trade planning, targets, and “where price could travel” under similar conditions.
⚪ Regime Read: Trend + Volatility
The projection shape is informative:
Rising basis + expanding width → trend with increasing volatility (needs wider stops / more caution)
Flat basis + compressing width → contraction regime (often precedes expansion)
⚪ Signals for Mean-Reversion / Failed Breakouts
The rejection markers are useful for fade-style setups:
A Down signal near/after upper-band failure can imply rotation back toward the basis.
An Up signal near/after lower-band failure can imply snap-back toward the basis.
With MA filtering enabled, signals are constrained to align with the broader bias, helping reduce chop-driven noise.
█ Related Publications
Donchian Predictive Channel (Zeiierman)
█ Settings
⚪ Bollinger Band
Controls the live Bollinger Bands on the chart.
Source – Price used for calculations.
Length – Lookback period; higher = smoother, lower = more reactive.
Multiplier – Bandwidth; higher = wider bands, lower = tighter bands.
⚪ Forecast
Controls the forward projection of the Bollinger Bands.
Forecast Bars – How far into the future the bands are projected.
Trend Length – Lookback used to estimate trend and volatility slopes.
Forecast Band Mode – Defines projection behavior (linear, curved, breathing, ATR-based, or smoothed).
⚪ Price Forecast
Controls the projected price path inside the bands.
ZigZag Swings – Number of projected oscillations.
Amplitude – Distance from basis, measured in bandwidth units.
Decay – Shrinks swings further into the forecast.
⚪ Random-Walk
Adds controlled randomness to the price path.
Enable – Toggle random-walk influence.
Blend – Strength of randomness vs. zigzag.
Step Size – Size of random steps (band-width units).
Decay – Reduces randomness as the forecast deepens.
Seed – Changes the (stable) random sequence.
⚪ Signals
Controls rejection/mean-reversion signals.
Show Signals – Enable/disable signal markers.
MA Filter (Type/Length) – Filters signals by trend direction.
-----------------
Disclaimer
The content provided in my scripts, indicators, ideas, algorithms, and systems is for educational and informational purposes only. It does not constitute financial advice, investment recommendations, or a solicitation to buy or sell any financial instruments. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
HAR Volatility ATR (Multi-Asset) - Andreus VillalobosIndicator based on the HAR (Hyper-Realized Volatility) model.
Combines daily, weekly, and monthly ATRs to project:
– Most probable price range (90%)
– Most probable take profit (60%)
Does not generate entry signals.
Designed for use in conjunction with:
market structure, liquidity, and price action.
Works on Forex, Indices, Gold, and Cryptocurrencies.
HAR Volatility ATR v1.0 (Andreus Villalobos)
Indicator based on the HAR (Hyper-Realized Volatility) model.
Combines daily, weekly, and monthly ATRs to project:
– Most probable price range (90%)
– Most probable take profit (60%)
Does not generate entry signals.
Designed for use in conjunction with:
market structure, liquidity, and price action.
Works on Forex, Indices, Gold, and Cryptocurrencies.
Renko Average Bricks This indicator calculates the average RENKO brick streaks. Streaks=consecutive bricks of the same color. EX. G= 1 streak of 1. GGG = 1 streak of 3. RR 1 streak of 2. Single bricks count. There is the option for look back period which can be changed but Defaults to 50. Calculates the last 50 completed green streaks and then averages them. Same with red streaks. Only closed bricks count.
Very Simple and can be used for targets, ect.
Cheers
TRV & nTRV - Trimmed Range VolatilityGrid bots require stable volatility measurement - ATR becomes misleading when gaps and sudden spikes distort the average. TRV (Trimmed Range Volatility) is an advanced version of ATR: it filters outliers at the extremes (highest and lowest ranges) and remains unaffected by gaps. This provides real-time, accurate volatility measurement for grid bot setup.Grid bots require stable volatility measurement - ATR becomes misleading when gaps and sudden spikes distort the average. TRV (Trimmed Range Volatility) is an advanced version of ATR: it filters outliers at the extremes (highest and lowest ranges) and remains unaffected by gaps. This provides real-time, accurate volatility measurement for grid bot setup.
Why We Developed TRV?
When a gap or sudden spike occurs in the morning, this extreme movement affects standard ATR calculations for an extended period. Even if the price moves sideways for the rest of the day, ATR remains elevated. This causes grid bots to operate with unnecessarily wide spacing and execute fewer trades.
TRV Advantages:
✅ Unaffected by Gaps: Opening gaps don't distort the calculation
✅ Extreme Point Elimination: Filters the largest and smallest outlier candles
✅ Real-Time Accuracy: Shows current market volatility
✅ Grid Bot Optimization: Enables tighter and more efficient grid spacing
✅ Comparison Capability: Compare different stocks and timeframes with nTRV
Grid Bot Usage:
The TRV value is used directly to calculate the number of grid lines:
(Resistance - Support) / TRV = Number of Grid Lines
Example:
Resistance: $110
Support: $90
TRV: $2
Grid Count: (110-90)/2 = 10 grid lines
Features:
Two Filtering Modes: Manual (enter number) or Percentage-Based (automatic ratio)
Four Indicators in One: nTRV, TRV, ATR, and nATR all displayed on the same panel
nTRV: Normalized value (percentage-based, for stock comparison)
TRV: Absolute value (currency-based, for grid calculation)
ATR & nATR Included: Standard ATR and nATR for direct comparison with TRV
Comprehensive Analysis: Compare filtered (TRV) vs unfiltered (ATR) volatility side-by-side
Default: 10% top, 10% bottom outlier elimination
Conclusion:
TRV is an advanced version of ATR specifically designed for grid bot traders. By filtering outlier movements, it provides more stable and reliable volatility measurement. The indicator includes both TRV (filtered) and ATR (unfiltered) on the same chart, giving traders a comprehensive view to make informed decisions. This dual-display approach enables more efficient grid strategies and increased trading frequency.
GARCH Volume Volatility [MarkitTick]Title: GARCH Volume Volatility
Description
Overview
The GARCH Volume Volatility (GV) indicator is a sophisticated quantitative tool designed to analyze the rate of change in market participation. While the vast majority of technical indicators focus on Price Volatility (how much price moves), this script focuses on Volume Volatility (how unstable the participation is).
Market volume is rarely distributed evenly; it tends to cluster. Periods of high activity are often followed by more high activity, and periods of calm tend to persist. This behavior is known as "heteroskedasticity." This script utilizes an Exponentially Weighted Moving Average (EWMA) model—a core component of Generalized Autoregressive Conditional Heteroskedasticity (GARCH) frameworks—to model these changing variance regimes.
By isolating volume volatility from raw volume data, this tool helps traders distinguish between sustainable liquidity flows and erratic, unsustainable volume shocks that often precede market reversals or breakouts.
Methodology and Calculations
1. Logarithmic vs. Percentage Returns
The foundation of this indicator is the calculation of "Volume Returns"—the period-over-period change in volume.
- The script defaults to Logarithmic Returns. In financial statistics, log returns are preferred because they normalize data that can vary wildly in magnitude (such as cryptocurrency volume spikes), providing a more symmetric view of changes.
- Users can opt for standard percentage changes if they prefer a linear approach.
2. Variance Proxy (Squared Returns)
To measure volatility, the direction of the volume change (up or down) matters less than the magnitude. The script squares the returns to create a "Variance Proxy." This ensures that a massive drop in volume is treated with the same statistical weight as a massive spike in volume—both represent a significant change in the volatility of participation.
3. GARCH-Style Smoothing (EWMA)
Standard Moving Averages (SMA) treat all data points in the lookback period equally. However, volatility is dynamic. This script uses an EWMA model with a tunable "Lambda" (Decay Factor).
- The Recursive Formula: The current calculation relies on a weighted average of the current variance and the previous period's smoothed variance.
- Memory Effect: This allows the indicator to "remember" recent volatility shocks while gradually letting their influence fade. This mimics the GARCH process of conditional variance.
4. Dynamic Statistical Thresholds
The final output is the Volatility (square root of variance). To make this data actionable, the script calculates a dynamic upper and lower limit based on the standard deviation (Z-Score) of the volatility itself over a user-defined lookback period.
How to Use
The indicator plots a histogram that categorizes the market into four distinct volatility regimes:
1. High Volatility (Red Histogram)
Trigger: Volatility > High Band (Upper Standard Deviation).
Interpretation: This signals an extreme anomaly in volume stability. This is not just "high volume," but "erratic volume behavior." This often occurs at:
- Capitulation bottoms (panic selling).
- Euphoric tops (blow-off tops).
- Major news events or earnings releases.
2. Elevated Volatility (Maroon Histogram)
Trigger: Volatility > Mean Average.
Interpretation: The market is in an active state. Participation is changing rapidly, but within statistically normal bounds. This is common during healthy, trending moves where new participants are entering the market steadily.
3. Normal/Low Volatility (Green Histogram)
Trigger: Volatility is within the lower bands.
Interpretation: The market volume is stable. There are no sudden shocks in participation. This is typical of consolidation phases or "creeping" trends where the price drifts without significant volume conviction.
4. Extremely Low Volatility (Bright Green/Transparent)
Trigger: Volatility < Low Band.
Interpretation: The "calm before the storm." When volume volatility collapses to near-zero, it implies that the market has reached a state of equilibrium or disinterest. Historically, volatility is cyclical; periods of extreme compression often lead to violent expansion.
Settings and Configuration
Core Settings
- Use EWMA: When checked (Default), uses the recursive GARCH-style calculation. If unchecked, it reverts to a simple SMA of variance, which is less sensitive to recent shocks but more stable.
- Log Returns: Uses natural log for calculations. Highly recommended for assets with exponential growth or large volume ranges.
- Length: The baseline period for the calculation.
- Threshold Lookback: The number of bars used to calculate the Mean and Standard Deviation bands.
- EWMA Lambda: The decay factor (0.0 to 1.0). A value of 0.94 is standard for risk metrics.
-- Higher Lambda (e.g., 0.98): The indicator reacts slower and is smoother (long memory).
-- Lower Lambda (e.g., 0.80): The indicator reacts very fast to new data (short memory).
Visuals
- Show Thresholds: Toggles the visibility of the statistical bands on the chart.
- High Band (StdDev): The multiplier for the upper warning zone. Default is 1.5 deviations. Increasing this to 2.0 or 3.0 will filter for only the most extreme events.
Disclaimer This tool is for educational and technical analysis purposes only. Breakouts can fail (fake-outs), and past geometric patterns do not guarantee future price action. Always manage risk and use this tool in conjunction with other forms of analysis.
SUPERTREND VALIDADO ADX EMAS VWAP # Modular Trading System - SuperTrend + ADX + Multi-Filter Confirmation
## Overview
Professional modular trading system designed for trend-following strategies on 4H timeframes. Features a clean, mobile-optimized interface with customizable filters and real-time status monitoring.
## Core Features
### Validated Components (Backtested)
- **SuperTrend (ATR 10, Multiplier 3.0)**: Primary trend direction filter with visual fill
- **ADX >23**: Trend strength confirmation (14-period)
- Proven performance: 52.11% win rate, 3.162 profit factor over 4 years
### Additional Filters (Optional)
- **DI Spread >9**: Directional movement confirmation
- **Volume > EMA20**: Volume confirmation above 20-period average
- **EMA System**: 7/21/50 with dynamic coloring
- **VWAP**: Daily volume-weighted average price
### Visual Elements
- **SuperTrend Line**: Green (bullish) / Red (bearish) with background fill
- **EMA 7**: Yellow when ADX >23, White when ADX ≤23
- **EMA 21**: Green (price above) / Red (price below)
- **EMA 50**: Blue reference line
- **VWAP**: Orange line
- **PDH/PDL**: Previous day high/low levels
- **EMA Cross Signals**: Small dots marking 7/21 crossovers
### Smart Money Concepts
- Automatic Previous Day High (PDH) / Previous Day Low (PDL) tracking
- Horizontal lines extending from current price
- Clear labeling for support/resistance levels
## Status Dashboard
Compact 2-column table (top-right) shows:
```
FILTERS | STATUS
1. ADX >23 | 47.6 OK / 18.2 NO
2. DI Spread >9 | Bullish / Bearish
3. SuperTrend | Bullish / Bearish
4. Volume >EMA20 | 1.25x OK / 0.14x NO
─────────────────────────────
SIGNAL | BUY / SELL / WAIT
```
Color-coded backgrounds:
- Green: Condition met
- Red: Condition not met
- Yellow: Waiting for confirmation
## Signal Logic
### Entry Conditions
**LONG**: All active filters must align
- SuperTrend bullish (green)
- ADX >23
- DI+ > DI- (if DI Spread enabled)
- Volume > EMA20 (if Volume enabled)
- Price > EMA21 and EMA7 > EMA21 (if EMAs enabled)
**SHORT**: All active filters must align
- SuperTrend bearish (red)
- ADX >23
- DI- > DI+ (if DI Spread enabled)
- Volume > EMA20 (if Volume enabled)
- Price < EMA21 and EMA7 < EMA21 (if EMAs enabled)
### Exit Conditions
- SuperTrend direction change
- Clear "EXIT" markers on chart
### Position Management
- One position per trend (no pyramiding)
- Prevents multiple entries in same direction
- "WAIT" status when conditions partially met
## Settings & Customization
### Filters (Enable/Disable)
**Core Filters:**
- ✓ SuperTrend (VALIDATED)
- ✓ ADX >23 (VALIDATED)
**Additional Filters:**
- ⚠️ DI Spread >9 (EXPERIMENTAL)
- ⚠️ Volume > EMA20 (EXPERIMENTAL)
- ⚠️ EMAs 7/21/50 (EXPERIMENTAL)
**Visual:**
- Show EMA 7/21 Crosses (dots)
### Parameters
**SuperTrend:**
- ATR Period: 10 (default)
- ATR Multiplier: 3.0 (default)
**ADX/DI:**
- ADX Length: 14 (default)
- ADX Threshold: 23 (default)
- DI Spread Threshold: 9 (default)
**Volume:**
- Volume EMA: 20 (default)
**EMAs:**
- Fast EMA: 7 (default)
- Medium EMA: 21 (default)
- Slow EMA: 50 (default)
## Alerts
Pre-configured alerts for:
- Long Signal (BUY - Entry confirmed)
- Short Signal (SELL - Entry confirmed)
- Exit Long (EXIT LONG - SuperTrend changed)
- Exit Short (EXIT SHORT - SuperTrend changed)
- EMA Cross Up (EMA 7 crossed above EMA 21)
- EMA Cross Down (EMA 7 crossed below EMA 21)
## Best Practices
### Recommended Setup (Validated System)
```
Enable ONLY:
- SuperTrend: ON
- ADX >23: ON
- All other filters: OFF
```
### Testing New Filters
1. Enable experimental filters
2. Backtest thoroughly before live trading
3. Compare performance metrics
4. Validate with demo account first
### Timeframe
- Optimized for: 4H charts
- Tested on: Bitcoin/USDT
- Works on: Any trending instrument
## Risk Management
This indicator provides entry/exit signals but does NOT include:
- Stop loss levels
- Take profit targets
- Position sizing
Always use proper risk management:
- Maximum 1-2% risk per trade
- Use stop losses
- Follow your trading plan
## Performance Notes
**Validated Backtest Results (SuperTrend + ADX only):**
- Win Rate: 52.11%
- Profit Factor: 3.162
- Return: +45.46% (4 years)
- Tested Period: 2020-2024
- Instrument: BTC/USDT 4H
**Important:** Adding additional filters changes the system. Results may vary. Always backtest your specific configuration before live trading.
## Mobile Optimization
- Compact table design
- Clear color coding
- Minimal chart clutter
- Large signal text
- Optimized for small screens
## Use Cases
✅ **Ideal for:**
- Trend-following strategies
- Swing trading (4H timeframe)
- Clear market conditions
- Systematic traders
❌ **NOT ideal for:**
- Scalping (too slow)
- Range-bound markets
- Counter-trend strategies
- Lateral/choppy conditions
## Credits & Methodology
Based on proven technical analysis principles:
- SuperTrend (volatility-based trend following)
- ADX (trend strength measurement)
- Directional Indicators (DI+/DI-)
- Volume analysis
- EMA systems
**Designed for:** Disciplined execution over frequent trading
**Philosophy:** Quality setups > Quantity of trades
## Disclaimer
This indicator is for educational purposes only. Past performance does not guarantee future results. Always:
- Test on demo account first
- Use proper risk management
- Never risk more than you can afford to lose
- Consult a financial advisor
Trading involves substantial risk. This tool does not constitute financial advice.
---
## Version History
**v2.0 (Current)**
- Modular filter system
- 2-column compact status table
- EMA 7 dynamic coloring (yellow when ADX >23)
- EMA 50 + VWAP added
- PDH/PDL levels
- EMA cross markers
- Improved signal logic
- One position per trend
- Multiple alert conditions
---
**For support, updates, or feedback, contact the developer.**
SUPERTREND ADX FACTOR Modular Trading System - SuperTrend + ADX + DI
A comprehensive trend-following system with customizable filters for precise trade execution.
CORE COMPONENTS:
- SuperTrend with visual fill (trend detection)
- ADX + Directional Indicators (trend strength confirmation)
- Volume filter (optional)
- EMAs 7/21/50 (optional)
- Daily VWAP (optional)
- Previous Day High/Low levels (support/resistance)
KEY FEATURES:
✓ One entry per trend - avoids overtrading
✓ Entry: ADX crosses above threshold with SuperTrend alignment
✓ Exit: SuperTrend direction change
✓ Real-time status dashboard showing all filter conditions
✓ Clear BUY/SELL signals with EXIT markers
✓ All filters can be toggled ON/OFF for testing
✓ Customizable parameters for each indicator
DASHBOARD DISPLAY:
- Live ADX value (green >23 / red <23)
- DI+/DI- values with color coding
- Volume metrics
- Position status (IN/OUT)
- Signal status (BUY/SELL/WAIT)
IDEAL FOR:
Swing traders and position traders on 4H timeframe looking for high-probability trend entries with proper confirmation.
Default configuration: SuperTrend (ATR 10, 3.0) + ADX >23 + DI alignment
RSI WMA Crossover Momentum w/ HighlightRSI WMA Crossover Momentum
This is a momentum indicator that tracks the RSI. Its principle is to use the WMA line to determine the trend of the RSI, and from the RSI, the price trend can be determined.
Volume-Gated Trend Ribbon [QuantAlgo]🟢 Overview
The Volume-Gated Trend Ribbon employs a selective price-updating mechanism that filters market noise through volume validation, creating a trend-following system that responds exclusively to significant price movements. The indicator gates price updates to moving average calculations based on volume threshold crossovers, ensuring that only bars with significant participation influence the trend direction. By interpolating between fast and slow moving averages to create a multi-layered visual ribbon, the indicator provides traders and investors with an adaptive trend identification framework that distinguishes between volume-backed directional shifts and low-conviction price fluctuations across multiple timeframes and asset classes.
🟢 How It Works
The indicator first establishes a dynamic baseline by calculating the simple moving average of volume over a configurable lookback period, then applies a user-defined multiplier to determine the significance threshold:
avgVol = ta.sma(volume, volPeriod)
highVol = volume >= avgVol * volMult
The gated price mechanism employs conditional updating where the close price is only captured and stored when volume exceeds the threshold. During low-volume periods, the indicator maintains the last qualified price level rather than tracking every minor fluctuation:
var float gatedClose = close
if highVol
gatedClose := close
Dual moving averages are calculated using the gated price input, with the indicator supporting various MA types. The fast and slow periods create the outer boundaries of the trend ribbon:
fastMA = volMA(gatedClose, close, fastPeriod)
slowMA = volMA(gatedClose, close, slowPeriod)
Ribbon interpolation creates intermediate layers by blending the fast and slow moving averages using weighted combinations, establishing a gradient effect that visually represents trend strength and momentum distribution:
midFastMA = fastMA * 0.67 + slowMA * 0.33
midSlowMA = fastMA * 0.33 + slowMA * 0.67
Trend state determination compares the fast MA against the slow MA, establishing bullish regimes when the faster average trades above the slower average and bearish regimes during the inverse relationship. Signal generation triggers on state transitions, producing alerts when the directional bias shifts:
bullish = fastMA > slowMA
longSignal = trendState == 1 and trendState != 1
shortSignal = trendState == -1 and trendState != -1
The visualization architecture constructs a three-tiered opacity gradient where the ribbon's core (between mid-slow and slow MAs) displays the highest opacity, the inner layer (between mid-fast and mid-slow) shows medium opacity, and the outer layer (between fast and mid-fast) presents the lightest fill, creating depth perception that emphasizes the trend center while acknowledging edge uncertainty.
🟢 How to Use This Indicator
▶ Long and Short Signals: The indicator generates long/buy signals when the trend state transitions to bullish (fast MA crosses above slow MA) and short/sell signals when transitioning to bearish (fast MA crosses below slow MA). Because these crossovers only reflect volume-validated price movements, they represent significant level of participation rather than random noise, providing higher-conviction entry signals that filter out false breakouts occurring on thin volume.
▶ Ribbon Width Dynamics: The spacing between the fast and slow moving averages creates the ribbon width, which serves as a visual proxy for trend strength and volatility. Expanding ribbons indicate accelerating directional movement with increasing separation between short-term and long-term momentum, suggesting robust trend development. Conversely, contracting ribbons signal momentum deceleration, potential trend exhaustion, or impending consolidation as the fast MA converges toward the slow MA.
▶ Preconfigured Presets: Three optimized parameter sets accommodate different trading styles and market conditions. Default provides balanced trend identification suitable for swing trading on daily timeframes with moderate volume filtering and responsiveness. Fast Response delivers aggressive signal generation optimized for intraday scalping on 1-15 minute charts, using lower volume thresholds and shorter moving average periods to capture rapid momentum shifts. Smooth Trend offers conservative trend confirmation ideal for position trading on 4-hour to weekly charts, employing stricter volume requirements and extended periods to filter noise and identify only the most robust directional moves.
▶ Built-in Alerts: Three alert conditions enable automated monitoring: Bullish Trend Signal triggers when the fast MA crosses above the slow MA confirming uptrend initiation, Bearish Trend Signal activates when the fast MA crosses below the slow MA confirming downtrend initiation, and Trend Change alerts on any directional transition regardless of direction. These notifications allow you to respond to volume-validated regime shifts without continuous chart monitoring.
▶ Color Customization: Six visual themes (Classic, Aqua, Cosmic, Ember, Neon, plus Custom) accommodate different chart backgrounds and display preferences, ensuring optimal contrast and visual clarity across trading environments. The adjustable fill opacity control (0-100%) allows fine-tuning of ribbon prominence, with lower opacity values create subtle background context while higher values produce bold trend emphasis. Optional bar coloring extends the trend indication directly to the price bars, providing immediate directional reference without requiring visual cross-reference to the ribbon itself.
VEGA (Velocity of Efficient Gain Adaptation)VEGA (Velocity of Efficient Gain Adaptation)
VEGA is a momentum oscillator that measures the velocity of an efficiency-weighted adaptive moving average. Unlike traditional momentum indicators that react uniformly to all price movements, VEGA intelligently adapts its sensitivity based on market conditions—responding quickly during trending periods and filtering noise during consolidation.
--------------------------------
What Makes VEGA Different
Efficiency-Driven Adaptation
At its core, VEGA uses the Efficiency Ratio (ER) to distinguish between trending and choppy markets. When price moves efficiently in one direction, VEGA's underlying adaptive MA speeds up to capture the move. When price chops sideways, it slows down to avoid whipsaws. This creates a momentum reading that's inherently cleaner than fixed-period alternatives.
Linear Regression Smoothed Source
VEGA offers an optional LinReg-smoothed price source that blends regular candles with linear regression values. This pre-smoothing reduces noise before it ever enters the calculation, resulting in a histogram that's easier to read without sacrificing responsiveness. The mix ratio lets you dial in exactly how much smoothing you want.
Z-Score Normalization with Dead Zone
Rather than arbitrary oscillator bounds, VEGA normalizes output as standard deviations from the mean. This gives statistically meaningful levels: readings above +2σ or below -2σ represent genuinely extreme momentum. The configurable dead zone (with Snap, Soft Fade, or None modes) filters out insignificant movements near zero, keeping you focused on signals that matter.
--------------------------------
How It Works
1. Source Preparation — Price is smoothed via a LinReg/regular candle blend
2. Efficiency Ratio — Measures directional movement vs total movement over the lookback period
3. Adaptive MA — Applies variable smoothing based on efficiency (fast during trends, slow during chop)
4. Velocity — Calculates the rate of change of the adaptive MA
5. Normalization — Converts to Z-Score (standard deviations) or ATR-normalized percentage
6. Dead Zone — Optionally filters near-zero values to reduce noise
--------------------------------
How To Read VEGA
Signal and Interpretation
Histogram above zero | Bullish momentum
Histogram below zero | Bearish momentum
Bright color | Momentum accelerating
Faded color | Momentum decelerating
Beyond ±1σ bands | Above-average momentum
Beyond ±2σ bands | Extreme momentum (potential reversal zone)
Zero line cross*| Momentum shift
--------------------------------
Key Settings
ER Length — Lookback for efficiency ratio calculation. Higher = smoother, slower adaptation.
Fast/Slow Smoothing — Controls the adaptive MA's responsiveness range. The MA blends between these based on efficiency.
LinReg Settings — Enable smoothed candles and adjust the blend ratio (0 = regular candles, 1 = full LinReg, 0.5 = 50/50 mix).
Z-Score Lookback — Period for calculating mean and standard deviation. Shorter = more reactive normalization.
Dead Zone Type — How to handle near-zero values:
Snap — Hard cutoff to zero
Soft Fade — Gradual reduction toward zero
None — No filtering
Dead Zone Threshold — Values within this Z-Score range are affected by the dead zone setting.
VEGA works on any timeframe and any market. For best results, adjust the ER Length and LinReg settings to match your trading style and the volatility characteristics of your instrument.
Volatility Targeting: Single Asset [BackQuant]Volatility Targeting: Single Asset
An educational example that demonstrates how volatility targeting can scale exposure up or down on one symbol, then applies a simple EMA cross for long or short direction and a higher timeframe style regime filter to gate risk. It builds a synthetic equity curve and compares it to buy and hold and a benchmark.
Important disclaimer
This script is a concept and education example only . It is not a complete trading system and it is not meant for live execution. It does not model many real world constraints, and its equity curve is only a simplified simulation. If you want to trade any idea like this, you need a proper strategy() implementation, realistic execution assumptions, and robust backtesting with out of sample validation.
Single asset vs the full portfolio concept
This indicator is the single asset, long short version of the broader volatility targeted momentum portfolio concept. The original multi asset concept and full portfolio implementation is here:
That portfolio script is about allocating across multiple assets with a portfolio view. This script is intentionally simpler and focuses on one symbol so you can clearly see how volatility targeting behaves, how the scaling interacts with trend direction, and what an equity curve comparison looks like.
What this indicator is trying to demonstrate
Volatility targeting is a risk scaling framework. The core idea is simple:
If realized volatility is low relative to a target, you can scale position size up so the strategy behaves like it has a stable risk budget.
If realized volatility is high relative to a target, you scale down to avoid getting blown around by the market.
Instead of always being 1x long or 1x short, exposure becomes dynamic. This is often used in risk parity style systems, trend following overlays, and volatility controlled products.
This script combines that risk scaling with a simple trend direction model:
Fast and slow EMA cross determines whether the strategy is long or short.
A second, longer EMA cross acts as a regime filter that decides whether the system is ACTIVE or effectively in CASH.
An equity curve is built from the scaled returns so you can visualize how the framework behaves across regimes.
How the logic works step by step
1) Returns and simple momentum
The script uses log returns for the base return stream:
ret = log(price / price )
It also computes a simple momentum value:
mom = price / price - 1
In this version, momentum is mainly informational since the directional signal is the EMA cross. The lookback input is shared with volatility estimation to keep the concept compact.
2) Realized volatility estimation
Realized volatility is estimated as the standard deviation of returns over the lookback window, then annualized:
vol = stdev(ret, lookback) * sqrt(tradingdays)
The Trading Days/Year input controls annualization:
252 is typical for traditional markets.
365 is typical for crypto since it trades daily.
3) Volatility targeting multiplier
Once realized vol is estimated, the script computes a scaling factor that tries to push realized volatility toward the target:
volMult = targetVol / vol
This is then clamped into a reasonable range:
Minimum 0.1 so exposure never goes to zero just because vol spikes.
Maximum 5.0 so exposure is not allowed to lever infinitely during ultra low volatility periods.
This clamp is one of the most important “sanity rails” in any volatility targeted system. Without it, very low volatility regimes can create unrealistic leverage.
4) Scaled return stream
The per bar return used for the equity curve is the raw return multiplied by the volatility multiplier:
sr = ret * volMult
Think of this as the return you would have earned if you scaled exposure to match the volatility budget.
5) Long short direction via EMA cross
Direction is determined by a fast and slow EMA cross on price:
If fast EMA is above slow EMA, direction is long.
If fast EMA is below slow EMA, direction is short.
This produces dir as either +1 or -1. The scaled return stream is then signed by direction:
avgRet = dir * sr
So the strategy return is volatility targeted and directionally flipped depending on trend.
6) Regime filter: ACTIVE vs CASH
A second EMA pair acts as a top level regime filter:
If fast regime EMA is above slow regime EMA, the system is ACTIVE.
If fast regime EMA is below slow regime EMA, the system is considered CASH, meaning it does not compound equity.
This is designed to reduce participation in long bear phases or low quality environments, depending on how you set the regime lengths. By default it is a classic 50 and 200 EMA cross structure.
Important detail, the script applies regime_filter when compounding equity, meaning it uses the prior bar regime state to avoid ambiguous same bar updates.
7) Equity curve construction
The script builds a synthetic equity curve starting from Initial Capital after Start Date . Each bar:
If regime was ACTIVE on the previous bar, equity compounds by (1 + netRet).
If regime was CASH, equity stays flat.
Fees are modeled very simply as a per bar penalty on returns:
netRet = avgRet - (fee_rate * avgRet)
This is not realistic execution modeling, it is just a simple turnover penalty knob to show how friction can reduce compounded performance. Real backtesting should model trade based costs, spreads, funding, and slippage.
Benchmark and buy and hold comparison
The script pulls a benchmark symbol via request.security and builds a buy and hold equity curve starting from the same date and initial capital. The buy and hold curve is based on benchmark price appreciation, not the strategy’s asset price, so you can compare:
Strategy equity on the chart symbol.
Buy and hold equity for the selected benchmark instrument.
By default the benchmark is TVC:SPX, but you can set it to anything, for crypto you might set it to BTC, or a sector index, or a dominance proxy depending on your study.
What it plots
If enabled, the indicator plots:
Strategy Equity as a line, colored by recent direction of equity change, using Positive Equity Color and Negative Equity Color .
Buy and Hold Equity for the chosen benchmark as a line.
Optional labels that tag each curve on the right side of the chart.
This makes it easy to visually see when volatility targeting and regime gating change the shape of the equity curve relative to a simple passive hold.
Metrics table explained
If Show Metrics Table is enabled, a table is built and populated with common performance statistics based on the simulated daily returns of the strategy equity curve after the start date. These include:
Net Profit (%) total return relative to initial capital.
Max DD (%) maximum drawdown computed from equity peaks, stored over time.
Win Rate percent of positive return bars.
Annual Mean Returns (% p/y) mean daily return annualized.
Annual Stdev Returns (% p/y) volatility of daily returns annualized.
Variance of annualized returns.
Sortino Ratio annualized return divided by downside deviation, using negative return stdev.
Sharpe Ratio risk adjusted return using the risk free rate input.
Omega Ratio positive return sum divided by negative return sum.
Gain to Pain total return sum divided by absolute loss sum.
CAGR (% p/y) compounded annual growth rate based on time since start date.
Portfolio Alpha (% p/y) alpha versus benchmark using beta and the benchmark mean.
Portfolio Beta covariance of strategy returns with benchmark returns divided by benchmark variance.
Skewness of Returns actually the script computes a conditional value based on the lower 5 percent tail of returns, so it behaves more like a simple CVaR style tail loss estimate than classic skewness.
Important note, these are calculated from the synthetic equity stream in an indicator context. They are useful for concept exploration, but they are not a substitute for professional backtesting where trade timing, fills, funding, and leverage constraints are accurately represented.
How to interpret the system conceptually
Vol targeting effect
When volatility rises, volMult falls, so the strategy de risks and the equity curve typically becomes smoother. When volatility compresses, volMult rises, so the system takes more exposure and tries to maintain a stable risk budget.
This is why volatility targeting is often used as a “risk equalizer”, it can reduce the “biggest drawdowns happen only because vol expanded” problem, at the cost of potentially under participating in explosive upside if volatility rises during a trend.
Long short directional effect
Because direction is an EMA cross:
In strong trends, the direction stays stable and the scaled return stream compounds in that trend direction.
In choppy ranges, the EMA cross can flip and create whipsaws, which is where fees and regime filtering matter most.
Regime filter effect
The 50 and 200 style filter tries to:
Keep the system active in sustained up regimes.
Reduce exposure during long down regimes or extended weakness.
It will always be late at turning points, by design. It is a slow filter meant to reduce deep participation, not to catch bottoms.
Common applications
This script is mainly for understanding and research, but conceptually, volatility targeting overlays are used for:
Risk budgeting normalize risk so your exposure is not accidentally huge in high vol regimes.
System comparison see how a simple trend model behaves with and without vol scaling.
Parameter exploration test how target volatility, lookback length, and regime lengths change the shape of equity and drawdowns.
Framework building as a reference blueprint before implementing a proper strategy() version with trade based execution logic.
Tuning guidance
Lookback lower values react faster to vol shifts but can create unstable scaling, higher values smooth scaling but react slower to regime changes.
Target volatility higher targets increase exposure and drawdown potential, lower targets reduce exposure and usually lower drawdowns, but can under perform in strong trends.
Signal EMAs tighter EMAs increase trade frequency, wider EMAs reduce churn but react slower.
Regime EMAs slower regime filters reduce false toggles but will miss early trend transitions.
Fees if you crank this up you will see how sensitive higher turnover parameter sets are to friction.
Final note
This is a compact educational demonstration of a volatility targeted, long short single asset framework with a regime gate and a synthetic equity curve. If you want a production ready implementation, the correct next step is to convert this concept into a strategy() script, add realistic execution and cost modeling, test across multiple timeframes and market regimes, and validate out of sample before making any decision based on the results.






















