Range Oscillator (Zeiierman)█ Overview
Range Oscillator (Zeiierman) is a dynamic market oscillator designed to visualize how far the price is trading relative to its equilibrium range. Instead of relying on traditional overbought/oversold thresholds, it uses adaptive range detection and heatmap coloring to reveal where price is trading within a volatility-adjusted band.
The oscillator maps market movement as a heat zone, highlighting when the price approaches the upper or lower range boundaries and signaling potential breakout or mean-reversion conditions.
Highlights
Adaptive range detection based on ATR and weighted price movement.
Heatmap-driven coloring that visualizes volatility pressure and directional bias.
Clear transition zones for detecting trend shifts and equilibrium points.
█ How It Works
⚪ Range Detection
The indicator identifies a dynamic price range using two main parameters:
Minimum Range Length: The number of bars required to confirm that a valid range exists.
Range Width Multiplier: Expands or contracts the detected range proportionally to the ATR (Average True Range).
This approach ensures that the oscillator automatically adapts to both trending and ranging markets without manual recalibration.
⚪ Weighted Mean Calculation
Instead of a simple moving average, the script calculates a weighted equilibrium mean based on the size of consecutive candle movements:
Larger price changes are given greater weight, emphasizing recent volatility.
⚪ Oscillator Formula
Once the range and equilibrium mean are defined, the oscillator computes:
Osc = 100 * (Close - Mean) / RangeATR
This normalizes price distance relative to the dynamic range size — producing consistent readings across volatile and quiet periods.
█ Heatmap Logic
The Range Oscillator includes a built-in heatmap engine that color-codes each oscillator value based on recent price interaction intensity:
Strong Bullish Zones: Bright green — price faces little resistance upward.
Weak Bullish Zones: Muted green — uptrend continuation but with minor hesitation.
Transition Zones: Blue — areas of uncertainty or trend shift.
Weak Bearish Zones: Maroon — downtrend pressure but soft momentum.
Strong Bearish Zones: Bright red — strong downside continuation with low resistance.
Each color band adapts dynamically using:
Number of Heat Levels: Controls granularity of the heatmap.
Minimum Touches per Level: Defines how reactive or “sensitive” each color zone is.
█ How to Use
⚪ Trend & Momentum Confirmation
When the oscillator stays above +0 with green coloring, it suggests sustained bullish pressure.
Similarly, readings below –0 with red coloring, it suggests sustained bearish pressure.
⚪ Range Breakouts
When the oscillator line breaks above +100 or below –100, the price is exceeding its normal volatility range, often signaling breakout potential or exhaustion extremes.
⚪ Mean Reversion Trades
Look for the oscillator to cross back toward zero after reaching an extreme. These transitions (often marked by blue tones) can identify early reversals or range resets.
⚪ Divergence
Use oscillator peaks and troughs relative to price action to spot hidden strength or weakness before the next move.
█ Settings
Minimum Range Length: Number of bars needed to confirm a valid range.
Range Width Multiplier: Expands or contracts range width based on ATR.
Number of Heat Levels: Number of gradient bands used in the oscillator.
Minimum Touches per Level: Sensitivity threshold for when a zone becomes “hot.”
-----------------
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.
Osilatörler
RSI Breakout Zones█ OVERVIEW
“RSI Breakout Zones” is a technical analysis tool that identifies significant zones on the chart based on the Relative Strength Index (RSI). The indicator maps overbought (OB) and oversold (OS) zones using boxes, then extends them until the next zone of the same type is detected, highlighting breakout points to aid in trade entry decisions. These zones often serve as areas of consolidation, support, or resistance.
█ CONCEPTS
The indicator identifies overbought (above 70) and oversold (below 30) zones, drawing boxes that extend until the next zone of the same type (OB for OB, OS for OS) is detected. Breakout signals are generated when the price crosses the zone boundaries, indicating potential shifts in market momentum.
Why are RSI zones important? These zones represent areas of extreme market sentiment, often leading to corrections or reversals. Overbought zones suggest potential selling pressure, while oversold zones indicate buying opportunities. After a breakout, a zone may switch roles, e.g., from support to resistance or vice versa, making it a key element in price action analysis. Larger zones, formed during high volatility, may attract price for retests due to stronger imbalances in buyer/seller dynamics. Consolidation often occurs within these zones as the market seeks equilibrium before further moves. However, in strong trends, zones may be decisively broken without immediate pullbacks, and their significance depends on their position relative to key support and resistance levels.
█ FEATURES
- RSI Zone Detection: Calculates RSI with a customizable length (default 14) and identifies overbought/oversold zones based on user-defined levels (default 70/30), drawing boxes that dynamically adjust to price action within the zone.
- Customizable Boxes: Zones extend until the next zone of the same type is detected. The indicator draws zones with adjustable colors for overbought (red) and oversold (green) areas, with options for box and zone transparency.
- Breakout Signals: Generates upward (green triangle) and downward (red triangle) breakout signals when the price crosses the top or bottom of a zone. Signals appear below or above the bar, indicating potential trade entry points.
- Midline: Automatically draws a dashed line at the midpoint of each zone, helping traders assess price behavior within the zone and potential halfway retests.
- Box Management: Option to remove outdated boxes.
- Alerts: Built-in support for alerts on breakout signals, enabling traders to receive notifications for key zone crossings.
█ HOW TO USE
Add to Chart: Apply the indicator to your TradingView chart via the Pine Editor or Indicators menu.
Configure Settings:
- RSI Settings: Adjust RSI Length (default 14), Overbought Level (default 70), and Oversold Level (default 30) to tailor zone detection sensitivity—higher lengths smooth signals for longer-term analysis.
- Box Settings: Configure colors and transparency for overbought (red) and oversold (green) zones, including box transparency (default 90) and zone transparency (default 90).
- Signal Settings: Customize breakout signal colors (green for upward, red for downward) and enable/disable keeping boxes after RSI normalization.
Interpreting Signals:
- Upward Breakout Signal: A green triangle below the bar indicates a breakout, suggesting potential bullish momentum and trend continuation or reversal.
- Downward Breakout Signal: A red triangle above the bar indicates a breakout, suggesting potential bearish momentum.
- RSI Zones: If the price re-enters a zone after a breakout, it may signal a false breakout or consolidation; persistent zones can act as future support/resistance levels. Consolidation often occurs within these zones as the market seeks equilibrium.
- Use signals alongside other technical analysis tools for confirmation, such as moving averages (to confirm trend direction), Fibonacci levels (to identify key price zones), or volume indicators (to validate breakout strength). Analyze RSI zones on higher timeframes for stronger signals due to broader market context.
█ APPLICATIONS
- Momentum Trading: Use RSI zones as overbought/oversold filters. In an uptrend, look for buying opportunities on upward breakouts, and in a downtrend, on downward breakouts. Combining with MACD crossovers, Fibonacci levels, or pivot points enhances zone significance.
- Inter-Zone Trading: Utilize breakouts from one RSI zone and hold the position until reaching the next zone, which may act as a target level or reversal point.
█ NOTES
- Test the indicator across different timeframes and markets (stocks, forex, crypto) to optimize RSI length and levels for your trading style.
- For best results, use in trending markets where RSI extremes are more predictive; in ranging markets, additional filters are recommended to reduce false signals.
- Always combine with risk management; RSI zones alone do not guarantee reversals, and false breakouts may occur in low-liquidity environments.
TOPIX Relative Strength vs Symbol + Volume Quality (JP)Overview
Relative Strength vs Symbol + Volume Quality (JP) visualizes the relative performance (%) of a stock versus a chosen benchmark (e.g., TOPIX, Nikkei 225, or ETFs) while incorporating volume quality and momentum analysis.
It calculates percentage-point differences between the target and benchmark, smooths them (EMA/SMA), and evaluates whether the strength is supported by quality volume flow.
All data uses confirmed bars only (request.security() with confirmed values) to minimize repainting, and labels are drawn only on confirmed bars.
What It Shows
Relative Performance (%pt): Difference in rate of change between the stock and its benchmark.
Above 0 → outperforming
Below 0 → underperforming
Trend Direction: Short-/mid-term trend from smoothed EMA/SMA.
Volume Quality: Ratio of up-volume to down-volume, scaled from -1 to +1.
Volume Momentum (Z-Score): Measures unusual surges in trading activity.
Strength Detection: Combines price-based strength (relative or z-score) with volume quality and momentum filters.
How to Use
Set your comparison symbol (e.g., TSE:1306, TVC:NI225).
Adjust lookback length and smoothing period/type to fit your analysis window.
Enable “Confirm strength by volume quality” and/or “Use volume Z-score” to filter signals with supportive volume.
Optionally, configure background thresholds to highlight extreme relative strength/weakness.
Use Screener Mode to suppress visual outputs (table/labels) for performance in Pine Screener.
Main Input Groups
Comparison Settings: Benchmark symbol, calculation timeframe.
Period & Smoothing: lookback, smoothLen, and MA type (EMA or SMA).
Price Strength Detection: Enable Z-score mode and adjust zLen / zThresh.
Volume Quality & Momentum: vqThresh (volume quality) and vZth (Z-score threshold).
Display: Toggle histogram tint, background highlight, mini-table, and signal labels.
Background Thresholds: Independent thresholds for histogram/MA lines and colors.
Screener Output: Suppress visuals for screening use.
Output & Coloring
Histogram: Relative performance in %pt. Red = outperforming, Green = underperforming (intensity by magnitude).
White Line (EMA/SMA):
Rising with good volume quality → Red
Rising but poor quality → Yellow
Falling → White
Background: Optional highlight when histogram/MA exceeds user thresholds.
Counters: Hidden plots track how many bars have consecutively exceeded thresholds (usable in screeners).
Alerts
Strength Detection (Price + Volume):
Triggered when price condition (MA > 0 or Z-score > threshold) and volume conditions are met.
Weakness / Loss of Strength:
Triggered on cross-under or when volume conditions fail.
Labels: Optional, shown only on confirmed bars.
Repaint Prevention
All calculations use confirmed bar data only.
Labels appear only when bars close.
On lower timeframes, benchmark update delays may cause minor lag.
Volume quality is derived from up/down bar classification, which can be distorted by gaps or illiquid markets.
Avoid overfitting thresholds — values differ by asset and timeframe.
Practical Applications
Identify outperformance with supportive volume across sectors or themes.
Use streak counters to find consistent relative winners or laggards.
Compare stocks vs sector indices or ETFs to track rotation and momentum shifts.
Disclaimer
This script and its description are provided for educational and informational purposes only.
They do not constitute financial advice or recommendations.
Use at your own discretion, considering market risk, liquidity, and data limitations.
This description follows TradingView’s House Rules (no promotion, plagiarism, or misleading claims).
Publication Guidelines
When publishing:
Do not include promotional links or invitations.
Do not copy text/code from other authors without permission.
Screenshots should illustrate the script’s function only, not serve as marketing material.
Maintain consistency of language (English only for this version).
概要
Relative Strength vs Symbol + Volume Quality (JP) は、対象銘柄と比較指標(例:TOPIX)との相対パフォーマンスを%ポイント差で算出し、平滑化線(EMA/SMA)とヒストグラムで可視化します。さらに、出来高を「質(上げ/下げボリュームのバランス)」と「勢い(Zスコア)」で評価し、価格×出来高の両面から“強さ/弱さ”を判定します。
リペイント抑制のため、request.security()は確定足を参照し、ラベル描画も確定時に限定しています。
何がわかるか
相対パフォーマンス(%pt):対象と比較指標の騰落率差。0より上=相対優位、下=相対劣位。
平滑化トレンド:相対の短中期的な傾き(EMA/SMA)。
出来高の質:上昇バー出来高と下降バー出来高の比から -1〜+1 で評価。
出来高の勢い(Zスコア):直近出来高の異常度。
強/弱シグナル:価格条件(基準越え・Z超え)に、出来高条件(質・勢い)を組み合わせて抽出。
使い方(基本手順)
比較対象を「比較シンボル」で指定(例:TSE:1306、TVC:NI225 等)。
「比較期間(バー数)」と「平滑化(期間/種類)」を調整し、相対の視点を合わせる。
出来高確認を使う場合は「出来高の質で“強さ”を確認」「出来高の勢い(Z)」をオンにし、閾値を調整。
背景ハイライトの**閾値(ヒスト/平均線別)**を設定すると、重要局面を一目で把握可能。
スクリーナー利用時は「スクリーナー用」をオンにして、テーブル/ラベルの描画を抑制。
主な入力項目
比較設定:比較シンボル、計算タイムフレーム。
期間・平滑化:比較期間lookback、平滑化長smoothLen、MA種別(EMA/SMA)。
強さ検出(価格):Zスコア方式のオン/オフ、zLen、zThresh。
出来高の質・勢い:質の閾値vqThresh、勢いZの長さvZlenと閾値vZth。
表示:テーブル、背景、ヒスト濃淡、直近ラベルのON/OFF。
背景(閾値):ヒスト/平均線の上下しきいと背景色。
スクリーナー出力:描画抑制トグル。
出力と色分け
ヒストグラム:相対パフォーマンス(%pt)。プラス域は赤系、マイナス域は緑系で濃淡表示。
白線(実体は平滑化相対):上向きかつ出来高質が閾値以上なら赤、上向きでも質不足なら黄、下降時は白。
背景色(任意):設定したヒスト/平均線の閾値を超過/割れで自動着色。
カウンタ:ヒスト/平均線が各閾値を連続超過/連続割れした本数を、スクリーナーが取得できるよう非表示プロットで出力。
シグナル・アラート
強さ検出(価格+出来高):
価格条件 … 平滑化線の0越え、またはZスコアがzThresh越え。
出来高条件 … 「質 ≥ vqThresh」「勢いZ ≥ vZth」(任意)。
条件一致で「強」アラート/喪失・未達で「弱」アラート。
ラベル(任意):確定足でのみ出力。
リペイントと制約
request.security()は確定足データを用い、確定時ラベルのみ描画する設計です。
比較シンボルの更新周期・分足集計差により、短期足ではタイムラグが生じる場合があります。
出来高の「質」は上昇/下降バーの単純仕分けに依存するため、ギャップや出来高の歪みが強い市場では解釈に注意。
閾値は銘柄・期間で最適値が異なります。**過度な最適化(カーブフィット)**は避けてください。
(公開ガイドライン上も、明確で誤解を生む表現の回避が推奨されます。
TradingView
)
活用アイデア(例)
相対優位×出来高質の改善が同時に起きた局面を抽出。
連続超過カウントで、相対の“粘り”や“伸び”をスクリーニング。
指数だけでなく、業種ETFやセクター指数を比較軸にしてローテーション把握。
免責
本スクリプトおよび説明は情報提供・教育目的です。投資助言・勧誘ではありません。市場リスク、流動性、スリッページ、データ仕様に起因する差異等は利用者の自己責任でご確認ください。TradingViewのハウスルール(広告禁止・独自性・言語一致・わかりやすさ)および公開ルールに準拠する形で記述しています。
Trend Following Reflectometry🧭 Trend Following Reflectometry (TFR)
Author: Stef Jonker
Version: Pine Script® v6
The Trend Following Reflectometry (TFR) indicator translates market behavior into the language of impedance and signal reflection theory, providing a unique way to measure trend strength, stability, and purity.
🧩 Summary
Trend Following Reflectometry acts as a trend-quality meter, helping traders identify when a trend is strong, efficient, and worth following — or when the market is too noisy to trust.
It blends physics-inspired logic with practical trading insight, offering both a directional oscillator and a trend stability filter in one tool.
⚙️ Concept
Inspired by electrical impedance matching, this tool compares the market’s characteristic impedance (Z₀) — its natural volatility-to-price behavior — with the load impedance (Zₗ), representing current trend momentum.
The interaction between these two produces a reflection coefficient (Gamma) and a VSWR ratio, which reveal how efficiently market trends are transmitting energy (moving smoothly) versus reflecting noise (becoming unstable).
📊 Core Components
Z₀ (Characteristic Impedance): Market baseline, derived from ATR and SMA.
Zₗ (Load Impedance): Trend momentum based on fast and slow EMAs.
Γ (Gamma – Reflection Coefficient): Measures the mismatch between Z₀ and Zₗ.
VSWR (Voltage Standing Wave Ratio): Quantifies trend purity — lower = cleaner trend.
Impedance Oscillator: Combines momentum and reflection to produce directional bias.
⚡ Gamma & VSWR Interpretation
Gamma (Γ) represents the reflection coefficient — how much of the market’s trend energy is being reflected instead of transmitted.
When Gamma is low, the market trend is smooth and efficient, moving with little resistance.
When Gamma is high, the market becomes unstable or overextended, signaling potential turbulence, exhaustion, or reversal pressure.
VSWR (Voltage Standing Wave Ratio) measures trend purity — how clean or distorted the current trend is.
A low VSWR indicates a well-aligned, steady trend that’s likely to continue smoothly.
A high VSWR suggests an unbalanced or noisy market, where trends may struggle to sustain or could soon reverse.
Together, Gamma and VSWR help identify how well the market’s current momentum aligns with its natural behavior — whether the trend is stable and efficient or reflecting instability beneath the surface.
RSI to Price Projection PanelThis indicator calculates the current RSI based on the closing price and projects estimated prices for user-defined RSI target levels. Results are displayed in a table at the top-right corner of the chart.
RSI Divergence Strategy v6 What this does
Detects regular and hidden divergences between price and RSI using confirmed RSI pivots. Adds RSI@pivot entry gates, a normalized strength + volume filter, optional volume gate, delayed entries, and transparent risk management with rigid SL and activatable trailing. Visuals are throttled for clarity and include a gap-free horizontal RSI gradient.
How it works (simple)
🧮 RSI is calculated on your selected source/period.
📌 RSI pivots are confirmed with left/right lookbacks (lbL/lbR). A pivot becomes final only after lbR bars; before that, it can move (expected).
🔎 The latest confirmed pivot is compared against the previous confirmed pivot within your bar window:
• Regular Bullish = price lower low + RSI higher low
• Hidden Bullish = price higher low + RSI lower low
• Regular Bearish = price higher high + RSI lower high
• Hidden Bearish = price lower high + RSI higher high
💪 Each divergence gets a strength score that multiplies price % change, RSI change, and a volume ratio (Volume SMA / Baseline Volume SMA).
• Set Min divergence strength to filter tiny/noisy signals.
• Turn on the volume gate to require volume ratio ≥ your threshold (e.g., 1.0).
🎯 RSI@pivot gating:
• Longs only if RSI at the bullish pivot ≤ 30 (default).
• Shorts only if RSI at the bearish pivot ≥ 70 (default).
⏱ Entry timing:
• Immediate: on divergence confirm (delay = 0).
• Delayed: after N bars if RSI is still valid.
• RSI-only mode: ignore divergences; use RSI thresholds only.
🛡 Risk:
• Rigid SL is placed from average entry.
• Trailing activates only after unrealized gain ≥ threshold; it re-anchors on new highs (long) or new lows (short).
What’s NEW here (vs. the reference) — and why you may care
• Improved pivots + bar window → fewer early/misaligned signals; cleaner drawings.
• RSI@pivot gates → entries aligned with true oversold/overbought at the exact decision bar.
• Normalized strength + volume gate → ignore weak or low-volume divergences.
• Delayed entries → require the signal to persist N bars if you want more confirmation.
• Rigid SL + activatable trailing → trailing engages only after a cushion, so it’s less noisy.
• Clutter control + gradient → readable chart with a smooth RSI band look.
Suggested starting values (clear ranges)
• RSI@pivot thresholds: LONG ≤ 30 (oversold), SHORT ≥ 70 (overbought).
• Min divergence strength:
0.0 = off
3–6 = moderate filter
7–12 = strict filter for noisy LTFs
• Volume gate (ratio):
1.0 = at least baseline volume
1.2–1.5 = strong-volume only (fewer but cleaner signals)
• Pivot lookbacks:
lbL 1–2, lbR 3–4 (raise lbR to confirm later and reduce noise)
• Bar window (between pivots):
Min 5–10, Max 30–60 (increase Min if you see micro-pivots; increase Max for wider structures)
• Risk:
Rigid SL 2–5% on liquid majors; 5–10% on higher-volatility symbols
Trailing activation 1–3%, trailing 0.5–1.5% are common intraday starts
Plain-text examples
• BTCUSDT 1h → RSI 9, lbL 1, lbR 3, Min strength 5.0, Volume gate 1.0, SL 4.5%, Trail on 2.0%, Trail 1.0%.
• SPY 15m → RSI 8, lbL 1, lbR 3, Min strength 7.0, Volume gate 1.2, SL 3.0%, Trail on 1.5%, Trail 0.8%.
• EURUSD 4h → RSI 14, lbL 2, lbR 4, Min strength 4.0, Volume gate 1.0, SL 2.5%, Trail on 1.0%, Trail 0.5%.
Notes & limitations
• Pivot confirmation means the newest candidate pivot can move until lbR confirms it (expected).
• Results vary by timeframe/symbol/settings; always forward-test.
• Educational tool — no performance or profit claims.
Credits
• RSI by J. Welles Wilder Jr. (1978).
• Reference divergence script by eemani123:
• This version by tagstrading 2025 adds: improved pivot engine, RSI@pivot gating, normalized strength + optional volume gate, delayed entries, rigid SL and activatable trailing, and a gap-free RSI gradient.
Puell Multiple Variants [OperationHeadLessChicken]Overview
This script contains three different, but related indicators to visualise Bitcoin miner revenue.
The classical Puell Multiple : historically, it has been good at signaling Bitcoin cycle tops and bottoms, but due to the diminishing rewards miners get after each halving, it is not clear how you determine overvalued and undervalued territories on it. Here is how the other two modified versions come into play:
Halving-Corrected Puell Multiple : The idea is to multiply the miner revenue after each halving with a correction factor, so overvalued levels are made comparable by a horizontal line across cycles. After experimentation, this correction factor turned out to be around 1.63. This brings cycle tops close to each other, but we lose the ability to see undervalued territories as a horizontal region. The third variant aims to fix this:
Miner Revenue Relative Strength Index (Miner Revenue RSI) : It uses RSI to map miner revenue into the 0-100 range, making it easy to visualise over/undervalued territories. With correct parameter settings, it eliminates the diminishing nature of the original Puell Multiple, and shows both over- and undervalued revenues correctly.
Example usage
The goal is to determine cycle tops and bottoms. I recommend using it on high timeframes, like monthly or weekly . Lower than that, you will see a lot of noise, but it could still be used. Here I use monthly as the example.
The classical Puell Multiple is included for reference. It is calculated as Miner Revenue divided by the 365-day Moving Average of the Miner Revenue . As you can see in the picture below, it has been good at signaling tops at 1,3,5,7.
The problems:
- I have to switch the Puell Multiple to a logarithmic scale
- Still, I cannot use a horizontal oversold territory
- 5 didn't touch the trendline, despite being a cycle top
- 9 touched the trendline despite not being a cycle top
Halving-Corrected Puell Multiple (yellow): Multiplies the Puell Multiple by 1.63 (a number determined via experimentation) after each halving. In the picture below, you can see how the Classical (white) and Corrected (yellow) Puell Multiples compare:
Advantages:
- Now you can set a constant overvalued level (12.49 in my case)
- 1,3,7 are signaled correctly as cycle tops
- 9 is correctly not signaled as a cycle top
Caveats:
- Now you don't have bottom signals anymore
- 5 is still not signaled as cycle top
Let's see if we can further improve this:
Miner Revenue RSI (blue):
On the monthly, you can see that an RSI period of 6, an overvalued threshold of 90, and an undervalued threshold of 35 have given historically pretty good signals.
Advantages:
- Uses two simple and clear horizontal levels for undervalued and overvalued levels
- Signaling 1,3,5,7 correctly as cycle tops
- Correctly does not signal 9 as a cycle top
- Signaling 4,6,8 correctly as cycle bottoms
Caveats:
- Misses two as a cycle bottom, although it was a long time ago when the Bitcoin market was much less mature
- In the past, gave some early overvalued signals
Usage
Using the example above, you can apply these indicators to any timeframe you like and tweak their parameters to obtain signals for overvalued/undervalued BTC prices
You can show or hide any of the three indicators individually
Set overvalued/undervalued thresholds for each => the background will highlight in green (undervalued) or red (overvalued)
Set special parameters for the given indicators: correction factor for the Corrected Puell and RSI period for Revenue RSI
Show or hide halving events on the indicator panel
All parameters and colours are adjustable
RVI Divergence Detector with Custom SMA Filter (v6)This script enhances the classic Relative Vigor Index (RVI) by integrating divergence detection with a user-configurable SMA filter applied directly to the RVI oscillator. The goal is to help traders identify high-probability reversal and continuation signals by combining momentum analysis with dynamic baseline filtering.
How it works:
- The RVI measures the conviction behind price moves by comparing closing vs. opening prices relative to the high-low range over a 10-period window.
- Divergences are detected when price makes a new high/low but the RVI does not:
- Regular Bullish: Price makes a lower low, RVI makes a higher low → potential reversal up.
- Hidden Bullish: Price makes a higher low, RVI makes a lower low → trend continuation.
- Inverse logic applies for bearish cases.
- A customizable SMA (default: 14 periods) is plotted on the RVI line. This acts as a dynamic reference to assess whether divergences occur in strong momentum zones (far from SMA) or neutral zones (near SMA), helping filter out weaker signals.
- Users can adjust:
- Pivot lookback range (min/max bars)
- SMA period (1–200)
- Visibility of bullish/bearish and hidden/regular divergences
Why this version adds value:
Unlike basic RVI scripts, this adaptation introduces a configurable trend filter (SMA) and clear visual labeling ("D" for regular, "H" for hidden) with colored lines (green/red) connecting oscillator and price pivots—making divergences instantly recognizable. The logic is optimized for both scalping (short SMA) and swing trading (longer SMA).
Credits:
Based on the original RVI divergence concept by madoqa. This is an open-source adaptation under the Mozilla Public License 2.0. No financial advice. Use at your own risk.
Smart MACD Volume Trader# Smart MACD Volume Trader
## Overview
Smart MACD Volume Trader is an enhanced momentum indicator that combines the classic MACD (Moving Average Convergence Divergence) oscillator with an intelligent high-volume filter. This combination significantly reduces false signals by ensuring that trading signals are only generated when price momentum is confirmed by substantial volume activity.
The indicator supports over 24 different instruments including major and exotic forex pairs, precious metals (gold and silver), energy commodities (crude oil, natural gas), and industrial metals (copper). For forex and commodity traders, the indicator automatically maps to CME and COMEX futures contracts to provide accurate institutional-grade volume data.
## Originality and Core Concept
Traditional MACD indicators generate signals based solely on price momentum, which can result in numerous false signals during low-activity periods or ranging markets. This indicator addresses this critical weakness by introducing a volume confirmation layer with automatic institutional volume integration.
**What makes this approach original:**
- Signals are triggered only when MACD crossovers coincide with elevated volume activity
- Implements a lookback mechanism to detect volume spikes within recent bars
- Automatically detects and maps 24+ forex pairs and commodities to their corresponding CME and COMEX futures contracts
- Provides real institutional volume data for forex pairs where spot volume is unreliable
- Combines two independent market dimensions (price momentum and volume) into a single, actionable signal
- Includes intelligent asset detection that works across multiple exchanges and ticker formats
**The underlying principle:** Volume validates price movement. When institutional money enters the market, it creates volume signatures. By requiring high volume confirmation and using actual institutional volume data from futures markets, this indicator filters out weak price movements and focuses on trades backed by genuine market participation. The automatic futures mapping ensures that forex and commodity traders always have access to the most accurate volume data available, without manual configuration.
## How It Works
### MACD Component
The indicator calculates MACD using standard methodology:
1. **Fast EMA (default: 12 periods)** - Tracks short-term price momentum
2. **Slow EMA (default: 26 periods)** - Tracks longer-term price momentum
3. **MACD Line** - Difference between Fast EMA and Slow EMA
4. **Signal Line (default: 9-period SMA)** - Smoothed average of MACD line
**Crossover signals:**
- **Bullish:** MACD line crosses above Signal line (momentum turning positive)
- **Bearish:** MACD line crosses below Signal line (momentum turning negative)
### Volume Filter Component
The volume filter adds an essential confirmation layer:
1. **Volume Moving Average** - Calculates exponential MA of volume (default: 20 periods)
2. **High Volume Threshold** - Multiplies MA by ratio (default: 2.0x or 200%)
3. **Volume Detection** - Identifies bars where current volume exceeds threshold
4. **Lookback Period** - Checks if high volume occurred in recent bars (default: 5 bars)
**Signal logic:**
- Buy/Sell signals only trigger when BOTH conditions are met:
- MACD crossover/crossunder occurs
- High volume detected within lookback period
### Automatic CME Futures Integration
For forex traders, spot FX volume data can be unreliable or non-existent. This indicator solves this problem by automatically detecting forex pairs and mapping them to corresponding CME futures contracts with real institutional volume data.
**Supported Major Forex Pairs (7):**
- EURUSD → CME:6E1! (Euro FX Futures)
- GBPUSD → CME:6B1! (British Pound Futures)
- AUDUSD → CME:6A1! (Australian Dollar Futures)
- USDJPY → CME:6J1! (Japanese Yen Futures)
- USDCAD → CME:6C1! (Canadian Dollar Futures)
- USDCHF → CME:6S1! (Swiss Franc Futures)
- NZDUSD → CME:6N1! (New Zealand Dollar Futures)
**Supported Exotic Forex Pairs (4):**
- USDMXN → CME:6M1! (Mexican Peso Futures)
- USDRUB → CME:6R1! (Russian Ruble Futures)
- USDBRL → CME:6L1! (Brazilian Real Futures)
- USDZAR → CME:6Z1! (South African Rand Futures)
**Supported Cross Pairs (6):**
- EURJPY → CME:6E1! (Uses Euro Futures)
- GBPJPY → CME:6B1! (Uses British Pound Futures)
- EURGBP → CME:6E1! (Uses Euro Futures)
- AUDJPY → CME:6A1! (Uses Australian Dollar Futures)
- EURAUD → CME:6E1! (Uses Euro Futures)
- GBPAUD → CME:6B1! (Uses British Pound Futures)
**Supported Precious Metals (2):**
- Gold (XAUUSD, GOLD) → COMEX:GC1! (Gold Futures)
- Silver (XAGUSD, SILVER) → COMEX:SI1! (Silver Futures)
**Supported Energy Commodities (3):**
- WTI Crude Oil (USOIL, WTIUSD) → NYMEX:CL1! (Crude Oil Futures)
- Brent Oil (UKOIL) → NYMEX:BZ1! (Brent Crude Futures)
- Natural Gas (NATGAS) → NYMEX:NG1! (Natural Gas Futures)
**Supported Industrial Metals (1):**
- Copper (COPPER) → COMEX:HG1! (Copper Futures)
**How the automatic detection works:**
The indicator intelligently identifies the asset type by analyzing:
1. Exchange name (FX, OANDA, TVC, COMEX, NYMEX, etc.)
2. Currency pair pattern (6-letter codes like EURUSD, GBPUSD)
3. Commodity identifiers (XAU for gold, XAG for silver, OIL for crude)
When a supported instrument is detected, the indicator automatically switches to the corresponding futures contract for volume analysis. For stocks, cryptocurrencies, and other assets, the indicator uses the native volume data from the current chart.
**Visual feedback:**
An information table appears in the top-right corner of the MACD pane showing:
- Current chart symbol
- Exchange name
- Currency pair or asset name
- Volume source being used (highlighted in orange for futures, yellow for native volume)
- Current high volume status
This provides complete transparency about which data source the indicator is using for its volume analysis.
## How to Use
### Basic Setup
1. Add the indicator to your chart
2. The indicator displays in a separate pane (MACD) and overlay (signals/volume bars)
3. Default settings work well for most assets, but can be customized
### Signal Interpretation
### Visual Signals
**Visual Signals:**
- **Green "BUY" label** - Bullish MACD crossover confirmed by high volume
- **Red "SELL" label** - Bearish MACD crossunder confirmed by high volume
- **Green/Red candles** - Highlight bars with volume exceeding the threshold
- **Light green/red background** - Emphasizes signal bars on the chart
**Information Table:**
A detailed information table appears in the top-right corner of the MACD pane, providing real-time transparency about the indicator's operation:
- **Chart:** Current symbol being analyzed
- **Exchange:** The exchange or data feed being used
- **Pair:** The currency pair or asset name extracted from the ticker
- **Volume From:** The actual symbol used for volume analysis
- Orange color indicates CME or COMEX futures are being used (automatic institutional volume)
- Yellow color indicates native volume from the chart symbol is being used
- Hover tooltip shows whether automatic futures mapping is active
- **High Volume:** Current status showing YES (green) when volume exceeds threshold, NO (gray) otherwise
This table ensures complete transparency and allows you to verify that the correct volume source is being used for your analysis.
**Volume Analysis:**
- Gray histogram bars = Normal volume
- Red histogram bars = High volume (exceeds threshold)
- Green line = Volume moving average baseline
**MACD Analysis:**
- Blue line = MACD line (momentum indicator)
- Orange line = Signal line (trend confirmation)
- Gray dotted line = Zero line (bullish above, bearish below)
### Parameter Customization
**MACD Parameters:**
- Adjust Fast/Slow EMA lengths for different sensitivities
- Shorter periods = More signals, faster response
- Longer periods = Fewer signals, less noise
**Volume Parameters:**
- **Volume MA Period:** Higher values smooth volume analysis
- **High Volume Ratio:** Lower values (1.5x) = More signals; Higher values (3.0x) = Fewer, stronger signals
- **Volume Lookback Bars:** Controls how recent the volume spike must be
**Direction Filters:**
- **Only Buy Signals:** Enables long-only strategy mode
- **Only Sell Signals:** Enables short-only strategy mode
### Alert Configuration
The indicator includes three alert types:
1. **Buy Signal Alert** - Triggers when bullish signal appears
2. **Sell Signal Alert** - Triggers when bearish signal appears
3. **High Volume Alert** - Triggers when volume exceeds threshold
To set up alerts:
1. Click the indicator name → "Add alert on Smart MACD Volume Trader"
2. Select desired alert condition
3. Configure notification method (popup, email, webhook, etc.)
## Trading Strategy Guidelines
### Best Practices
**Recommended markets:**
- Liquid stocks (large-cap, high daily volume)
- Major forex pairs (EURUSD, GBPUSD, USDJPY, AUDUSD, USDCAD, USDCHF, NZDUSD)
- Exotic forex pairs (USDMXN, USDRUB, USDBRL, USDZAR)
- Cross pairs (EURJPY, GBPJPY, EURGBP, AUDJPY, EURAUD, GBPAUD)
- Precious metals (Gold, Silver with automatic COMEX futures mapping)
- Energy commodities (Crude Oil, Natural Gas with automatic NYMEX futures mapping)
- Industrial metals (Copper with automatic COMEX futures mapping)
- Major cryptocurrency pairs
- Index futures and ETFs
**Timeframe recommendations:**
- **Day trading:** 5-minute to 15-minute charts
- **Swing trading:** 1-hour to 4-hour charts
- **Position trading:** Daily charts
**Risk management:**
- Use signals as entry confirmation, not standalone strategy
- Combine with support/resistance levels
- Consider overall market trend direction
- Always use stop-loss orders
### Strategy Examples
**Trend Following Strategy:**
1. Identify overall trend using higher timeframe (e.g., daily chart)
2. Trade only in trend direction
3. Use "Only Buy" filter in uptrends, "Only Sell" in downtrends
4. Enter on signal, exit on opposite signal or at resistance/support
**Volume Breakout Strategy:**
1. Wait for consolidation period (low volume, tight MACD range)
2. Enter when signal appears with high volume (confirms breakout)
3. Target previous swing highs/lows
4. Stop loss below/above recent consolidation
**Forex Scalping Strategy (with automatic CME futures):**
1. The indicator automatically detects forex pairs and uses CME futures volume
2. Trade during active sessions only (use session filter)
3. Focus on quick profits (10-20 pips)
4. Exit at opposite signal or profit target
**Commodities Trading Strategy (Gold, Silver, Oil):**
1. The indicator automatically maps to COMEX and NYMEX futures contracts
2. Trade during high-liquidity sessions (overlap of major markets)
3. Use the high volume confirmation to identify institutional entry points
4. Combine with key support and resistance levels for entries
5. Monitor the information table to confirm futures volume is being used (orange color)
6. Exit on opposite MACD signal or at predefined profit targets
## Why This Combination Works
### The Volume Advantage
Studies consistently show that price movements accompanied by high volume are more likely to continue, while low-volume movements often reverse. This indicator leverages this principle by requiring volume confirmation.
**Key benefits:**
1. **Reduced False Signals:** Eliminates MACD whipsaws during low-volume consolidation
2. **Confirmation Bias:** Two independent indicators (price momentum + volume) agreeing
3. **Institutional Alignment:** High volume often indicates institutional participation
4. **Trend Validation:** Volume confirms that price momentum has "conviction"
### Statistical Edge
By combining two uncorrelated signals (MACD crossovers and volume spikes), the indicator creates a higher-probability setup than either signal alone. The lookback mechanism ensures signals aren't missed if volume spike slightly precedes the MACD cross.
## Supported Exchanges and Automatic Detection
The indicator includes intelligent asset detection that works across multiple exchanges and ticker formats:
**Forex Exchanges (Automatic CME Mapping):**
- FX (TradingView forex feed)
- OANDA
- FXCM
- SAXO
- FOREXCOM
- PEPPERSTONE
- EASYMARKETS
- FX_IDC
**Commodity Exchanges (Automatic COMEX/NYMEX Mapping):**
- TVC (TradingView commodity feed)
- COMEX (directly)
- NYMEX (directly)
- ICEUS
**Other Asset Classes (Native Volume):**
- Stock exchanges (NASDAQ, NYSE, AMEX, etc.)
- Cryptocurrency exchanges (BINANCE, COINBASE, KRAKEN, etc.)
- Index providers (SP, DJ, etc.)
The detection algorithm analyzes three factors:
1. Exchange prefix in the ticker symbol
2. Pattern matching for currency pairs (6-letter codes)
3. Commodity identifiers in the symbol name
This ensures accurate automatic detection regardless of which data feed or exchange you use for charting. The information table in the top-right corner always displays which volume source is being used, providing complete transparency.
## Technical Details
**Calculations:**
- MACD Fast MA: EMA(close, fastLength)
- MACD Slow MA: EMA(close, slowLength)
- MACD Line: Fast MA - Slow MA
- Signal Line: SMA(MACD Line, signalLength)
- Volume MA: Exponential MA of volume
- High Volume: Current volume >= Volume MA × Ratio
**Signal logic:**
```
Buy Signal = (MACD crosses above Signal) AND (High volume in last N bars)
Sell Signal = (MACD crosses below Signal) AND (High volume in last N bars)
```
## Parameters Reference
| Parameter | Default | Description |
|-----------|---------|-------------|
| Volume Symbol | Blank | Manual override for volume source (leave blank for automatic detection) |
| Use CME Futures | False | Legacy option (automatic detection is now built-in) |
| Alert Session | 1530-2200 | Active session time range for alerts |
| Timezone | UTC+1 | Timezone for alert sessions |
| Volume MA Period | 20 | Number of periods for volume moving average |
| High Volume Ratio | 2.0 | Volume threshold multiplier (2.0 = 200% of average) |
| Volume Lookback | 5 | Number of bars to check for high volume confirmation |
| MACD Fast Length | 12 | Fast EMA period for MACD calculation |
| MACD Slow Length | 26 | Slow EMA period for MACD calculation |
| MACD Signal Length | 9 | Signal line SMA period |
| Only Buy | False | Filter to show only bullish signals |
| Only Sell | False | Filter to show only bearish signals |
| Show Signals | True | Display buy and sell labels on chart |
## Optimization Tips
**For volatile markets (crypto, small caps):**
- Increase High Volume Ratio to 2.5-3.0
- Reduce Volume Lookback to 3-4 bars
- Consider faster MACD settings (8, 17, 9)
**For stable markets (large-cap stocks, bonds):**
- Decrease High Volume Ratio to 1.5-1.8
- Increase Volume MA Period to 30-50
- Use standard MACD settings
**For forex (with automatic CME futures):**
- The indicator automatically uses CME futures when forex pairs are detected
- Set appropriate trading session based on your timezone
- Use Volume Lookback of 5-7 bars
- Consider session-based alerts only
- Monitor the information table to verify correct futures mapping
**For commodities (Gold, Silver, Oil, Copper):**
- The indicator automatically maps to COMEX and NYMEX futures
- Increase High Volume Ratio to 2.0-2.5 for metals
- Use slightly higher Volume MA Period (25-30) for smoother analysis
- Trade during active market hours for best volume data
- The information table will show the futures contract being used (orange highlight)
## Limitations and Considerations
**What this indicator does NOT do:**
- Does not predict future price direction
- Does not guarantee profitable trades
- Does not replace proper risk management
- Does not work well in extremely low-volume conditions
**Market conditions to avoid:**
- Pre-market and after-hours sessions (low volume)
- Major news events (volatile, unpredictable volume)
- Holidays and low-liquidity periods
- Extremely low float stocks
## Conclusion
Smart MACD Volume Trader represents a significant evolution of the traditional MACD indicator by combining volume confirmation with automatic institutional volume integration. This dual-confirmation approach significantly improves signal quality by filtering out low-conviction price movements and ensuring traders work with accurate volume data.
The indicator's automatic detection and mapping system supports over 24 instruments across forex, commodities, and metals markets. By intelligently switching to CME and COMEX futures contracts when appropriate, the indicator provides forex and commodity traders with the same quality of volume data that stock traders naturally have access to.
This indicator is particularly valuable for traders who want to:
- Align their entries with institutional money flow
- Avoid getting trapped in false breakouts
- Trade forex pairs with reliable volume data
- Access accurate volume information for gold, silver, and energy commodities
- Combine momentum and volume analysis in a single, streamlined tool
Whether you are day trading stocks, swing trading forex pairs, or positioning in commodities markets, this indicator provides a robust framework for identifying high-probability momentum trades backed by genuine institutional participation. The automatic futures mapping works seamlessly across all supported instruments, requiring no manual configuration or expertise in futures markets.
---
## Support and Updates
This indicator is actively maintained and updated based on user feedback and market conditions. For questions about implementation or custom modifications, please use the comments section below.
**Disclaimer:** This indicator is for educational and informational purposes only. Past performance does not guarantee future results. Always conduct your own analysis and risk management before trading.
Relative Vigor Index with Divergence and SMA FilterThis script implements the Relative Vigor Index (RVI), originally developed by John Ehlers, enhanced with three practical analytical layers:
1. Configurable SMA filter applied to the RVI line (default: 14 periods) to smooth noise and clarify the underlying momentum trend.
2. Automated divergence detection between price action and the RVI oscillator, identifying both:
- Regular divergences ("R"): potential reversal signals (e.g., price makes a lower low while RVI makes a higher low).
- Hidden divergences ("H"): potential continuation signals (e.g., price makes a higher low while RVI makes a lower low).
3.Visual aids: labeled markers ("R"/"H") and connecting lines to make divergence patterns immediately recognizable.
Unlike basic RVI implementations, this version is designed to highlight momentum-price decoupling—a core concept in technical analysis—using robust pivot detection (`ta.pivotlow`/`ta.pivothigh`) with user-defined lookback and search ranges (default: 5–60 bars). The SMA filter helps traders distinguish between genuine momentum shifts and short-term volatility.
How it works:
- The RVI is calculated as the ratio of smoothed (close – open) to smoothed (high – low), reflecting the idea that in uptrends, closes tend to occur near highs, and in downtrends, near lows.
- Divergences are confirmed only when both a valid price pivot and a corresponding RVI pivot occur within the specified bar range.
- Hidden bearish divergences are disabled by default to reduce noise on shorter timeframes.
Suggested use:
- Use regular bullish divergences near negative RVI extremes as potential long setups.
- Watch for regular bearish divergences at positive RVI peaks as early reversal warnings.
- Combine with support/resistance or trend structure for higher-confidence entries.
This script is not a simple mashup: the integration of divergence logic with the RVI’s unique behavior, configurable sensitivity, and clean visualization provides a cohesive analytical tool that goes beyond standard implementations.
> Disclaimer: This script is for educational and informational purposes only. It does not constitute financial, investment, or trading advice. Past performance is not indicative of future results.
—
Credits:
- Relative Vigor Index concept: John Ehlers
- Divergence methodology: Standard technical analysis practice
- Implementation and enhancements: © Carlos Mauricio Vizcarra (2025)
- Licensed under MPL 2.0
RVI with SMA Smoothing and Divergence SignalsThis script enhances the Relative Volatility Index (RVI)—originally introduced by Donald Dorsey in 1993—by integrating three complementary analytical features:
1. SMA-based smoothing of the RVI line to reduce noise and clarify the underlying volatility momentum trend.
2. Automated detection of regular and hidden divergences between price action (highs/lows) and RVI pivots, using robust `ta.pivotlow` and `ta.pivothigh` logic with configurable lookback and search ranges.
3. Visual labels ("R" for regular, "H" for hidden) and color-coded pivot markers to help traders quickly identify potential reversal or continuation zones.
Unlike basic RVI implementations, this version is designed to highlight momentum-price decoupling, a key concept in technical analysis. The divergence engine is synchronized with RVI’s unique 0–100 scale and volatility-based calculation, ensuring signals are contextually relevant—not generic overlays.
How it works:
- RVI is computed using standard deviation of directional price changes, normalized to 0–100.
- A user-defined SMA (default: 14 periods) smooths the RVI for trend clarity.
- Divergences are confirmed only when both a valid price pivot and a corresponding RVI pivot occur within a configurable bar range (default: 5–60 bars).
- Hidden bearish divergences are disabled by default to reduce noise on short-term charts.
Suggested use:
- Regular bullish divergences near the 20 (oversold) level may signal exhaustion of a downtrend.
- Regular bearish divergences above 80 (overbought) can warn of upward momentum loss.
- Combine with price structure (support/resistance) for higher-probability setups.
This script is **not a simple mashup**: the integration of divergence logic with RVI’s volatility-based nature, parameterized sensitivity controls, and clean visualization provides a cohesive analytical tool not found in standard indicators.
> Disclaimer: This script is for educational and informational purposes only. It does not constitute financial, investment, or trading advice. Past performance is not indicative of future results.
—
Créditos:
- RVI concept: Donald Dorsey (1993)
- Divergence methodology: Standard technical analysis practice
- Implementation and enhancements: © Carlos Mauricio Vizcarra (2025)
- Licensed under MPL 2.0
RSI FlipIndicator Description: RSI Flip (30/70 Threshold)
This indicator uses a 7-period Relative Strength Index (RSI) to detect potential market reversals based on classic momentum thresholds:
- RSI < 30 → triggers a Long Deal Signal (1) indicating potential bullish reversal.
- RSI > 70 → triggers a Short Deal Signal (2) indicating potential bearish reversal.
🔧 Features:
- Backtest-compatible output: Hidden plots emit 1 for long and 2 for short, enabling seamless integration with strategy scripts.
- Bias tracking: Internal bias state updates on each trigger, allowing for modular lifecycle logic.
- Background tinting ready: The bias variable can be used to drive visual overlays or downstream automation.
🧩 Integration Notes:
- Designed for symbol-specific use — no external feeds or dependencies.
- Ideal for modular signal stacking, lifecycle-safe deal initiation, or audit-grade strategy mapping.
Hidden Impulse═══════════════════════════════════════════════════════════════════
HIDDEN IMPULSE - Multi-Timeframe Momentum Detection System
═══════════════════════════════════════════════════════════════════
OVERVIEW
Hidden Impulse is an advanced momentum oscillator that combines the Schaff Trend Cycle (STC) and Force Index into a comprehensive multi-timeframe trading system. Unlike standard implementations of these indicators, this script introduces three distinct trading setups with specific entry conditions, multi-timeframe confirmation, and trend filtering.
═══════════════════════════════════════════════════════════════════
ORIGINALITY & KEY FEATURES
This indicator is original in the following ways:
1. DUAL-TIMEFRAME STC ANALYSIS
Standard STC implementations work on a single timeframe. This script
simultaneously analyzes STC on both your trading timeframe and a higher
timeframe, providing trend context and filtering out low-probability signals.
2. FORCE INDEX INTEGRATION
The script combines STC with Force Index (volume-weighted price momentum)
to confirm the strength behind price moves. This combination helps identify
when momentum shifts are backed by genuine buying/selling pressure.
3. THREE DISTINCT TRADING SETUPS
Rather than generic overbought/oversold signals, the indicator provides
three specific, rule-based setups:
- Setup A: Classic trend-following entries with multi-timeframe confirmation
- Setup B: Divergence-based reversal entries (highest probability)
- Setup C: Mean-reversion bounce trades at extreme levels
4. INTELLIGENT FILTERING
All signals are filtered through:
- 50 EMA trend direction (prevents counter-trend trades)
- Higher timeframe STC alignment (ensures macro trend agreement)
- Force Index confirmation (validates volume support)
═══════════════════════════════════════════════════════════════════
HOW IT WORKS - TECHNICAL EXPLANATION
SCHAFF TREND CYCLE (STC) CALCULATION:
The STC is a cyclical oscillator that combines MACD concepts with stochastic
smoothing to create earlier and smoother trend signals.
Step 1: Calculate MACD
- Fast MA = EMA(close, Length1) — default 23
- Slow MA = EMA(close, Length2) — default 50
- MACD Line = Fast MA - Slow MA
Step 2: First Stochastic Smoothing
- Apply stochastic calculation to MACD
- Stoch1 = 100 × (MACD - Lowest(MACD, Smoothing)) / (Highest(MACD, Smoothing) - Lowest(MACD, Smoothing))
- Smooth result with EMA(Stoch1, Smoothing) — default 10
Step 3: Second Stochastic Smoothing
- Apply stochastic calculation again to the smoothed stochastic
- This creates the final STC value between 0-100
The dual stochastic smoothing makes STC more responsive than MACD while
being smoother than traditional stochastics.
FORCE INDEX CALCULATION:
Force Index measures the power behind price movements by incorporating volume:
Force Raw = (Close - Close ) × Volume
Force Index = EMA(Force Raw, Period) — default 13
Interpretation:
- Positive Force Index = Buying pressure (bulls in control)
- Negative Force Index = Selling pressure (bears in control)
- Force Index crossing zero = Momentum shift
- Divergences with price = Weakening momentum (reversal signal)
TREND FILTER:
A 50-period EMA serves as the trend filter:
- Price above EMA50 = Uptrend → Only LONG signals allowed
- Price below EMA50 = Downtrend → Only SHORT signals allowed
This prevents counter-trend trading which accounts for most losing trades.
═══════════════════════════════════════════════════════════════════
THE THREE TRADING SETUPS - DETAILED
SETUP A: CLASSIC MOMENTUM ENTRY
Concept: Enter when STC exits oversold/overbought zones with trend confirmation
LONG CONDITIONS:
1. Higher timeframe STC > 25 (macro trend is up)
2. Primary timeframe STC crosses above 25 (momentum turning up)
3. Force Index crosses above 0 OR already positive (volume confirms)
4. Price above 50 EMA (local trend is up)
SHORT CONDITIONS:
1. Higher timeframe STC < 75 (macro trend is down)
2. Primary timeframe STC crosses below 75 (momentum turning down)
3. Force Index crosses below 0 OR already negative (volume confirms)
4. Price below 50 EMA (local trend is down)
Best for: Trending markets, continuation trades
Win rate: Moderate (60-65%)
Risk/Reward: 1:2 to 1:3
───────────────────────────────────────────────────────────────────
SETUP B: DIVERGENCE REVERSAL (HIGHEST PROBABILITY)
Concept: Identify exhaustion points where price makes new extremes but
momentum (Force Index) fails to confirm
BULLISH DIVERGENCE:
1. Price makes a lower low (LL) over 10 bars
2. Force Index makes a higher low (HL) — refuses to follow price down
3. STC is below 25 (oversold condition)
Trigger: STC starts rising AND Force Index crosses above zero
BEARISH DIVERGENCE:
1. Price makes a higher high (HH) over 10 bars
2. Force Index makes a lower high (LH) — refuses to follow price up
3. STC is above 75 (overbought condition)
Trigger: STC starts falling AND Force Index crosses below zero
Why this works: Divergences signal that the current trend is losing steam.
When volume (Force Index) doesn't confirm new price extremes, a reversal
is likely.
Best for: Reversal trading, range-bound markets
Win rate: High (70-75%)
Risk/Reward: 1:3 to 1:5
───────────────────────────────────────────────────────────────────
SETUP C: QUICK BOUNCE AT EXTREMES
Concept: Catch rapid mean-reversion moves when price touches EMA50 in
extreme STC zones
LONG CONDITIONS:
1. Price touches 50 EMA from above (pullback in uptrend)
2. STC < 15 (extreme oversold)
3. Force Index > 0 (buyers stepping in)
SHORT CONDITIONS:
1. Price touches 50 EMA from below (pullback in downtrend)
2. STC > 85 (extreme overbought)
3. Force Index < 0 (sellers stepping in)
Best for: Scalping, quick mean-reversion trades
Win rate: Moderate (55-60%)
Risk/Reward: 1:1 to 1:2
Note: Use tighter stops and quick profit-taking
═══════════════════════════════════════════════════════════════════
HOW TO USE THE INDICATOR
STEP 1: CONFIGURE TIMEFRAMES
Primary Timeframe (STC - Primary Timeframe):
- Leave empty to use your current chart timeframe
- This is where you'll take trades
Higher Timeframe (STC - Higher Timeframe):
- Default: 30 minutes
- Recommended ratios:
* 5min chart → 30min higher TF
* 15min chart → 1H higher TF
* 1H chart → 4H higher TF
* Daily chart → Weekly higher TF
───────────────────────────────────────────────────────────────────
STEP 2: ADJUST STC PARAMETERS FOR YOUR MARKET
Default (23/50/10) works well for stocks and forex, but adjust for:
CRYPTO (volatile):
- Length 1: 15
- Length 2: 35
- Smoothing: 8
(Faster response for rapid price movements)
STOCKS (standard):
- Length 1: 23
- Length 2: 50
- Smoothing: 10
(Balanced settings)
FOREX MAJORS (slower):
- Length 1: 30
- Length 2: 60
- Smoothing: 12
(Filters out noise in 24/7 markets)
───────────────────────────────────────────────────────────────────
STEP 3: ENABLE YOUR PREFERRED SETUPS
Toggle setups based on your trading style:
Conservative Trader:
✓ Setup B (Divergence) — highest win rate
✗ Setup A (Classic) — only in strong trends
✗ Setup C (Bounce) — too aggressive
Trend Trader:
✓ Setup A (Classic) — primary signals
✓ Setup B (Divergence) — for entries on pullbacks
✗ Setup C (Bounce) — not suitable for trending
Scalper:
✓ Setup C (Bounce) — quick in-and-out
✓ Setup B (Divergence) — high probability scalps
✗ Setup A (Classic) — too slow
───────────────────────────────────────────────────────────────────
STEP 4: READ THE SIGNALS
ON THE CHART:
Labels appear when conditions are met:
Green labels:
- "LONG A" — Setup A long entry
- "LONG B DIV" — Setup B divergence long (best signal)
- "LONG C" — Setup C bounce long
Red labels:
- "SHORT A" — Setup A short entry
- "SHORT B DIV" — Setup B divergence short (best signal)
- "SHORT C" — Setup C bounce short
IN THE INDICATOR PANEL (bottom):
- Blue line = Primary timeframe STC
- Orange dots = Higher timeframe STC (optional)
- Green/Red bars = Force Index histogram
- Dashed lines at 25/75 = Entry/Exit zones
- Background shading = Oversold (green) / Overbought (red)
INFO TABLE (top-right corner):
Shows real-time status:
- STC values for both timeframes
- Force Index direction
- Price position vs EMA
- Current trend direction
- Active signal type
═══════════════════════════════════════════════════════════════════
TRADING STRATEGY & RISK MANAGEMENT
ENTRY RULES:
Priority ranking (best to worst):
1st: Setup B (Divergence) — wait for these
2nd: Setup A (Classic) — in confirmed trends only
3rd: Setup C (Bounce) — scalping only
Confirmation checklist before entry:
☑ Signal label appears on chart
☑ TREND in info table matches signal direction
☑ Higher timeframe STC aligned (check orange dots or table)
☑ Force Index confirming (check histogram color)
───────────────────────────────────────────────────────────────────
STOP LOSS PLACEMENT:
Setup A (Classic):
- LONG: Below recent swing low
- SHORT: Above recent swing high
- Typical: 1-2 ATR distance
Setup B (Divergence):
- LONG: Below the divergence low
- SHORT: Above the divergence high
- Typical: 0.5-1.5 ATR distance
Setup C (Bounce):
- LONG: 5-10 pips below EMA50
- SHORT: 5-10 pips above EMA50
- Typical: 0.3-0.8 ATR distance
───────────────────────────────────────────────────────────────────
TAKE PROFIT TARGETS:
Conservative approach:
- Exit when STC reaches opposite level
- LONG: Exit when STC > 75
- SHORT: Exit when STC < 25
Aggressive approach:
- Hold until opposite signal appears
- Trail stop as STC moves in your favor
Partial profits:
- Take 50% at 1:2 risk/reward
- Let remaining 50% run to target
───────────────────────────────────────────────────────────────────
WHAT TO AVOID:
❌ Trading Setup A in sideways/choppy markets
→ Wait for clear trend or use Setup B only
❌ Ignoring higher timeframe STC
→ Always check orange dots align with your direction
❌ Taking signals against the major trend
→ If weekly trend is down, be cautious with longs
❌ Overtrading Setup C
→ Maximum 2-3 bounce trades per session
❌ Trading during low volume periods
→ Force Index becomes unreliable
═══════════════════════════════════════════════════════════════════
ALERTS CONFIGURATION
The indicator includes 8 alert types:
Individual setup alerts:
- "Setup A - LONG" / "Setup A - SHORT"
- "Setup B - DIV LONG" / "Setup B - DIV SHORT" ⭐ recommended
- "Setup C - BOUNCE LONG" / "Setup C - BOUNCE SHORT"
Combined alerts:
- "ANY LONG" — fires on any long signal
- "ANY SHORT" — fires on any short signal
Recommended alert setup:
- Create "Setup B - DIV LONG" and "Setup B - DIV SHORT" alerts
- These are the highest probability signals
- Set "Once Per Bar Close" to avoid false alerts
═══════════════════════════════════════════════════════════════════
VISUALIZATION SETTINGS
Show Labels on Chart:
Toggle on/off the signal labels (green/red)
Disable for cleaner chart once you're familiar with the indicator
Show Higher TF STC:
Toggle the orange dots showing higher timeframe STC
Useful for visual confirmation of multi-timeframe alignment
Info Panel:
Cannot be disabled — always shows current status
Positioned top-right to avoid chart interference
═══════════════════════════════════════════════════════════════════
EXAMPLE TRADE WALKTHROUGH
SETUP B DIVERGENCE LONG EXAMPLE:
1. Market Context:
- Price in downtrend, below 50 EMA
- Multiple lower lows forming
- STC below 25 (oversold)
2. Divergence Formation:
- Price makes new low at $45.20
- Force Index refuses to make new low (higher low forms)
- This indicates selling pressure weakening
3. Signal Trigger:
- STC starts turning up
- Force Index crosses above zero
- Label appears: "LONG B DIV"
4. Trade Execution:
- Entry: $45.50 (current price at signal)
- Stop Loss: $44.80 (below divergence low)
- Target 1: $47.90 (STC reaches 75) — risk/reward 1:3.4
- Target 2: Opposite signal or trail stop
5. Trade Management:
- Price rallies to $47.20
- STC reaches 68 (approaching target zone)
- Take 50% profit, move stop to breakeven
- Exit remaining at $48.10 when STC crosses 75
Result: 3.7R gain
═══════════════════════════════════════════════════════════════════
ADVANCED TIPS
1. MULTI-TIMEFRAME CONFLUENCE
For highest probability trades, wait for:
- Primary TF signal
- Higher TF STC aligned (>25 for longs, <75 for shorts)
- Even higher TF trend in same direction (manual check)
2. VOLUME CONFIRMATION
Watch the Force Index histogram:
- Increasing bar size = Strengthening momentum
- Decreasing bar size = Weakening momentum
- Use this to gauge signal strength
3. AVOID THESE MARKET CONDITIONS
- Major news events (Force Index becomes erratic)
- Market open first 30 minutes (volatility spikes)
- Low liquidity instruments (Force Index unreliable)
- Extreme trending days (wait for pullbacks)
4. COMBINE WITH SUPPORT/RESISTANCE
Best signals occur near:
- Key horizontal levels
- Fibonacci retracements
- Previous day's high/low
- Psychological round numbers
5. SESSION AWARENESS
- Asia session: Use lower timeframes, Setup C works well
- London session: Setup A and B both effective
- New York session: All setups work, highest volume
═══════════════════════════════════════════════════════════════════
INDICATOR WINDOWS LAYOUT
MAIN CHART:
- Price action
- 50 EMA (green/red)
- Signal labels
- Info panel
INDICATOR WINDOW:
- STC oscillator (blue line, 0-100 scale)
- Higher TF STC (orange dots, optional)
- Force Index histogram (green/red bars)
- Reference levels (25, 50, 75)
- Background zones (green oversold, red overbought)
═══════════════════════════════════════════════════════════════════
PERFORMANCE OPTIMIZATION
For best results:
Backtesting:
- Test on your specific instrument and timeframe
- Adjust STC parameters if win rate < 55%
- Record which setup works best for your market
Position Sizing:
- Risk 1-2% per trade
- Setup B can use 2% risk (higher win rate)
- Setup C should use 1% risk (lower win rate)
Trade Frequency:
- Setup B: 2-5 signals per week (be patient)
- Setup A: 5-10 signals per week
- Setup C: 10+ signals per week (scalping)
═══════════════════════════════════════════════════════════════════
CREDITS & REFERENCES
This indicator builds upon established technical analysis concepts:
Schaff Trend Cycle:
- Developed by Doug Schaff (1996)
- Original concept published in Technical Analysis of Stocks & Commodities
- Implementation based on standard STC formula
Force Index:
- Developed by Dr. Alexander Elder
- Described in "Trading for a Living" (1993)
- Classic volume-momentum indicator
The multi-timeframe integration, three-setup system, and specific
entry conditions are original contributions of this indicator.
═══════════════════════════════════════════════════════════════════
DISCLAIMER
This indicator is a technical analysis tool and does not guarantee profits.
Past performance is not indicative of future results. Always:
- Use proper risk management
- Test on demo account first
- Combine with fundamental analysis
- Never risk more than you can afford to lose
═══════════════════════════════════════════════════════════════════
SUPPORT & QUESTIONS
If you find this indicator helpful, please:
- Leave a like and comment
- Share your feedback and results
- Report any bugs or issues
For questions about usage or optimization for specific markets,
feel free to comment below.
═════════════════════════════════════════════════════════════
Blue Dot Red DotInspired by Dr Wish
This script is a confluence indicator designed to identify potential trend reversals or "mean reversion" trade setups. It plots buy (blue) and sell (red) dots directly on your price chart.
The core strategy is to find moments where price is overextended (using Bollinger Bands) and momentum is simultaneously reversing (using the Stochastic Oscillator). A signal is only generated when both of these conditions are met.
Core Components
The script combines two classic technical indicators:
Bollinger Bands (BB):
These create a "channel" around the price based on a simple moving average (the basis) and a standard deviation (dev).
Upper Band: Basis + (2.0 * StdDev)
Lower Band: Basis - (2.0 * StdDev)
In this script, the bands are used to identify when the price has moved significantly far from its recent average, suggesting it's "overbought" (at the upper band) or "oversold" (at the lower band) and may be due for a pullback.
Stochastic Oscillator:
This is a momentum oscillator that compares a closing price to its price range over a certain period.
It consists of two lines: %K (the main, faster line) and %D (a moving average of %K, the slower signal line).
It's used to identify overbought and oversold momentum conditions and, more importantly, momentum shifts, which are signaled by the %K and %D lines crossing.
Signal Logic: How the Dots Are Generated
This script's "secret sauce" is that it demands three specific conditions to be true at the same time before plotting a dot.
🔵 Blue Dot (Buy Signal)
A blue dot will appear below a price bar if all three of these conditions are met:
Stochastic Crossover: The faster %K line crosses above the slower %D line (ta.crossover(k, d)). This signals that short-term momentum is starting to turn bullish.
Was Oversold: On the previous bar, the %K line was below the "Oversold Threshold" (was_oversold = k < oversold). This ensures the bullish crossover is happening from an oversold (or at least bearish) momentum state.
Note: The default oversold threshold is set to 50. This is a key detail. It means the script is looking for a bullish crossover that originates from anywhere in the bottom half of the Stochastic range, not just the traditional "extreme" oversold area (like 20).
Price Extension: Within the last 3 bars (the current bar or the two before it), the price's low must have touched or gone below the lower Bollinger Band (bb_touch_lower). This confirms that the price itself is in an "oversold" or overextended area.
In plain English: A blue dot appears when the price has recently dipped to an extreme low (touching the lower BB) and its underlying momentum has just started to turn back up (Stoch cross from the lower half).
🔴 Red Dot (Sell Signal)
A red dot will appear above a price bar if all three of these conditions are met:
Stochastic Crossunder: The faster %K line crosses below the slower %D line (ta.crossunder(k, d)). This signals that short-term momentum is starting to turn bearish.
Was Overbought: On the previous bar, the %K line was above the "Overbought Threshold" (was_overbought = k > overbought). The default for this is 80, which is a traditional overbought level.
Price Extension: Within the last 3 bars (the current bar or the two before it), the price's high must have touched or gone above the upper Bollinger Band (bb_touch_upper). This confirms that the price itself is in an "overbought" or overextended area.
A red dot appears when the price has recently spiked to an extreme high (touching the upper BB) and its underlying momentum has just started to roll over and turn back down (Stoch cross from the overbought zone).
LegendaryGoldTraderLegendaryGoldTrader Signals – TradingView Indicator
This script is a comprehensive multi-indicator signal tool for XAUUSD (Gold), optimized for short timeframes from 1 to 15 minutes. It combines trend, momentum, and entry indicators to help identify potential Long and Short trading opportunities.
Features:
EMA (Trend Filter): Two EMAs determine the short-term trend direction.
RSI: Highlights overbought and oversold conditions.
MACD: Detects momentum shifts and trend changes.
Stochastic: Provides precise entry timing.
ADX: Confirms trend strength and filters signals during weak trends.
3-Candle Pattern (optional): Identifies short-term reversal patterns for Long or Short entries.
BUY/SELL Labels: Clear signals displayed above or below the chart.
Info Window: Displays all indicator signals and trend strength at a glance.
Highlights:
Fully configurable indicators and signals.
3-Candle Pattern can be enabled or disabled.
Suitable for fast intraday trading on minute charts, but flexible for other timeframes.
Supports trend confirmation and false-signal filtering for controlled entries.
Glassnode Whale Oscillator 🐳Glassnode Whale Oscillator🐳
Glassnode Whale Oscillator: tracks BTC accumulation/distribution by whales. Normalized (0-100) based on WSPC (±50k BTC), smoothed SMA. Signals: >60 – bullish (buy), <40 – bearish (sell).
RSI Colored by Relative StrengthThis indicator enhances the traditional RSI by combining it with Relative Strength (RS) — the ratio of an asset’s price to a chosen benchmark (e.g., SPY, QQQ, BTCUSD) — to create a more accurate, powerful, and dynamic momentum confirmation tool.
Instead of relying solely on RSI’s internal momentum, this version color-codes RSI values and backgrounds based on whether the asset is outperforming, underperforming, or neutral relative to the benchmark, not only identifying the RSI value, but color codes it in relation to the overall market to give more accurate confirmations.
• RS > 1 → The asset is outperforming the benchmark (relative strength).
• RS < 1 → The asset is underperforming.
• RS ≈ 1 → Neutral or moving in sync with the benchmark.
Gradient background zones:
• Green tones = outperformance (RS > 1).
• Red tones = underperformance (RS < 1).
• Gray neutral band = parity (RS ≈ 1).
Intensity adjusts dynamically based on how far RS deviates from 1, giving an at-a-glance view of market leadership strength.
• Color-coded RSI line: Green when RS > 1, red when RS < 1.
• Optional markers and labels show confirmed RS+RSI crossovers with smart spacing to prevent clutter.
• Alerts included for bullish and bearish RS+RSI alignment events.
How to Use
1. Add your preferred benchmark symbol (default: SPY).
2. Move this indicator into the same pane as your RSI (No need to overlay, does so automatically) and can also be used standalone.
3. Watch for:
• Green RSI & background: Significant momentum strength (asset trending upward and outpacing the market).
• Red RSI & background: False or insignificant momentum (asset lagging).
• Gray zone: neutral phase — consolidation or rotation period.
Use this as a trend-confirmation filter rather than a signal generator.
For example:
• Confirm and refine breakout entries when RS > 1 (RSI support = stronger conviction).
• Take profits when RSI weakens and RS slips below 1.
Dual RVI Divergence Detector: Volatility + Vigor
This script combines two distinct but complementary momentum oscillators—the Relative Volatility Index (RVI Volatility) by Donald Dorsey and the Relative Vigor Index (RVI Vigor) by John Ehlers—into a single, unified divergence detection system.
Why combine them?
RVI Volatility measures the directional consistency of volatility, helping identify overbought/oversold conditions based on price dispersion.
RVI Vigor measures the strength of price movement relative to its range, reflecting market conviction through the relationship between open/close and high/low.
While both are called "RVI", they are fundamentally different indicators with unique mathematical foundations. Using them together provides convergent confirmation: when both oscillators show bullish (or bearish) divergence at the same time, the signal gains statistical robustness. This reduces false positives compared to using either in isolation.
Key Original Enhancements (by Carlos Mauricio Vizcarra, 2025):
Dynamic normalization: The Vigor oscillator (normally centered near 0) is scaled to the 0–100 range of the Volatility RVI, enabling direct visual comparison in a single panel without distortion.
Independent divergence logic: Each oscillator retains its own pivot detection, divergence conditions (regular + hidden), and visual markers ("R"/"H" labels + connecting lines).
User-controlled visibility: Traders can toggle each RVI on/off to focus on one signal or compare both.
Full compliance with MPL 2.0: Original authors are credited, and all reused concepts are properly attributed.
How to Use:
Look for aligned divergences (e.g., bullish divergence on both RVIs) for high-probability reversals.
Use hidden divergences for trend-continuation signals.
The SMA filters (configurable) help smooth noise.
All alerts are included for automated scanning.
Note: This is not a simple "mashup". It solves a real analytical problem: comparing structurally different oscillators on equal visual footing while preserving their unique divergence behaviors—something not available in any single existing indicator.
Additional Compliance Notes :
No emoji or non-ASCII characters in title
English-first description (you may add Spanish after if desired)
Clear justification for combining two indicators
Explanation of calculations (Dorsey vs. Ehlers)
Highlight of original contributions (normalization, dual divergence logic, UI controls)
No promotion, links, or contact info
Clean chart recommended: publish with only this script active, no other indicators or drawings
RSI Value Table – match builtin🧭 Overview
“RSI Value Table – match builtin” displays the exact RSI value (identical to TradingView’s built-in RSI) for any selected timeframe — directly on your chart.
It’s designed for professional traders who need quick RSI confirmation without switching panels or opening multiple indicators.
⚙️ Core Logic
Reads RSI from any timeframe using request.security() with gaps_off and lookahead_off — ensuring a perfect match with the native RSI.
Optional EMA smoothing (non-standard) for visual stability.
Color-coded cell:
🟩 Green → RSI > 50 (bullish momentum)
🟥 Red → RSI < 50 (bearish momentum)
🟨 Yellow → Neutral zone around 50
Adjustable table position: top/bottom, left/right corners.
⚡ Alerts
Built-in alert conditions trigger automatically:
RSI > 50 → bullish momentum confirmation.
RSI < 50 → bearish momentum confirmation.
📈 How to Use
Select your preferred RSI timeframe (e.g., Daily, Weekly, 4H).
Watch the color-coded cell:
Green → trade long bias only.
Red → short bias only.
Ideal as a confirmation module for multi-timeframe systems or smart signal engines.
Spread Trading Z-ScoreIndicator: Z-Score Spread Indicator
Description
The "Z-Score Spread Indicator" is a powerful tool for traders employing mean-reversion strategies on the spread between two financial assets (e.g., futures contracts like MNQ and MES). This indicator calculates and plots the Z-score of the price spread, indicating how far the current spread deviates from its historical mean. It features customizable entry and exit thresholds with adjustable offsets, along with an estimated p-value displayed in a table to assess statistical significance.
Key Features
Asset Selection: Allows users to select two asset symbols (e.g., CME_MINI:MNQ1! and CME_MINI:MES1!) via customizable inputs.
Z-Score Calculation: Computes the Z-score based on the spread’s simple moving average and standard deviation over a user-defined lookback period.
Customizable Thresholds with Offset: Offers adjustable base entry and exit thresholds, with an optional offset to fine-tune trading levels, plotted as horizontal lines.
P-Value Estimation: Provides an approximate p-value to evaluate the statistical significance of the Z-score, displayed in a table anchored to the top-left corner.
Visual Representation: Plots the Z-score with a zero line and threshold lines for intuitive interpretation.
Adjustable Parameters
Asset A Symbol: Symbol for Asset A (default: CME_MINI:MNQ1!).
Asset B Symbol: Symbol for Asset B (default: CME_MINI:MES1!).
Z-Score Lookback: Lookback period for Z-score calculation (default: 40, minimum 2).
Base Entry Threshold: Threshold for entry signals (default: 1.8, adjustable with a step of 0.1).
Base Exit Threshold: Threshold for exit signals (default: 0.5, adjustable with a step of 0.1).
Threshold Offset (+/-): Offset to adjust entry and exit thresholds symmetrically (default: 0.0, range -5.0 to 5.0, step 0.1).
Usage
Add the indicator to your chart via the "Indicators" tab.
Customize the parameters based on your preferred assets and trading strategy (lookback period, thresholds, offset).
Observe the Z-score plot and threshold lines (red for short entry, green for long entry, orange dotted for exits) to identify potential trade setups.
Check the p-value table in the top-left corner to assess the statistical significance of the current Z-score.
Use this data to inform mean-reversion trading decisions, ideally in conjunction with other indicators.
Notes
A Z-score above the entry threshold (positive) or below the negative entry threshold suggests a potential short or long entry, respectively. Exits are signaled when the Z-score crosses the exit thresholds.
The p-value is an approximation based on the normal distribution; a value below 0.05 typically indicates statistical significance, but further validation is recommended.
The indicator uses a simple spread (Asset A - Asset B) without volatility adjustments; consider pairing it with a lots calculator for hedging.
Limitations
The p-value is an approximation and may not reflect advanced statistical tests (e.g., ADF) due to Pine Script constraints.
No automatic trading signals are generated; it provides data for manual analysis.
Author
Developed by grogusama, October 15, 2025, 07:29 PM CEST.
Mean Reversion Oscillator [Alpha Extract]An advanced composite oscillator system specifically designed to identify extreme market conditions and high-probability mean reversion opportunities, combining five proven oscillators into a single, powerful analytical framework.
By integrating multiple momentum and volume-based indicators with sophisticated extreme level detection, this oscillator provides precise entry signals for contrarian trading strategies while filtering out false reversals through momentum confirmation.
🔶 Multi-Oscillator Composite Framework
Utilizes a comprehensive approach that combines Bollinger %B, RSI, Stochastic, Money Flow Index, and Williams %R into a unified composite score. This multi-dimensional analysis ensures robust signal generation by capturing different aspects of market extremes and momentum shifts.
// Weighted composite (equal weights)
normalized_bb = bb_percent
normalized_rsi = rsi
normalized_stoch = stoch_d_val
normalized_mfi = mfi
normalized_williams = williams_r
composite_raw = (normalized_bb + normalized_rsi + normalized_stoch + normalized_mfi + normalized_williams) / 5
composite = ta.sma(composite_raw, composite_smooth)
🔶 Advanced Extreme Level Detection
Features a sophisticated dual-threshold system that distinguishes between moderate and extreme market conditions. This hierarchical approach allows traders to identify varying degrees of mean reversion potential, from moderate oversold/overbought conditions to extreme levels that demand immediate attention.
🔶 Momentum Confirmation System
Incorporates a specialized momentum histogram that confirms mean reversion signals by analyzing the rate of change in the composite oscillator. This prevents premature entries during strong trending conditions while highlighting genuine reversal opportunities.
// Oscillator momentum (rate of change)
osc_momentum = ta.mom(composite, 5)
histogram = osc_momentum
// Momentum confirmation
momentum_bullish = histogram > histogram
momentum_bearish = histogram < histogram
// Confirmed signals
confirmed_bullish = bullish_entry and momentum_bullish
confirmed_bearish = bearish_entry and momentum_bearish
🔶 Dynamic Visual Intelligence
The oscillator line adapts its color intensity based on proximity to extreme levels, providing instant visual feedback about market conditions. Background shading creates clear zones that highlight when markets enter moderate or extreme territories.
🔶 Intelligent Signal Generation
Generates precise entry signals only when the composite oscillator crosses extreme thresholds with momentum confirmation. This dual-confirmation approach significantly reduces false signals while maintaining sensitivity to genuine mean reversion opportunities.
How It Works
🔶 Composite Score Calculation
The indicator simultaneously tracks five different oscillators, each normalized to a 0-100 scale, then combines them into a smoothed composite score. This approach eliminates the noise inherent in single-oscillator analysis while capturing the consensus view of multiple momentum indicators.
// Mean reversion entry signals
bullish_entry = ta.crossover(composite, 100 - extreme_level) and composite < (100 - extreme_level)
bearish_entry = ta.crossunder(composite, extreme_level) and composite > extreme_level
// Bollinger %B calculation
bb_basis = ta.sma(src, bb_length)
bb_dev = bb_mult * ta.stdev(src, bb_length)
bb_percent = (src - bb_lower) / (bb_upper - bb_lower) * 100
🔶 Extreme Zone Identification
The system automatically identifies when markets reach statistically significant extreme levels, both moderate (65/35) and extreme (80/20). These zones represent areas where mean reversion has the highest probability of success based on historical market behavior.
🔶 Momentum Histogram Analysis
A specialized momentum histogram tracks the velocity of oscillator changes, helping traders distinguish between healthy corrections and potential trend reversals. The histogram's color-coded display makes momentum shifts immediately apparent.
🔶 Divergence Detection Framework
Built-in divergence analysis identifies situations where price and oscillator movements diverge, often signaling impending reversals. Diamond-shaped markers highlight these critical divergence patterns for enhanced pattern recognition.
🔶 Real-Time Information Dashboard
An integrated information table provides instant access to current oscillator readings, market status, and individual component values. This dashboard eliminates the need to manually check multiple indicators while trading.
🔶 Individual Component Display
Optional display of individual oscillator components allows traders to understand which specific indicators are driving the composite signal. This transparency enables more informed decision-making and deeper market analysis.
🔶 Adaptive Background Coloring
Intelligent background shading automatically adjusts based on market conditions, creating visual zones that correspond to different levels of mean reversion potential. The subtle color gradations make pattern recognition effortless.
1D
3D
🔶 Comprehensive Alert System
Multi-tier alert system covers confirmed entry signals, divergence patterns, and extreme level breaches. Each alert type provides specific context about the detected condition, enabling traders to respond appropriately to different signal strengths.
🔶 Customizable Threshold Management
Fully adjustable extreme and moderate levels allow traders to fine-tune the indicator's sensitivity to match different market volatilities and trading timeframes. This flexibility ensures optimal performance across various market conditions.
🔶 Why Choose AE - Mean Reversion Oscillator?
This indicator provides the most comprehensive approach to mean reversion trading by combining multiple proven oscillators with advanced confirmation mechanisms. By offering clear visual hierarchies for different extreme levels and requiring momentum confirmation for signals, it empowers traders to identify high-probability contrarian opportunities while avoiding false reversals. The sophisticated composite methodology ensures that signals are both statistically significant and practically actionable, making it an essential tool for traders focused on mean reversion strategies across all market conditions.
Historical Matrix Analyzer [PhenLabs]📊Historical Matrix Analyzer
Version: PineScriptv6
📌Description
The Historical Matrix Analyzer is an advanced probabilistic trading tool that transforms technical analysis into a data-driven decision support system. By creating a comprehensive 56-cell matrix that tracks every combination of RSI states and multi-indicator conditions, this indicator reveals which market patterns have historically led to profitable outcomes and which have not.
At its core, the indicator continuously monitors seven distinct RSI states (ranging from Extreme Oversold to Extreme Overbought) and eight unique indicator combinations (MACD direction, volume levels, and price momentum). For each of these 56 possible market states, the system calculates average forward returns, win rates, and occurrence counts based on your configurable lookback period. The result is a color-coded probability matrix that shows you exactly where you stand in the historical performance landscape.
The standout feature is the Current State Panel, which provides instant clarity on your active market conditions. This panel displays signal strength classifications (from Strong Bullish to Strong Bearish), the average return percentage for similar past occurrences, an estimated win rate using Bayesian smoothing to prevent small-sample distortions, and a confidence level indicator that warns you when insufficient data exists for reliable conclusions.
🚀Points of Innovation
Multi-dimensional state classification combining 7 RSI levels with 8 indicator combinations for 56 unique trackable market conditions
Bayesian win rate estimation with adjustable smoothing strength to provide stable probability estimates even with limited historical samples
Real-time active cell highlighting with “NOW” marker that visually connects current market conditions to their historical performance data
Configurable color intensity sensitivity allowing traders to adjust heat-map responsiveness from conservative to aggressive visual feedback
Dual-panel display system separating the comprehensive statistics matrix from an easy-to-read current state summary panel
Intelligent confidence scoring that automatically warns traders when occurrence counts fall below reliable thresholds
🔧Core Components
RSI State Classification: Segments RSI readings into 7 distinct zones (Extreme Oversold <20, Oversold 20-30, Weak 30-40, Neutral 40-60, Strong 60-70, Overbought 70-80, Extreme Overbought >80) to capture momentum extremes and transitions
Multi-Indicator Condition Tracking: Simultaneously monitors MACD crossover status (bullish/bearish), volume relative to moving average (high/low), and price direction (rising/falling) creating 8 binary-encoded combinations
Historical Data Storage Arrays: Maintains rolling lookback windows storing RSI states, indicator states, prices, and bar indices for precise forward-return calculations
Forward Performance Calculator: Measures price changes over configurable forward bar periods (1-20 bars) from each historical state, accumulating total returns and win counts per matrix cell
Bayesian Smoothing Engine: Applies statistical prior assumptions (default 50% win rate) weighted by user-defined strength parameter to stabilize estimated win rates when sample sizes are small
Dynamic Color Mapping System: Converts average returns into color-coded heat map with intensity adjusted by sensitivity parameter and transparency modified by confidence levels
🔥Key Features
56-Cell Probability Matrix: Comprehensive grid displaying every possible combination of RSI state and indicator condition, with each cell showing average return percentage, estimated win rate, and occurrence count for complete statistical visibility
Current State Info Panel: Dedicated display showing your exact position in the matrix with signal strength emoji indicators, numerical statistics, and color-coded confidence warnings for immediate situational awareness
Customizable Lookback Period: Adjustable historical window from 50 to 500 bars allowing traders to focus on recent market behavior or capture longer-term pattern stability across different market cycles
Configurable Forward Performance Window: Select target holding periods from 1 to 20 bars ahead to align probability calculations with your trading timeframe, whether day trading or swing trading
Visual Heat Mapping: Color-coded cells transition from red (bearish historical performance) through gray (neutral) to green (bullish performance) with intensity reflecting statistical significance and occurrence frequency
Intelligent Data Filtering: Minimum occurrence threshold (1-10) removes unreliable patterns with insufficient historical samples, displaying gray warning colors for low-confidence cells
Flexible Layout Options: Independent positioning of statistics matrix and info panel to any screen corner, accommodating different chart layouts and personal preferences
Tooltip Details: Hover over any matrix cell to see full RSI label, complete indicator status description, precise average return, estimated win rate, and total occurrence count
🎨Visualization
Statistics Matrix Table: A 9-column by 8-row grid with RSI states labeling vertical axis and indicator combinations on horizontal axis, using compact abbreviations (XOverS, OverB, MACD↑, Vol↓, P↑) for space efficiency
Active Cell Indicator: The current market state cell displays “⦿ NOW ⦿” in yellow text with enhanced color saturation to immediately draw attention to relevant historical performance
Signal Strength Visualization: Info panel uses emoji indicators (🔥 Strong Bullish, ✅ Bullish, ↗️ Weak Bullish, ➖ Neutral, ↘️ Weak Bearish, ⛔ Bearish, ❄️ Strong Bearish, ⚠️ Insufficient Data) for rapid interpretation
Histogram Plot: Below the price chart, a green/red histogram displays the current cell’s average return percentage, providing a time-series view of how historical performance changes as market conditions evolve
Color Intensity Scaling: Cell background transparency and saturation dynamically adjust based on both the magnitude of average returns and the occurrence count, ensuring visual emphasis on reliable patterns
Confidence Level Display: Info panel bottom row shows “High Confidence” (green), “Medium Confidence” (orange), or “Low Confidence” (red) based on occurrence counts relative to minimum threshold multipliers
📖Usage Guidelines
RSI Period
Default: 14
Range: 1 to unlimited
Description: Controls the lookback period for RSI momentum calculation. Standard 14-period provides widely-recognized overbought/oversold levels. Decrease for faster, more sensitive RSI reactions suitable for scalping. Increase (21, 28) for smoother, longer-term momentum assessment in swing trading. Changes affect how quickly the indicator moves between the 7 RSI state classifications.
MACD Fast Length
Default: 12
Range: 1 to unlimited
Description: Sets the faster exponential moving average for MACD calculation. Standard 12-period setting works well for daily charts and captures short-term momentum shifts. Decreasing creates more responsive MACD crossovers but increases false signals. Increasing smooths out noise but delays signal generation, affecting the bullish/bearish indicator state classification.
MACD Slow Length
Default: 26
Range: 1 to unlimited
Description: Defines the slower exponential moving average for MACD calculation. Traditional 26-period setting balances trend identification with responsiveness. Must be greater than Fast Length. Wider spread between fast and slow increases MACD sensitivity to trend changes, impacting the frequency of indicator state transitions in the matrix.
MACD Signal Length
Default: 9
Range: 1 to unlimited
Description: Smoothing period for the MACD signal line that triggers bullish/bearish state changes. Standard 9-period provides reliable crossover signals. Shorter values create more frequent state changes and earlier signals but with more whipsaws. Longer values produce more confirmed, stable signals but with increased lag in detecting momentum shifts.
Volume MA Period
Default: 20
Range: 1 to unlimited
Description: Lookback period for volume moving average used to classify volume as “high” or “low” in indicator state combinations. 20-period default captures typical monthly trading patterns. Shorter periods (10-15) make volume classification more reactive to recent spikes. Longer periods (30-50) require more sustained volume changes to trigger state classification shifts.
Statistics Lookback Period
Default: 200
Range: 50 to 500
Description: Number of historical bars used to calculate matrix statistics. 200 bars provides substantial data for reliable patterns while remaining responsive to regime changes. Lower values (50-100) emphasize recent market behavior and adapt quickly but may produce volatile statistics. Higher values (300-500) capture long-term patterns with stable statistics but slower adaptation to changing market dynamics.
Forward Performance Bars
Default: 5
Range: 1 to 20
Description: Number of bars ahead used to calculate forward returns from each historical state occurrence. 5-bar default suits intraday to short-term swing trading (5 hours on hourly charts, 1 week on daily charts). Lower values (1-3) target short-term momentum trades. Higher values (10-20) align with position trading and longer-term pattern exploitation.
Color Intensity Sensitivity
Default: 2.0
Range: 0.5 to 5.0, step 0.5
Description: Amplifies or dampens the color intensity response to average return magnitudes in the matrix heat map. 2.0 default provides balanced visual emphasis. Lower values (0.5-1.0) create subtle coloring requiring larger returns for full saturation, useful for volatile instruments. Higher values (3.0-5.0) produce vivid colors from smaller returns, highlighting subtle edges in range-bound markets.
Minimum Occurrences for Coloring
Default: 3
Range: 1 to 10
Description: Required minimum sample size before applying color-coded performance to matrix cells. Cells with fewer occurrences display gray “insufficient data” warning. 3-occurrence default filters out rare patterns. Lower threshold (1-2) shows more data but includes unreliable single-event statistics. Higher thresholds (5-10) ensure only well-established patterns receive visual emphasis.
Table Position
Default: top_right
Options: top_left, top_right, bottom_left, bottom_right
Description: Screen location for the 56-cell statistics matrix table. Position to avoid overlapping critical price action or other indicators on your chart. Consider chart orientation and candlestick density when selecting optimal placement.
Show Current State Panel
Default: true
Options: true, false
Description: Toggle visibility of the dedicated current state information panel. When enabled, displays signal strength, RSI value, indicator status, average return, estimated win rate, and confidence level for active market conditions. Disable to declutter charts when only the matrix table is needed.
Info Panel Position
Default: bottom_left
Options: top_left, top_right, bottom_left, bottom_right
Description: Screen location for the current state information panel (when enabled). Position independently from statistics matrix to optimize chart real estate. Typically placed opposite the matrix table for balanced visual layout.
Win Rate Smoothing Strength
Default: 5
Range: 1 to 20
Description: Controls Bayesian prior weighting for estimated win rate calculations. Acts as virtual sample size assuming 50% win rate baseline. Default 5 provides moderate smoothing preventing extreme win rate estimates from small samples. Lower values (1-3) reduce smoothing effect, allowing win rates to reflect raw data more directly. Higher values (10-20) increase conservatism, pulling win rate estimates toward 50% until substantial evidence accumulates.
✅Best Use Cases
Pattern-based discretionary trading where you want historical confirmation before entering setups that “look good” based on current technical alignment
Swing trading with holding periods matching your forward performance bar setting, using high-confidence bullish cells as entry filters
Risk assessment and position sizing, allocating larger size to trades originating from cells with strong positive average returns and high estimated win rates
Market regime identification by observing which RSI states and indicator combinations are currently producing the most reliable historical patterns
Backtesting validation by comparing your manual strategy signals against the historical performance of the corresponding matrix cells
Educational tool for developing intuition about which technical condition combinations have actually worked versus those that feel right but lack historical evidence
⚠️Limitations
Historical patterns do not guarantee future performance, especially during unprecedented market events or regime changes not represented in the lookback period
Small sample sizes (low occurrence counts) produce unreliable statistics despite Bayesian smoothing, requiring caution when acting on low-confidence cells
Matrix statistics lag behind rapidly changing market conditions, as the lookback period must accumulate new state occurrences before updating performance data
Forward return calculations use fixed bar periods that may not align with actual trade exit timing, support/resistance levels, or volatility-adjusted profit targets
💡What Makes This Unique
Multi-Dimensional State Space: Unlike single-indicator tools, simultaneously tracks 56 distinct market condition combinations providing granular pattern resolution unavailable in traditional technical analysis
Bayesian Statistical Rigor: Implements proper probabilistic smoothing to prevent overconfidence from limited data, a critical feature missing from most pattern recognition tools
Real-Time Contextual Feedback: The “NOW” marker and dedicated info panel instantly connect current market conditions to their historical performance profile, eliminating guesswork
Transparent Occurrence Counts: Displays sample sizes directly in each cell, allowing traders to judge statistical reliability themselves rather than hiding data quality issues
Fully Customizable Analysis Window: Complete control over lookback depth and forward return horizons lets traders align the tool precisely with their trading timeframe and strategy requirements
🔬How It Works
1. State Classification and Encoding
Each bar’s RSI value is evaluated and assigned to one of 7 discrete states based on threshold levels (0: <20, 1: 20-30, 2: 30-40, 3: 40-60, 4: 60-70, 5: 70-80, 6: >80)
Simultaneously, three binary conditions are evaluated: MACD line position relative to signal line, current volume relative to its moving average, and current close relative to previous close
These three binary conditions are combined into a single indicator state integer (0-7) using binary encoding, creating 8 possible indicator combinations
The RSI state and indicator state are stored together, defining one of 56 possible market condition cells in the matrix
2. Historical Data Accumulation
As each bar completes, the current state classification, closing price, and bar index are stored in rolling arrays maintained at the size specified by the lookback period
When the arrays reach capacity, the oldest data point is removed and the newest added, creating a sliding historical window
This continuous process builds a comprehensive database of past market conditions and their subsequent price movements
3. Forward Return Calculation and Statistics Update
On each bar, the indicator looks back through the stored historical data to find bars where sufficient forward bars exist to measure outcomes
For each historical occurrence, the price change from that bar to the bar N periods ahead (where N is the forward performance bars setting) is calculated as a percentage return
This percentage return is added to the cumulative return total for the specific matrix cell corresponding to that historical bar’s state classification
Occurrence counts are incremented, and wins are tallied for positive returns, building comprehensive statistics for each of the 56 cells
The Bayesian smoothing formula combines these raw statistics with prior assumptions (neutral 50% win rate) weighted by the smoothing strength parameter to produce estimated win rates that remain stable even with small samples
💡Note:
The Historical Matrix Analyzer is designed as a decision support tool, not a standalone trading system. Best results come from using it to validate discretionary trade ideas or filter systematic strategy signals. Always combine matrix insights with proper risk management, position sizing rules, and awareness of broader market context. The estimated win rate feature uses Bayesian statistics specifically to prevent false confidence from limited data, but no amount of smoothing can create reliable predictions from fundamentally insufficient sample sizes. Focus on high-confidence cells (green-colored confidence indicators) with occurrence counts well above your minimum threshold for the most actionable insights.
Fair Value Lead-Lag Model [BackQuant]Fair Value Lead-Lag Model
A cross-asset model that estimates where price "should" be relative to a chosen reference series, then tracks the deviation as a normalized oscillator. It helps you answer two questions: 1) is the asset rich or cheap vs its driver, and 2) is the driver leading or lagging price over the next N bars.
Concept in one paragraph
Many assets co-move with a macro or sector driver. Think BTC vs DXY, gold vs real yields, a stock vs its sector ETF. This tool builds a rolling fair value of the charted asset from a reference series and shows how far price is above or below that fair value in standard deviation units. You can shift the reference forward or backward to test who leads whom, then use the deviation and its bands to structure mean-reversion or trend-following ideas.
What the model does
Reference mapping : Pulls a reference symbol at a chosen timeframe, with an optional lead or lag in bars to test causality.
Fair value engine : Converts the reference into a synthetic fair value of the chart using one of four methods:
Ratio : price/ref with a rolling average ratio. Good when the relationship is proportional.
Spread : price minus ref with a rolling average spread. Good when the relationship is additive.
Z-Score : normalizes both series, aligns on standardized units, then re-projects to price space. Good when scale drifts.
Beta-Adjusted : rolling regression style. Uses covariance and variance to compute beta, then builds a fair value = mean(price) + beta * (ref − mean(ref)).
Deviation and bands : Computes a z-scored deviation of price vs fair value and plots sigma bands (±1, ±2, ±3) around the fair value line on the chart.
Correlation context : Shows rolling correlation so you can judge if deviations are meaningful or just noise when co-movement is weak.
Visuals :
Fair value line on price chart with sigma envelopes.
Deviation as a column oscillator and optional line.
Threshold shading beyond user-set upper and lower levels.
Summary table with reference, deviation, status, correlation, and method.
Why this is useful
Mean reversion framework : When correlation is healthy and deviation stretches beyond your sigma threshold, probability favors reversion toward fair value. This is classic pairs logic adapted to a driver and a target.
Trend confirmation : If price rides the fair value line and deviation stays modest while correlation is positive, it supports trend persistence. Pullbacks to negative deviation in an uptrend can be buyable.
Lead-lag discovery : Shift the reference forward by +N bars. If correlation improves, the reference tends to lead. Shift backward for the reverse. Use the best setting for planning early entries or hedges.
Regime detection : Large persistent deviations with falling correlation hint at regime change. The relationship you relied on may be breaking down, so reduce confidence or switch methods.
How to use it step by step
Pick a sensible reference : Choose a macro, index, currency, or sector driver that logically explains the asset’s moves. Example: gold with DXY, a semiconductor stock with SOXX.
Test lead-lag : Nudge Lead/Lag Periods to small positive values like +1 to +5 to see if the reference leads. If correlation improves, keep that offset. If correlation worsens, try a small negative value or zero.
Select a method :
Start with Beta-Adjusted when the relationship is approximately linear with drift.
Use Ratio if the assets usually move in proportional terms.
Use Spread when they trade around a level difference.
Use Z-Score when scales wander or volatility regimes shift.
Tune windows :
Rolling Window controls how quickly fair value adapts. Shorter equals faster but noisier.
Normalization Period controls how deviations are standardized. Longer equals stabler sigma sizing.
Correlation Length controls how co-movement is measured. Keep it near the fair value window.
Trade the edges :
Mean reversion idea : Wait for deviation beyond your Upper or Lower Threshold with positive correlation. Fade back toward fair value. Exit at the fair value line or the next inner sigma band.
Trend idea : In an uptrend, buy pullbacks when deviation dips negative but correlation remains healthy. In a downtrend, sell bounces when deviation spikes positive.
Read the table : Deviation shows how many sigmas you are from fair value. Status tells you overvalued or undervalued. Correlation color hints confidence. Method tells you the projection style used.
Reading the display
Fair value line on price chart: the model’s estimate of where price should trade given the reference, updated each bar.
Sigma bands around fair value: a quick sense of residual volatility. Reversions often target inner bands first.
Deviation oscillator : above zero means rich vs fair value, below zero means cheap. Color bins intensify with distance.
Correlation line (optional): scale is folded to match thresholds. Higher values increase trust in deviations.
Parameter tips
Start with Rolling Window 20 to 30, Normalization Period 100, Correlation Length 50.
Upper and Lower Threshold at ±2.0 are classic. Tighten to ±1.5 for more signals or widen to ±2.5 to focus on outliers.
When correlation drifts below about 0.3, treat deviations with caution. Consider switching method or reference.
If the fair value line whipsaws, increase Rolling Window or move to Beta-Adjusted which tends to be smoother.
Playbook examples
Pairs-style reversion : Asset is +2.3 sigma rich vs reference, correlation 0.65, trend flat. Short the deviation back toward fair value. Cover near the fair value line or +1 sigma.
Pro-trend pullback : Uptrend with correlation 0.7. Deviation dips to −1.2 sigma while price sits near the −1 sigma band. Buy the dip, target the fair value line, trail if the line is rising.
Lead-lag timing : Reference leads by +3 bars with improved correlation. Use reference swings as early cues to anticipate deviation turns on the target.
Caveats
The model assumes a stable relationship over the chosen windows. Structural breaks, policy shocks, and index rebalances can invalidate recent history.
Correlation is descriptive, not causal. A strong correlation does not guarantee future convergence.
Do not force trades when the reference has low liquidity or mismatched hours. Use a reference timeframe that captures real overlap.
Bottom line
This tool turns a loose cross-asset intuition into a quantified, visual fair value map. It gives you a consistent way to find rich or cheap conditions, time mean-reversion toward a statistically grounded target, and confirm or fade trends when the driver agrees.