Golden Ladder – Louay Joha (Wave & Gann Hi/Lo + ATR R-Levels)Overview
Golden Ladder is a momentum-and-structure tool that detects three-bar ladder waves and filters them with a Gann Hi/Lo regime guide (SMA-based). When a valid wave aligns with the current Hi/Lo bias and passes optional market filters (ADX, RSI, and proximity to recent extremes), the script prints BUY/SELL n labels (n = wave index) and draws a complete Entry / SL / TP1–TP4 ladder using ATR-based risk units (R) or fixed caps—configured for clarity and consistency. The script also keeps the chart clean: the last trade remains fully drawn while historical groups are trimmed to compact “ENTRY-only” stubs.
Why these components together (originality)
Three-bar ladder captures short-term momentum structure (progressively higher highs/lows for buys; the reverse for sells).
Gann Hi/Lo (SMA of highs/lows with a directional state) acts as a regime filter, reducing counter-trend ladders.
ATR-based R ladder turns signals into an actionable plan: a volatility-aware SL and TP1–TP4 that scale across instruments/timeframes.
Smart Entry filters (ADX strength, RSI extremes, and distance from recent top/bottom using ATR buffers) seek to avoid low-quality, stretched entries.
Slim history keeps only a short ENTRY stub for prior groups, so the signal you just got is always the most readable.
This is not a mere mashup; each layer constrains the others to produce fewer, clearer setups.
How it works (high-level logic)
Regime (Gann Hi/Lo):
Compute SMA(high, HPeriod) and SMA(low, LPeriod).
Direction state HLv flips when the close crosses above/below its track; one unified Hi/Lo guide is plotted.
Ladder signal (structure + confirmation):
BUY ladder: three consecutive green bars with rising highs and rising lows and HLv == +1.
SELL ladder: mirror conditions with HLv == -1.
Signals evaluate intrabar and are controlled by Smart Entry filters (ADX/RSI/extreme checks).
Risk ladder (R-based or capped):
Default: risk = ATR(atr_len) × SL_multiple and TPs in R.
Optional fixed caps by timeframe (e.g., M1/M5) using USD per point.
Longs: SL = entry – risk; TPi = entry + (Ri × risk).
Shorts: SL = entry + risk; TPi = entry – (Ri × risk).
All levels auto-reflow to the right as bars print.
Chart hygiene:
The latest trade shows ENTRY/SL/TP1–TP4 fully.
Older trades are automatically trimmed (only a short ENTRY line remains, with optional label).
Alerts:
BUY – Smart Entry (Tick) & SELL – Smart Entry (Tick) fire on live-qualified signals.
You can connect alerts to your automation, respecting your broker’s risk controls.
Inputs (English summary of UI)
Label settings: label size; ATR-based vs fixed-tick offsets; leader line width/transparency; horizontal label shift.
Gann Hi/Lo: HIGH Period (HPeriod), LOW Period (LPeriod).
Market filters: ADX (length, smoothing, minimum), RSI (length + caps), recent extremes (lookback + ATR buffer).
Entry/SL/TP Levels: TP1–TP4 (R), label right-shift, show last-trade prices on labels.
Fixed SL Caps: per-timeframe caps (M1/M5) via USD per point.
How to use
Apply on your instrument/timeframe; tune H/L periods and filters to your market (e.g., XAUUSD on M1/M5).
Favor signals aligned with the Hi/Lo regime; tighten filters (higher ADX, stricter RSI caps) to reduce noise.
Choose ATR-Risk or fixed caps depending on your preferences.
The drawing policy ensures the most recent trade remains front-and-center.
Notes & limitations
Signals can evaluate intrabar; MA-based context is inherently lagging.
ATR-based ladders adapt to volatility; extreme spikes can widen risk.
This is a technical analysis tool, not financial advice.
Volatilidade
True Range(TR) + Average True Range (ATR) COMBINEDThis indicator combines True Range (TR) and Average True Range (ATR) into a single panel for a clearer understanding of price volatility.
True Range (TR) measures the absolute price movement between highs, lows, and previous closes — showing raw, unsmoothed volatility.
Average True Range (ATR) is a moving average of the True Range, providing a smoother, more stable volatility signal.
📊 Usage Tips:
High TR/ATR values indicate strong price movement or volatility expansion.
Low values suggest compression or a potential volatility breakout zone.
Can be used for stop-loss placement, volatility filters, or trend strength confirmation.
⚙️ Features:
Multiple smoothing methods: RMA, SMA, EMA, WMA.
Adjustable ATR length.
Separate colored plots for TR (yellow) and ATR (red).
Works across all timeframes and instruments.
True Range(TR) & ATR Combined – Volatility Strength IndicatorThis indicator combines True Range (TR) and Average True Range (ATR) into a single panel for a clearer understanding of price volatility.
True Range (TR) measures the absolute price movement between highs, lows, and previous closes — showing raw, unsmoothed volatility.
Average True Range (ATR) is a moving average of the True Range, providing a smoother, more stable volatility signal.
📊 Usage Tips:
High TR/ATR values indicate strong price movement or volatility expansion.
Low values suggest compression or a potential volatility breakout zone.
Can be used for stop-loss placement, volatility filters, or trend strength confirmation.
⚙️ Features:
Multiple smoothing methods: RMA, SMA, EMA, WMA.
Adjustable ATR length.
Separate colored plots for TR (yellow) and ATR (red).
Works across all timeframes and instruments.
Candlestick StrengthThis indicator quantifies the “energy” of each candlestick by combining its height (high–low span), trading volume, and internal structure (body vs. wick proportions). It provides a numeric measure of how strongly each candle contributes to market momentum, allowing traders to distinguish meaningful price action from indecision or noise.
Concept
Every candlestick represents a short-term contest between buyers and sellers. Large candles with significant volume indicate strong market participation, while small or low-volume candles suggest hesitation or absorption. Candlestick Strength captures this by calculating a normalized measure of each candle’s energy relative to recent activity, making it comparable across different market conditions and timeframes.
The indicator also analyzes the candle’s internal structure:
The body reflects net directional movement.
The wicks represent back-and-forth price traversal within the candle. Because wick movement does not fully contribute to directional momentum, it is weighted at half the body’s contribution. This ensures the indicator emphasizes sustained directional pressure while still acknowledging rejection or absorption.
Interpretation
High values indicate candles with energy above recent averages — suggesting expanding momentum and strong directional intent.
Average values reflect typical candle activity, representing neutral or steady market behavior.
Low values suggest weak candles — either the market is pausing, consolidating, or momentum is fading.
The outputs are displayed as a symmetric histogram: bullish candle energy is shown in green above zero, bearish energy in red below zero, with ±1 reference lines marking the normalized average energy level.
Usage
Combine with trend analysis, swing highs/lows, or volume-weighted averages to validate breakouts or trend continuation.
Monitor for divergence between price movement and candle energy to identify exhaustion, absorption, or potential reversals.
Filter out false momentum signals caused by narrow-range or low-volume candles.
Adaptable across timeframes: normalized energy allows comparison between small and large timeframe candles.
Vandan V2Vandan V2 is an automated trend-following strategy for NASDAQ E-mini Futures (NQ1!).
It uses multi-timeframe momentum and volatility filters to identify high-probability entries.
Includes dynamic risk management and trailing logic optimized for intraday trading.
ATR x Trend x Volume SignalsATR x Trend x Volume Signals is a multi-factor indicator that combines volatility, trend, and volume analysis into one adaptive framework. It is designed for traders who use technical confluence and prefer clear, rule-based setups.
🎯 Purpose
This tool identifies high-probability market moments when volatility structure (ATR), momentum direction (CCI-based trend logic), and volume expansion all align. It helps filter out noise and focus on clean, actionable trade conditions.
⚙️ Structure
The indicator consists of three main analytical layers:
1️⃣ ATR Trailing Stop – calculates two adaptive ATR lines (fast and slow) that define volatility context, trend bias, and potential reversal points.
2️⃣ Trend Indicator (CCI + ATR) – uses a CCI-based logic combined with ATR smoothing to determine the dominant trend direction and reduce false flips.
3️⃣ Volume Analysis – evaluates volume deviations from their historical average using standard deviation. Bars are highlighted as medium, high, or extra-high volume depending on intensity.
💡 Signal Logic
A Buy Signal (green) appears when all of the following are true:
• The ATR (slow) line is green.
• The Trend Indicator is blue.
• A bullish candle closes above both the ATR (slow) and the Trend Indicator.
• The candle shows medium, high, or extra-high volume.
A Sell Signal (red) appears when:
• The ATR (slow) line is red.
• The Trend Indicator is red.
• A bearish candle closes below both the ATR (slow) and the Trend Indicator.
• The candle shows medium, high, or extra-high volume.
Only one signal can appear per ATR trend phase. A new signal is generated only after the ATR direction changes.
❌ Exit Logic
Exit markers are shown when price crosses the slow ATR line. This behavior simulates a trailing stop exit. The exit is triggered one bar after entry to prevent same-bar exits.
⏰ Session Filter
Signals are generated only between the user-defined session start and end times (default: 14:00–18:00 chart time). This allows the trader to limit signal generation to active trading hours.
💬 Practical Use
It is recommended to trade with a fixed risk-reward ratio such as 1 : 1.5. Stop-loss placement should be beyond the slow ATR line and adjusted gradually as the trade develops.
For better confirmation, the Trend Indicator timeframe should be higher than the chart timeframe (for example: trading on 1 min → set Trend Indicator timeframe to 15 min; trading on 5 min → set to 1 hour).
🧠 Main Features
• Dual ATR volatility structure (fast and slow)
• CCI-based trend direction filtering
• Volume deviation heatmap logic
• Time-restricted signal generation
• Dynamic trailing-stop exit system
• Non-repainting logic
• Fully optimized for Pine Script v6
📊 Usage Tip
Best results are achieved when combining this indicator with additional technical context such as support-resistance, higher-timeframe confirmation, or market structure analysis.
📈 Credits
Inspired by:
• ATR Trailing Stop by Ceyhun
• Trend Magic by Kivanc Ozbilgic
• Heatmap Volume by xdecow
APXTradez - TTM Squeeze🔹 APXTradez TTM Squeeze — Summary & How To Use It
What this indicator is
- This is a volatility + momentum engine built for options trading.
It does two jobs at the same time:
- Shows when price is coiling and ready to move (volatility compression using Bollinger Bands vs Keltner Channels).
- Shows which side has control (bullish vs bearish momentum, and whether that pressure is growing or cooling off).
- You use it to time entries on explosive directional moves (breakouts/breakdowns) and to avoid dead chop.
1. Volatility / Compression Logic (the dots)
- This script measures how tight price is by comparing:
- Bollinger Bands (BB): tracks standard deviation (volatility).
- Keltner Channels (KC): tracks ATR (true range / movement).
- When the Bollinger Bands get tighter than the Keltner Channels, price is literally getting bottled up. That’s what traders call “a squeeze.”
- This script splits that squeeze into tiers so you know how aggressive it is:
Orange Dot = High Compression
- BB are inside the tightest Keltner channel (kcMultHigh).
- This is the tightest coil. Energy is loaded.
- Translation: “Something is about to happen here. Pay attention.”
Red Dot = Medium Compression
- BB still inside KC, but looser than orange.
- Pressure building, not maxed.
Yellow Dot = Low Compression
- Still compressed, but wider than red.
- Early stage coil.
Black/Dark Dot = Fired / No Compression
- BB are no longer inside KC.
- The squeeze “released.”
- Translation: “The move is now happening.”
So visually, you’ll often see a sequence like:
yellow → red → orange → black.
That’s the life cycle:
Coil tighter and tighter.
Then BOOM: release.
That release is often where traders take entries.
How to trade the dots
- When you see orange dots stacking, you’re in max coil. You prepare, you don’t FOMO-enter yet.
- When the dots flip to black, that means volatility just expanded (squeeze fired).
- You only want to follow that release in the direction of momentum (see histogram section below). Do not blindly buy every “black.”
So:
- Identify compression (orange/red/yellow).
- Wait for “fired” (black).
- Then check: is momentum actually pushing bullish or bearish, or is it weak?
- That prevents chasing fake breaks.
2. Momentum Histogram (the bars)
- The lower histogram measures momentum using a linear regression on price and a smoothed EMA. In simple terms: it’s checking if price is pushing with force or fading.
It splits momentum into four readable states:
Bullish Side
- Bull Rising (Teal Bright)
- Momentum is above 0 and increasing.
Translation: “Buyers are in control and getting stronger.”
- This is the ideal bullish continuation / call side pressure.
Bull Cooling (Teal Faded)
- Momentum is above 0 but starting to slow down.
Translation: “Still bullish, but momentum is losing steam.”
- You can still stay in the trade, but be aware it’s not accelerating anymore.
Bearish Side
- Bear Pressing (Yellow Bright)
- Momentum is below 0 and getting more negative.
Translation: “Sellers are in control and pressure is increasing.”
- Great for puts / downside continuation.
Bear Cooling (Yellow Faded)
- Momentum is below 0 but starting to weaken.
Translation: “Still bearish, but selling force is easing.”
- Possible bottoming / potential reversal building soon.
- There’s also a zero line plotted. That’s your “neutral axis.”
Bars above zero = bullish regime.
Bars below zero = bearish regime.
Cross through zero = possible momentum flip.
How to read the histogram with the dots
- This is where it gets powerful.
Bullish breakout setup (calls):
- You’ve had compression dots (yellow/red/orange).
- Dots flip to black (squeeze fired).
- Histogram is teal and in “Bull Rising” (bright teal above zero and increasing).
→ That means volatility JUST expanded, and buyers are actually in control. That’s your A+ long/bullish continuation scenario.
Bearish breakdown setup (puts):
- You’ve had compression dots.
- Dots flip to black.
- Histogram is “Bear Pressing” (bright yellow below zero, getting more negative).
→ That means the release is to the downside with real selling pressure, not just a fake wick. That’s your A+ put/downside continuation scenario.
3. Timeframe and Trade Intent
This thing is designed to sit in its own lower panel (overlay = false). You watch it like MACD / Squeeze Pro, but cleaner and more obvious.
Recommended for:
- 4H and Daily: locating swings (2–5 day option plays).
- 5m / 15m / 1h: timing entries on liquid names if you’re doing intraday.
Flow is usually:
- Find the setup on a higher timeframe (Daily / 4H squeeze).
- Drop down one timeframe (1H / 15m) and enter on the first bullish or bearish “fire” in the same direction.
- This keeps you from randomly guessing entries.
4. Cheat Sheet (what to actually do)
Calls (bullish swing):
- You see clustered orange/red/yellow dots → stock is coiling.
- Then you get a black dot → squeeze fired.
- At the same time, the histogram turns bright teal (Bull Rising) and stays above zero.
-That’s your “calls / long continuation” look.
Puts (bearish swing):
- Compression dots first.
- Black dot shows up.
- Histogram turns bright yellow (Bear Pressing) and stays below zero.
That’s your “puts / short continuation” look.
Take profit / De-risk signs:
- Bullish but teal fades to dull teal → momentum is cooling.
- Bearish but yellow fades to dull yellow → selling is cooling.
- You’re still in trend, but gas pedal is coming off. That’s when you scale or trail.
5. Why this version is different from generic TTM Squeeze
-Most public squeeze indicators just tell you “in squeeze / out of squeeze” and show one color.
APXTradez version:
- Breaks compression into three levels (high / medium / low) so you know how “charged” the setup is, not just whether a squeeze exists.
- Shows the release (black dot) separately, so you instantly see “the moment it fired.”
- Splits momentum into four states, not two. You don’t just see “above / below zero,” you see:
- Building bullish
- Cooling bullish
- Building bearish
- Cooling bearish
That means you can tell:
“Is momentum gaining or dying?” instead of just “Is it green or red?”
Which is way more useful for options timing.
BH BTC LS Atopetrader Bitcoin 15M Advanced Trading Strategy
This strategy is designed to trade Bitcoin on the 15-minute timeframe for long and short positions. It uses an advanced system adapted to price action, combined with automated risk management through stop loss and take profit. It is optimized to adapt to the high volatility and speculative nature of BTC, seeking out trend-driven momentum opportunities and avoiding low-probability periods detected through historical analysis.
Timeframe Compatibility
While the strategy is specifically adapted and optimized for the 15-minute timeframe (15M), it has been engineered to perform across multiple timeframes ranging from 5-minute to 4-hour intervals. This multi-timeframe versatility allows traders to adjust the strategy parameters according to their preferred trading style and market conditions.
This adaptability across different timeframes significantly enhances the strategy's robustness, making it more resilient to varying market regimes and reducing over-optimization to a single timeframe. By testing and validating across 5-minute to 4-hour intervals, the strategy demonstrates consistent edge across diverse trading environments, which strengthens confidence in its performance across broader market conditions.
Cross-Asset Testing
Beyond Bitcoin, this strategy could be tested and adapted for trading other cryptocurrencies, making it a flexible framework for exploring momentum-based opportunities across different digital assets with varying volatility profiles.
Performance Summary
This strategy has significantly outperformed a simple buy-and-hold approach over the 6-year backtest period. Here are the standout metrics:
Total P&L: +$41,277.80 USDT (+2,063.89%)
Net Profit: +$41,277.80 USDT with only 18.35% max drawdown
Total Trades: 2,169 with 44.63% win rate
Profit Factor: 2.17x (strong edge)
Key Advantage Over Buy & Hold
The Buy & Hold return was +$16,576.63 USDT (+828.83%), meaning this strategy more than doubled Buy & Hold returns over the same period. The active trading approach consistently captured momentum while the 2.17x profit factor demonstrates edge-based entries.
Commission Structure: A 0.1% commission per trade has been factored into the backtesting analysis, which is more than sufficient to cover typical exchange trading fees on major platforms. This conservative fee structure ensures the reported results account for real-world trading costs while still demonstrating substantial profitability.
Important Disclaimer
This strategy does not guarantee future profits and should be used after testing and analyzing in a simulated environment. A disciplined approach and appropriate risk management are recommended for the cryptocurrency market. Past performance is not indicative of future results, and actual trading may differ from backtested scenarios due to market slippage, liquidity conditions, and changing market dynamics.
Volume Sentiment Breakout Channels [AlgoAlpha]🟠 OVERVIEW
This tool visualizes breakout zones based on volume sentiment within dynamic price channels . It identifies high-impact consolidation areas, quantifies buy/sell dominance inside those zones, and then displays real-time shifts in sentiment strength. When the market breaks above or below these sentiment-weighted channels, traders can interpret the event as a change in conviction, not just a technical breakout.
🟠 CONCEPTS
The script builds on two layers of logic:
Channel Detection : A volatility-based algorithm locates price compression areas using normalized highs and lows over a defined lookback. These “boxes” mark accumulation or distribution ranges.
Volume Sentiment Profiling : Each channel is internally divided into small bins, where volume is aggregated and signed by candle direction. This produces a granular sentiment map showing which levels are dominated by buyers or sellers.
When a breakout occurs, the script clears the previous box and forms a new one, letting traders visually track transitions between phases of control. The colored gradients and text updates continuously reflect the internal bias—green for net-buying, red for net-selling—so you can see conviction strength at a glance.
🟠 FEATURES
Volume-weighted sentiment map inside each box, with gradient color intensity proportional to participation.
Dynamic text display of current and overall sentiment within each channel.
Real-time trail lines to show active bullish/bearish trend extensions after breakout.
🟠 USAGE
Setup : Add the script to your chart and enable Strong Closes Only if you prefer cleaner breakouts. Use shorter normalization length (e.g., 50–80) for fast markets; longer (100–200) for smoother transitions.
Read Signals : Transparent boxes mark active sentiment channels. Green gradients show buy-side dominance, red shows sell-side. The middle dashed line is the equilibrium of the channel. “▲” appears when price breaks upward, “▼” when it breaks downward.
Understanding Sentiment : The sentiment profile can be used to show the probability of the price moving up or down at respective price levels.
MTF K-Means Price Regimes [matteovesperi] ⚠️ The preview uses a custom example to identify support/resistance zones. due to the fact that this identifier clusterizes, this is possible. this example was set up "in a hurry", therefore it has a possible inaccuracy. When setting up the indicator, it is extremely important to select the correct parameters and double-check them on the selected history.
📊 OVERVIEW
Purpose
MTF K-Means Price Regimes is a TradingView indicator that automatically identifies and classifies the current market regime based on the K-Means machine learning algorithm. The indicator uses data from a higher timeframe (Multi-TimeFrame, MTF) to build stable classification and applies it to the working timeframe in real-time.
Key Features
✅ Automatic market regime detection — the algorithm finds clusters of similar market conditions
✅ Multi-timeframe (MTF) — clustering on higher TF, application on lower TF
✅ Adaptive — model recalculates when a new HTF bar appears with a rolling window
✅ Non-Repainting — classification is performed only on closed bars
✅ Visualization — bar coloring + information panel with cluster characteristics
✅ Flexible settings — from 2 to 10 clusters, customizable feature periods, HTF selection
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔬 TECHNICAL DETAILS
K-Means Clustering Algorithm
What is K-Means?
K-Means is one of the most popular clustering algorithms (unsupervised machine learning). It divides a dataset into K groups (clusters) so that similar elements are within each cluster, and different elements are between clusters.
Algorithm objective:
Minimize within-cluster variance (sum of squared distances from points to their cluster center).
How Does K-Means Work in Our Indicator?
Step 1: Data Collection
The indicator accumulates history from the higher timeframe (HTF):
RSI (Relative Strength Index) — overbought/oversold indicator
ATR% (Average True Range as % of price) — volatility indicator
ΔP% (Price Change in %) — trend strength and direction indicator
By default, 200 HTF bars are accumulated (clusterLookback parameter).
Step 2: Creating Feature Vectors
Each HTF bar is described by a three-dimensional vector:
Vector =
Step 3: Normalization (Z-Score)
All features are normalized to bring them to a common scale:
Normalized_Value = (Value - Mean) / StdDev
This is critically important, as RSI is in the range 0-100, while ATR% and ΔP% have different scales. Without normalization, one feature would dominate over others.
Step 4: K-Means++ Centroid Initialization
Instead of random selection of K initial centers, an improved K-Means++ method is used:
First centroid is randomly selected from the data
Each subsequent centroid is selected with probability proportional to the square of the distance to the nearest already selected centroid
This ensures better initial centroid distribution and faster convergence
Step 5: Iterative Optimization (Lloyd's Algorithm)
Repeat until convergence (or maxIterations):
1. Assignment step:
For each point find the nearest centroid and assign it to this cluster
2. Update step:
Recalculate centroids as the average of all points in each cluster
3. Convergence check:
If centroids shifted less than 0.001 → STOP
Euclidean distance in 3D space is used:
Distance = sqrt((RSI1 - RSI2)² + (ATR1 - ATR2)² + (ΔP1 - ΔP2)²)
Step 6: Adaptive Update
With each new HTF bar:
The oldest bar is removed from history (rolling window method)
New bar is added to history
K-Means algorithm is executed again on updated data
Model remains relevant for current market conditions
Real-Time Classification
After building the model (clusters + centroids), the indicator works in classification mode:
On each closed bar of the current timeframe, RSI, ATR%, ΔP% are calculated
Feature vector is normalized using HTF statistics (Mean/StdDev)
Distance to all K centroids is calculated
Bar is assigned to the cluster with minimum distance
Bar is colored with the corresponding cluster color
Important: Classification occurs only on a closed bar (barstate.isconfirmed), which guarantees no repainting .
Data Architecture
Persistent variables (var):
├── featureVectors - Normalized HTF feature vectors
├── centroids - Cluster center coordinates (K * 3 values)
├── assignments - Assignment of each HTF bar to a cluster
├── htfRsiHistory - History of RSI values from HTF
├── htfAtrHistory - History of ATR values from HTF
├── htfPcHistory - History of price changes from HTF
├── htfCloseHistory - History of close prices from HTF
├── htfRsiMean, htfRsiStd - Statistics for RSI normalization
├── htfAtrMean, htfAtrStd - Statistics for ATR normalization
├── htfPcMean, htfPcStd - Statistics for Price Change normalization
├── isCalculated - Model readiness flag
└── currentCluster - Current active cluster
All arrays are synchronized and updated atomically when a new HTF bar appears.
Computational Complexity
Data collection: O(1) per bar
K-Means (one pass):
- Assignment: O(N * K) where N = number of points, K = number of clusters
- Update: O(N * K)
- Total: O(N * K * I) where I = number of iterations (usually 5-20)
Example: With N=200 HTF bars, K=5 clusters, I=20 iterations:
200 * 5 * 20 = 20,000 operations (executes quickly)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📖 USER GUIDE
Quick Start
1. Adding the Indicator
TradingView → Indicators → Favorites → MTF K-Means Price Regimes
Or copy the code from mtf_kmeans_price_regimes.pine into Pine Editor.
2. First Launch
When adding the indicator to the chart, you'll see a table in the upper right corner:
┌─────────────────────────┐
│ Status │ Collecting HTF │
├─────────────────────────┤
│ Collected│ 15 / 50 │
└─────────────────────────┘
This means the indicator is accumulating history from the higher timeframe. Wait until the counter reaches the minimum (default 50 bars for K=5).
3. Active Operation
After data collection is complete, the main table with cluster information will appear:
┌────┬──────┬──────┬──────┬──────────────┬────────┐
│ ID │ RSI │ ATR% │ ΔP% │ Description │Current │
├────┼──────┼──────┼──────┼──────────────┼────────┤
│ 1 │ 68.5 │ 2.15 │ 1.2 │ High Vol,Bull│ │
│ 2 │ 52.3 │ 0.85 │ 0.1 │ Low Vol,Flat │ ► │
│ 3 │ 35.2 │ 1.95 │ -1.5 │ High Vol,Bear│ │
└────┴──────┴──────┴──────┴──────────────┴────────┘
The arrow ► indicates the current active regime. Chart bars are colored with the corresponding cluster color.
Customizing for Your Strategy
Choosing Higher Timeframe (HTF)
Rule: HTF should be at least 4 times higher than the working timeframe.
| Working TF | Recommended HTF |
|------------|-----------------|
| 1 min | 15 min - 1H |
| 5 min | 1H - 4H |
| 15 min | 4H - D |
| 1H | D - W |
| 4H | D - W |
| D | W - M |
HTF Selection Effect:
Lower HTF (closer to working TF): More sensitive, frequently changing classification
Higher HTF (much larger than working TF): More stable, long-term regime assessment
Number of Clusters (K)
K = 2-3: Rough division (e.g., "uptrend", "downtrend", "flat")
K = 4-5: Optimal for most cases (DEFAULT: 5)
K = 6-8: Detailed segmentation (requires more data)
K = 9-10: Very fine division (only for long-term analysis with large windows)
Important constraint:
clusterLookback ≥ numClusters * 10
I.e., for K=5 you need at least 50 HTF bars, for K=10 — at least 100 bars.
Clustering Depth (clusterLookback)
This is the rolling window size for building the model.
50-100 HTF bars: Fast adaptation to market changes
200 HTF bars: Optimal balance (DEFAULT)
500-1000 HTF bars: Long-term, stable model
If you get an "Insufficient data" error:
Decrease clusterLookback
Or select a lower HTF (e.g., "4H" instead of "D")
Or decrease numClusters
Color Scheme
Default 10 colors:
Red → Often: strong bearish, high volatility
Orange → Transition, medium volatility
Yellow → Neutral, decreasing activity
Green → Often: strong bullish, high volatility
Blue → Medium bullish, medium volatility
Purple → Oversold, possible reversal
Fuchsia → Overbought, possible reversal
Lime → Strong upward momentum
Aqua → Consolidation, low volatility
White → Undefined regime (rare)
Important: Cluster colors are assigned randomly at each model recalculation! Don't rely on "red = bearish". Instead, look at the description in the table (RSI, ATR%, ΔP%).
You can customize colors in the "Colors" settings section.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚙️ INDICATOR PARAMETERS
Main Parameters
Higher Timeframe (htf)
Type: Timeframe selection
Default: "D" (daily)
Description: Timeframe on which the clustering model is built
Recommendation: At least 4 times larger than your working TF
Clustering Depth (clusterLookback)
Type: Integer
Range: 50 - 2000
Default: 200
Description: Number of HTF bars for building the model (rolling window size)
Recommendation:
- Increase for more stable long-term model
- Decrease for fast adaptation or if there's insufficient historical data
Number of Clusters (K) (numClusters)
Type: Integer
Range: 2 - 10
Default: 5
Description: Number of market regimes the algorithm will identify
Recommendation:
- K=3-4 for simple strategies (trending/ranging)
- K=5-6 for universal strategies
- K=7-10 only when clusterLookback ≥ 100*K
Max K-Means Iterations (maxIterations)
Type: Integer
Range: 5 - 50
Default: 20
Description: Maximum number of algorithm iterations
Recommendation:
- 10-20 is sufficient for most cases
- Increase to 30-50 if using K > 7
Feature Parameters
RSI Period (rsiLength)
Type: Integer
Default: 14
Description: Period for RSI calculation (overbought/oversold feature)
Recommendation:
- 14 — standard
- 7-10 — more sensitive
- 20-25 — more smoothed
ATR Period (atrLength)
Type: Integer
Default: 14
Description: Period for ATR calculation (volatility feature)
Recommendation: Usually kept equal to rsiLength
Price Change Period (pcLength)
Type: Integer
Default: 5
Description: Period for percentage price change calculation (trend feature)
Recommendation:
- 3-5 — short-term trend
- 10-20 — medium-term trend
Visualization
Show Info Panel (showDashboard)
Type: Checkbox
Default: true
Description: Enables/disables the information table on the chart
Cluster Color 1-10
Type: Color selection
Description: Customize colors for visual cluster distinction
Recommendation: Use contrasting colors for better readability
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 INTERPRETING RESULTS
Reading the Information Table
┌────┬──────┬──────┬──────┬──────────────┬────────┐
│ ID │ RSI │ ATR% │ ΔP% │ Description │Current │
├────┼──────┼──────┼──────┼──────────────┼────────┤
│ 1 │ 68.5 │ 2.15 │ 1.2 │ High Vol,Bull│ │
│ 2 │ 52.3 │ 0.85 │ 0.1 │ Low Vol,Flat │ ► │
│ 3 │ 35.2 │ 1.95 │ -1.5 │ High Vol,Bear│ │
│ 4 │ 45.0 │ 1.20 │ -0.3 │ Low Vol,Bear │ │
│ 5 │ 72.1 │ 3.05 │ 2.8 │ High Vol,Bull│ │
└────┴──────┴──────┴──────┴──────────────┴────────┘
"ID" Column
Cluster number (1-K). Order doesn't matter.
"RSI" Column
Average RSI value in the cluster (0-100):
< 30: Oversold zone
30-45: Bearish sentiment
45-55: Neutral zone
55-70: Bullish sentiment
> 70: Overbought zone
"ATR%" Column
Average volatility in the cluster (as % of price):
< 1%: Low volatility (consolidation, narrow range)
1-2%: Normal volatility
2-3%: Elevated volatility
> 3%: High volatility (strong movements, impulses)
Compared to the average volatility across all clusters to determine "High Vol" or "Low Vol".
"ΔP%" Column
Average price change in the cluster (in % over pcLength period):
> +0.05%: Bullish regime
-0.05% ... +0.05%: Flat (sideways movement)
< -0.05%: Bearish regime
"Description" Column
Automatic interpretation:
"High Vol, Bull" → Strong upward momentum, high activity
"Low Vol, Flat" → Consolidation, narrow range, uncertainty
"High Vol, Bear" → Strong decline, panic, high activity
"Low Vol, Bull" → Slow growth, low activity
"Low Vol, Bear" → Slow decline, low activity
"Current" Column
Arrow ► shows which cluster the last closed bar of your working timeframe is in.
Typical Cluster Patterns
Example 1: Trend/Flat Division (K=3)
Cluster 1: RSI=65, ATR%=2.5, ΔP%=+1.5 → Bullish trend
Cluster 2: RSI=50, ATR%=0.8, ΔP%=0.0 → Flat/Consolidation
Cluster 3: RSI=35, ATR%=2.3, ΔP%=-1.4 → Bearish trend
Strategy: Open positions when regime changes Flat → Trend, avoid flat.
Example 2: Volatility Breakdown (K=5)
Cluster 1: RSI=72, ATR%=3.5, ΔP%=+2.5 → Strong bullish impulse (high risk)
Cluster 2: RSI=60, ATR%=1.5, ΔP%=+0.8 → Moderate bullish (optimal entry point)
Cluster 3: RSI=50, ATR%=0.7, ΔP%=0.0 → Flat
Cluster 4: RSI=40, ATR%=1.4, ΔP%=-0.7 → Moderate bearish
Cluster 5: RSI=28, ATR%=3.2, ΔP%=-2.3 → Strong bearish impulse (panic)
Strategy: Enter in Cluster 2 or 4, avoid extremes (1, 5).
Example 3: Mixed Regimes (K=7+)
With large K, clusters can represent condition combinations:
High RSI + Low volatility → "Quiet overbought"
Neutral RSI + High volatility → "Uncertainty with high activity"
Etc.
Requires individual analysis of each cluster.
Regime Changes
Important signal: Transition from one cluster to another!
Trading situation examples:
Flat → Bullish trend → Buy signal
Bullish trend → Flat → Take profit, close longs
Flat → Bearish trend → Sell signal
Bearish trend → Flat → Close shorts, wait
You can build a trading system based on the current active cluster and transitions between them.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
💡 USAGE EXAMPLES
Example 1: Scalping with HTF Filter
Task: Scalping on 5-minute charts, but only enter in the direction of the daily regime.
Settings:
Working TF: 5 min
HTF: D (daily)
K: 3 (simple division)
clusterLookback: 100
Logic:
IF current cluster = "Bullish" (ΔP% > 0.5)
→ Look for long entry points on 5M
IF current cluster = "Bearish" (ΔP% < -0.5)
→ Look for short entry points on 5M
IF current cluster = "Flat"
→ Don't trade / reduce risk
Example 2: Swing Trading with Volatility Filtering
Task: Swing trading on 4H, enter only in regimes with medium volatility.
Settings:
Working TF: 4H
HTF: D (daily)
K: 5
clusterLookback: 200
Logic:
Allowed clusters for entry:
- ATR% from 1.5% to 2.5% (not too quiet, not too chaotic)
- ΔP% with clear direction (|ΔP%| > 0.5)
Prohibited clusters:
- ATR% > 3% → Too risky (possible gaps, sharp reversals)
- ATR% < 1% → Too quiet (small movements, commissions eat profit)
Example 3: Portfolio Rotation
Task: Managing a portfolio of multiple assets, allocate capital depending on regimes.
Settings:
Working TF: D (daily)
HTF: W (weekly)
K: 4
clusterLookback: 100
Logic:
For each asset in portfolio:
IF regime = "Strong trend + Low volatility"
→ Increase asset weight in portfolio (40-50%)
IF regime = "Medium trend + Medium volatility"
→ Standard weight (20-30%)
IF regime = "Flat" or "High volatility without trend"
→ Minimum weight or exclude (0-10%)
Example 4: Combining with Other Indicators
MTF K-Means as a filter:
Main strategy: MA Crossover
Filter: MTF K-Means on higher TF
Rule:
IF MA_fast > MA_slow AND Cluster = "Bullish regime"
→ LONG
IF MA_fast < MA_slow AND Cluster = "Bearish regime"
→ SHORT
ELSE
→ Don't trade (regime doesn't confirm signal)
This dramatically reduces false signals in unsuitable market conditions.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📈 OPTIMIZATION RECOMMENDATIONS
Optimal Settings for Different Styles
Day Trading
Working TF: 5M - 15M
HTF: 1H - 4H
numClusters: 4-5
clusterLookback: 100-150
Swing Trading
Working TF: 1H - 4H
HTF: D
numClusters: 5-6
clusterLookback: 150-250
Position Trading
Working TF: D
HTF: W - M
numClusters: 4-5
clusterLookback: 100-200
Scalping
Working TF: 1M - 5M
HTF: 15M - 1H
numClusters: 3-4
clusterLookback: 50-100
Backtesting
To evaluate effectiveness:
Load historical data (minimum 2x clusterLookback HTF bars)
Apply the indicator with your settings
Study cluster change history:
- Do changes coincide with actual trend transitions?
- How often do false signals occur?
Optimize parameters:
- If too much noise → increase HTF or clusterLookback
- If reaction too slow → decrease HTF or increase numClusters
Combining with Other Techniques
Regime-Based Approach:
MTF K-Means (regime identification)
↓
+---+---+---+
| | | |
v v v v
Trend Flat High_Vol Low_Vol
↓ ↓ ↓ ↓
Strategy_A Strategy_B Don't_trade
Examples:
Trend: Use trend-following strategies (MA crossover, Breakout)
Flat: Use mean-reversion strategies (RSI, Bollinger Bands)
High volatility: Reduce position sizes, widen stops
Low volatility: Expect breakout, don't open positions inside range
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📞 SUPPORT
Report an Issue
If you found a bug or have a suggestion for improvement:
Describe the problem in as much detail as possible
Specify your indicator settings
Attach a screenshot (if possible)
Specify the asset and timeframe where the problem is observed
Adaptive Target Tracker [wjdtks255]📊 Adaptive Target Tracker
Indicator Description
The Adaptive Target Tracker is a trend-following indicator that combines moving averages with an adaptive ATR (Average True Range) calculation to detect market trends with dynamic sensitivity. It plots entry lines, multiple profit targets (T1, T2, T3), and stop-loss levels directly on the chart, enabling traders to visualize trade setups clearly.
The indicator dynamically adjusts to market volatility, distinguishing between upward (long) and downward (short) trends, and reflects these states with distinct colored lines and labels for precise trade management.
🔍 How It Works
Trend Detection: The indicator calculates smoothed price bands by adding or subtracting ATR to the moving average of highs and lows.
Entry Signal: A crossover of the closing price above the upper band signals a long position; crossing below the lower band signals a short position.
Visual Elements: Entry price, stop-loss line (in red), and three progressively spaced target lines (in blue) are plotted for clear profit-taking guidance.
Confirmation & Alerts: Entry signals are marked with arrows and labels—green for long entries, orange for shorts—to help identify optimal trade points.
Real-Time Update: Lines and labels move forward with the price action and display check marks upon hitting target levels.
💡 Trading Method
Entry: Enter a long trade when the price closes above the adaptive upper band (green entry line and label appear). Enter a short trade when the price closes below the adaptive lower band (orange entry line and label appear).
Profit Targets: Use the three predefined target levels (T1, T2, T3) as incremental profit-taking points. These targets are calculated relative to the entry and ATR to ensure adaptability to market volatility.
Stop Loss: Set stop loss at the red line representing the calculated risk threshold below (for longs) or above (for shorts) the entry price.
Management: Monitor the chart for target achievement; when a target is hit, the indicator marks it with a check symbol. Adjust position exposure accordingly to lock in profits and minimize risk.
Customization: Parameters such as trend window length and ATR offset can be adjusted to suit trading style and timeframes.
Summary
The Adaptive Target Tracker is ideal for traders seeking clear visual trade signals with multi-level exit strategies and volatility-adapted risk management. It helps filter noise and focus on significant trend movements while providing practical entry, target, and stop-loss tools across various timeframes and asset classes.
Zscore COrrelation volatility OberlinThis is a complete multi-strategy dashboard for statistical arbitrage (pairs trading). It is designed to solve the biggest challenge in pairs trading: knowing when to trade mean-reversion and when to trade a regime break.
This indicator automatically analyzes the stability of the pair's relationship using two critical filters (a Volatility Ratio filter and a Correlation Z-Score filter). It then provides clear, actionable signals for two opposite strategies based on the current market "regime."
The Regime "Traffic Light" System
The indicator's background color tells you which strategy is currently active.
• 🟢 GREEN Background (Stable Regime): This is the "Mean Reversion" regime. It means both the volatility and correlation filters are stable. The pair is behaving predictably, and you can trust the Z-Score to revert to its mean.
• 🔴 RED Background (Unstable Regime): This is the "Divergence" or "Breakout" regime. It means the pair's relationship has failed (correlation has broken down OR volatility has exploded). In this regime, the Z-Score is not expected to revert and may continue to diverge.
How to Use: The Two Strategies
The indicator will plot text labels on your chart for four specific signals.
📈 Strategy 1: Mean Reversion (Green Regime 🟢)
This is the classic pairs trading strategy. You only take these signals when the background is GREEN.
• LONG Signal: "ACHAT MOYENNE" (Buy Mean)
• What it means: The Z-Score (blue line) has crossed below the lower band (e.g., -2.0) while the regime is stable.
• Your Bet: The spread is statistically "too cheap" and will rise back to the 0-line.
• Action: Buy the Spread (e.g., Buy MES, Sell MNQ).
• SHORT Signal: "VENTE MOYENNE" (Sell Mean)
• What it means: The Z-Score (blue line) has crossed above the upper band (e.g., +2.0) while the regime is stable.
• Your Bet: The spread is statistically "too expensive" and will fall back to the 0-line.
• Action: Sell the Spread (e.g., Sell MES, Buy MNQ).
• Exit Target: Close your position when the Z-Score (blue line) returns to 0.
🚀 Strategy 2: Divergence / Momentum (Red Regime 🔴)
This is a momentum strategy that bets on the continuation of a regime break. These signals appear on the exact bar the background turns RED.
• LONG Signal: "ACHAT ÉCART" (Buy Divergence)
• What it means: The regime just broke (turned RED) at the same time the Z-Score was already rising.
• Your Bet: The pair's relationship is broken, and the spread will continue to "rip" higher, diverging further from the mean.
• Action: Buy the Spread (e.g., Buy MES, Sell MNQ) and hold for momentum.
• SHORT Signal: "VENTE ÉCART" (Sell Divergence)
• What it means: The regime just broke (turned RED) at the same time the Z-Score was already falling.
• Your Bet: The pair's relationship is broken, and the spread will continue to "crash" lower, diverging further from the mean.
• Action: Sell the Spread (e.g., Sell MES, Buy MNQ) and hold for momentum.
• Exit Target: This is a momentum trade, so the exit is not the 0-line. Use a trailing stop or exit when the regime becomes stable again (turns GREEN).
The 3 Indicator Panes
1. Pane 1: Main Dashboard (Signal Pane)
• Z-Score PRIX (Blue Line): Your main signal. Shows the spread's deviation.
• Regime (Background Color): Your "traffic light" (Green for Mean Reversion, Red for Divergence).
• Trade Labels: The explicit entry signals.
2. Pane 2: Volatility Ratio (Diagnostic Pane)
• This pane shows the ratio of the two assets' volatility (Orange Line) vs. its long-term average (Gray Line).
• It is one of the two filters used to decide if the regime is "stable." If the orange line moves too far from the gray line, the regime turns RED.
3. Pane 3: Correlation Z-Score (Diagnostic Pane)
• This is the most critical filter. It measures the Z-Score of the rolling correlation itself.
• If this Purple Line drops below the Red Dashed Line (the "Danger Threshold"), it means the pair's correlation has statistically broken. This is the primary trigger for the RED "Divergence" regime.
Settings
• Symbol 1 & 2 Tickers: Set the two assets for the filters (e.g., "MES1!" and "MNQ1!"). Note: You must still load the spread chart itself (e.g., MES1!-MNQ1!) for the Price Z-Score to work.
• Z-Score Settings: Adjust the lookback period and bands for the Price Z-Score.
• Volatility Filter Settings: Adjust the ATR period, the MA period, and the deviation threshold.
• Correlation Filter Settings: Adjust the lookback periods and the "danger threshold" for the Correlation Z-Score.
Disclaimer: This indicator is for educational and informational purposes only. It does not constitute financial advice. All trading involves significant risk. Past performance is not indicative of future results.
ZScore correlation volatility spread pacThis is a complete multi-strategy dashboard for statistical arbitrage (pairs trading). It is designed to solve the biggest challenge in pairs trading: knowing when to trade mean-reversion and when to trade a regime break.
This indicator automatically analyzes the stability of the pair's relationship using two critical filters (a Volatility Ratio filter and a Correlation Z-Score filter). It then provides clear, actionable signals for two opposite strategies based on the current market "regime."
The Regime "Traffic Light" System
The indicator's background color tells you which strategy is currently active.
• 🟢 GREEN Background (Stable Regime): This is the "Mean Reversion" regime. It means both the volatility and correlation filters are stable. The pair is behaving predictably, and you can trust the Z-Score to revert to its mean.
• 🔴 RED Background (Unstable Regime): This is the "Divergence" or "Breakout" regime. It means the pair's relationship has failed (correlation has broken down OR volatility has exploded). In this regime, the Z-Score is not expected to revert and may continue to diverge.
How to Use: The Two Strategies
The indicator will plot text labels on your chart for four specific signals.
📈 Strategy 1: Mean Reversion (Green Regime 🟢)
This is the classic pairs trading strategy. You only take these signals when the background is GREEN.
• LONG Signal: "ACHAT MOYENNE" (Buy Mean)
• What it means: The Z-Score (blue line) has crossed below the lower band (e.g., -2.0) while the regime is stable.
• Your Bet: The spread is statistically "too cheap" and will rise back to the 0-line.
• Action: Buy the Spread (e.g., Buy MES, Sell MNQ).
• SHORT Signal: "VENTE MOYENNE" (Sell Mean)
• What it means: The Z-Score (blue line) has crossed above the upper band (e.g., +2.0) while the regime is stable.
• Your Bet: The spread is statistically "too expensive" and will fall back to the 0-line.
• Action: Sell the Spread (e.g., Sell MES, Buy MNQ).
• Exit Target: Close your position when the Z-Score (blue line) returns to 0.
🚀 Strategy 2: Divergence / Momentum (Red Regime 🔴)
This is a momentum strategy that bets on the continuation of a regime break. These signals appear on the exact bar the background turns RED.
• LONG Signal: "ACHAT ÉCART" (Buy Divergence)
• What it means: The regime just broke (turned RED) at the same time the Z-Score was already rising.
• Your Bet: The pair's relationship is broken, and the spread will continue to "rip" higher, diverging further from the mean.
• Action: Buy the Spread (e.g., Buy MES, Sell MNQ) and hold for momentum.
• SHORT Signal: "VENTE ÉCART" (Sell Divergence)
• What it means: The regime just broke (turned RED) at the same time the Z-Score was already falling.
• Your Bet: The pair's relationship is broken, and the spread will continue to "crash" lower, diverging further from the mean.
• Action: Sell the Spread (e.g., Sell MES, Buy MNQ) and hold for momentum.
• Exit Target: This is a momentum trade, so the exit is not the 0-line. Use a trailing stop or exit when the regime becomes stable again (turns GREEN).
The 3 Indicator Panes
1. Pane 1: Main Dashboard (Signal Pane)
• Z-Score PRIX (Blue Line): Your main signal. Shows the spread's deviation.
• Regime (Background Color): Your "traffic light" (Green for Mean Reversion, Red for Divergence).
• Trade Labels: The explicit entry signals.
2. Pane 2: Volatility Ratio (Diagnostic Pane)
• This pane shows the ratio of the two assets' volatility (Orange Line) vs. its long-term average (Gray Line).
• It is one of the two filters used to decide if the regime is "stable." If the orange line moves too far from the gray line, the regime turns RED.
3. Pane 3: Correlation Z-Score (Diagnostic Pane)
• This is the most critical filter. It measures the Z-Score of the rolling correlation itself.
• If this Purple Line drops below the Red Dashed Line (the "Danger Threshold"), it means the pair's correlation has statistically broken. This is the primary trigger for the RED "Divergence" regime.
Settings
• Symbol 1 & 2 Tickers: Set the two assets for the filters (e.g., "MES1!" and "MNQ1!"). Note: You must still load the spread chart itself (e.g., MES1!-MNQ1!) for the Price Z-Score to work.
• Z-Score Settings: Adjust the lookback period and bands for the Price Z-Score.
• Volatility Filter Settings: Adjust the ATR period, the MA period, and the deviation threshold.
• Correlation Filter Settings: Adjust the lookback periods and the "danger threshold" for the Correlation Z-Score.
Disclaimer: This indicator is for educational and informational purposes only. It does not constitute financial advice. All trading involves significant risk. Past performance is not indicative of future results.
Fakeout Kavach by Pooja v10📘 Description – Fakeout Kavach by Pooja
Fakeout Kavach by Pooja is a precision-built technical analysis tool designed for structured momentum and divergence evaluation within the RSI pane.
It helps visualize potential exhaustion zones using RSI divergence, ADX trend confirmation, and an integrated VAD (Volume + ATR + Delta) module — ensuring clarity and confirmation-based plotting.
⚙️ Core Functional Modules
1️⃣ RSI & Moving Average Module
Adaptive RSI with real-time color gradients
Optional RSI moving average (yellow) for momentum tracking
Dynamic fill zones showing overbought / oversold areas
Background fill for quick zone visualization
2️⃣ RSI Divergence Detection (Bull / Bear)
Auto-detects pivot-based bullish and bearish divergences
Non-repainting logic confirmed post-pivot formation
Smart line management with automatic cleanup
Visual divergence lines and clear on-chart markers
3️⃣ ADX Trend Confirmation
Adjustable comparison: “Higher than N bars ago” or “Higher than highest of last N”
Confirms directional strength before SB / SS signals are displayed
4️⃣ SB / SS Signal Module
“Signal Bull / Signal Sell” markers confirmed post candle closure
Integrated session-block feature to exclude specific intraday periods
Non-repainting, bar-confirmed signal plotting
5️⃣ VAD (Volume + ATR + Delta) Divergence Engine
Highlights hidden momentum shifts via volatility + volume flow logic
Bullish (B-DV) / Bearish (S-DV) divergence markers plotted at pivot bars
Customizable label or symbol-style visualization
🧩 Built-in Features
Non-repainting structure using barstate confirmation
Optimized for all timeframes and chart types
Lightweight execution with flexible styling options
Modular input control for easy customization
⚠️ Disclaimer
This indicator is for technical analysis and educational purposes only.
It does not provide financial advice, does not predict price direction, and does not guarantee profits or performance.
All trading decisions are the sole responsibility of the user. Always test thoroughly before applying to live markets.
Lightning Osc • PreVersion
The Lightning Osc • PreVersion is where the MahaTrend vision began —
the first oscillator designed to visualize the pulse of the market itself.
It reveals how momentum expands, cools down, and reverses through natural rhythm,
allowing you to see balance and exhaustion with clarity and precision.
This is the original core from which every Lightning indicator later evolved —
simple, focused, and deeply intuitive.
🧭 Purpose
The indicator highlights overbought and oversold rhythm zones,
helping traders recognize when the market may have reached its energetic limits.
Rather than generating signals, it visualizes the transitions of energy
— the quiet shift that often happens before price movement changes direction.
💡 Core Logic
When the curve moves above +67.65, the market enters an overbought zone.
The most informative moment is the break below and retest of that boundary —
it often reflects fading upward strength and possible correction.
When the curve dips below −67.65, the market enters an oversold zone.
A break above and retest of this area may show that selling pressure is exhausted
and the market is ready for relief or reversal.
These levels do not dictate trades — they show rhythm
so you can understand when momentum begins to breathe again.
⏱ Recommended Timeframes
Optimized for 1-minute to 1-hour charts,
the Lightning Osc • PreVersion is most expressive on lower timeframes
where short-term volatility and energy flow are clearly visible.
🧩 How to Use
Add the indicator to a separate pane below your chart.
Choose the calculation timeframe (default: current chart TF).
Observe the curve:
Above +67.65 → Overbought zone
Below −67.65 → Oversold zone
±4.6 → Micro-pulse equilibrium
Focus on break & retest behavior near key zones —
these moments often reveal changing market rhythm.
Always confirm with your broader context and personal strategy.
🌩 Philosophy
This PreVersion marks the beginning of the Lightning language —
a balance between structure and flow,
between overextension and calm restoration.
It embodies the MahaTrend idea that the market is not chaos,
but an energy field breathing in and out through rhythm.
Disclaimer:
For educational and analytical use only.
This indicator does not provide financial advice or guaranteed results.
Always combine it with your own analysis and risk management.
— by MahaTrend
Multi-Mode Seasonality Map [BackQuant]Multi-Mode Seasonality Map
A fast, visual way to expose repeatable calendar patterns in returns, volatility, volume, and range across multiple granularities (Day of Week, Day of Month, Hour of Day, Week of Month). Built for idea generation, regime context, and execution timing.
What is “seasonality” in markets?
Seasonality refers to statistically repeatable patterns tied to the calendar or clock, rather than to price levels. Examples include specific weekdays tending to be stronger, certain hours showing higher realized volatility, or month-end flow boosting volumes. This tool measures those effects directly on your charted symbol.
Why seasonality matters
It’s orthogonal alpha: timing edges independent of price structure that can complement trend, mean reversion, or flow-based setups.
It frames expectations: when a session typically runs hot or cold, you size and pace risk accordingly.
It improves execution: entering during historically favorable windows, avoiding historically noisy windows.
It clarifies context: separating normal “calendar noise” from true anomaly helps avoid overreacting to routine moves.
How traders use seasonality in practice
Timing entries/exits : If Tuesday morning is historically weak for this asset, a mean-reversion buyer may wait for that drift to complete before entering.
Sizing & stops : If 13:00–15:00 shows elevated volatility, widen stops or reduce size to maintain constant risk.
Session playbooks : Build repeatable routines around the hours/days that consistently drive PnL.
Portfolio rotation : Compare seasonal edges across assets to schedule focus and deploy attention where the calendar favors you.
Why Day-of-Week (DOW) can be especially helpful
Flows cluster by weekday (ETF creations/redemptions, options hedging cadence, futures roll patterns, macro data releases), so DOW often encodes a stable micro-structure signal.
Desk behavior and liquidity provision differ by weekday, impacting realized range and slippage.
DOW is simple to operationalize: easy rules like “fade Monday afternoon chop” or “press Thursday trend extension” can be tested and enforced.
What this indicator does
Multi-mode heatmaps : Switch between Day of Week, Day of Month, Hour of Day, Week of Month .
Metric selection : Analyze Returns , Volatility ((high-low)/open), Volume (vs 20-bar average), or Range (vs 20-bar average).
Confidence intervals : Per cell, compute mean, standard deviation, and a z-based CI at your chosen confidence level.
Sample guards : Enforce a minimum sample size so thin data doesn’t mislead.
Readable map : Color palettes, value labels, sample size, and an optional legend for fast interpretation.
Scoreboard : Optional table highlights best/worst DOW and today’s seasonality with CI and a simple “edge” tag.
How it’s calculated (under the hood)
Per bar, compute the chosen metric (return, vol, volume %, or range %) over your lookback window.
Bucket that metric into the active calendar bin (e.g., Tuesday, the 15th, 10:00 hour, or Week-2 of month).
For each bin, accumulate sum , sum of squares , and count , then at render compute mean , std dev , and confidence interval .
Color scale normalizes to the observed min/max of eligible bins (those meeting the minimum sample size).
How to read the heatmap
Color : Greener/warmer typically implies higher mean value for the chosen metric; cooler implies lower.
Value label : The center number is the bin’s mean (e.g., average % return for Tuesdays).
Confidence bracket : Optional “ ” shows the CI for the mean, helping you gauge stability.
n = sample size : More samples = more reliability. Treat small-n bins with skepticism.
Suggested workflows
Pick the lens : Start with Analysis Type = Returns , Heatmap View = Day of Week , lookback ≈ 252 trading days . Note the best/worst weekdays and their CI width.
Sanity-check volatility : Switch to Volatility to see which bins carry the most realized range. Use that to plan stop width and trade pacing.
Check liquidity proxy : Flip to Volume , identify thin vs thick windows. Execute risk in thicker windows to reduce slippage.
Drill to intraday : Use Hour of Day to reveal opening bursts, lunchtime lulls, and closing ramps. Combine with your main strategy to schedule entries.
Calendar nuance : Inspect Week of Month and Day of Month for end-of-month, options-cycle, or data-release effects.
Codify rules : Translate stable edges into rules like “no fresh risk during bottom-quartile hours” or “scale entries during top-quartile hours.”
Parameter guidance
Analysis Period (Days) : 252 for a one-year view. Shorten (100–150) to emphasize the current regime; lengthen (500+) for long-memory effects.
Heatmap View : Start with DOW for robustness, then refine with Hour-of-Day for your execution window.
Confidence Level : 95% is standard; use 90% if you want wider coverage with fewer false “insufficient data” bins.
Min Sample Size : 10–20 helps filter noise. For Hour-of-Day on higher timeframes, consider lowering if your dataset is small.
Color Scheme : Choose a palette with good mid-tone contrast (e.g., Red-Green or Viridis) for quick thresholding.
Interpreting common patterns
Return-positive but low-vol bins : Favorable drift windows for passive adds or tight-stop trend continuation.
Return-flat but high-vol bins : Opportunity for mean reversion or breakout scalping, but manage risk accordingly.
High-volume bins : Better expected execution quality; schedule size here if slippage matters.
Wide CI : Edge is unstable or sample is thin; treat as exploratory until more data accumulates.
Best practices
Revalidate after regime shifts (new macro cycle, liquidity regime change, major exchange microstructure updates).
Use multiple lenses: DOW to find the day, then Hour-of-Day to refine the entry window.
Combine with your core setup signals; treat seasonality as a filter or weight, not a standalone trigger.
Test across assets/timeframes—edges are instrument-specific and may not transfer 1:1.
Limitations & notes
History-dependent: short histories or sparse intraday data reduce reliability.
Not causal: a hot Tuesday doesn’t guarantee future Tuesday strength; treat as probabilistic bias.
Aggregation bias: changing session hours or symbol migrations can distort older samples.
CI is z-approximate: good for fast triage, not a substitute for full hypothesis testing.
Quick setup
Use Returns + Day of Week + 252d to get a clean yearly map of weekday edge.
Flip to Hour of Day on intraday charts to schedule precise entries/exits.
Keep Show Values and Confidence Intervals on while you calibrate; hide later for a clean visual.
The Multi-Mode Seasonality Map helps you convert the calendar from an afterthought into a quantitative edge, surfacing when an asset tends to move, expand, or stay quiet—so you can plan, size, and execute with intent.
SigmaRevert: Z-Score Adaptive Mean Reversion [KedArc Quant]🔍 Overview
SigmaRevert is a clean, research-driven mean-reversion framework built on Z-Score deviation — a statistical measure of how far the current price diverges from its dynamic mean.
When price stretches too far from equilibrium (the mean), SigmaRevert identifies the statistical “sigma distance” and seeks reversion trades back toward it. Designed primarily for 5-minute intraday use, SigmaRevert automatically adapts to volatility via ATR-based scaling, optional higher-timeframe trend filters, and cooldown logic for controlled frequency
🧠 What “Sigma” Means Here
In statistics, σ (sigma) represents standard deviation, the measure of dispersion or variability.
SigmaRevert uses this concept directly:
Each bar’s price deviation from the mean is expressed as a Z-Score — the number of sigmas away from the mean.
When Z > 1.5, the price is statistically “over-extended”; when it returns toward 0, it reverts to the mean.
In short:
Sigma = Standard deviation distance
SigmaRevert = Trading the reversion of extreme sigma deviations
💡 Why Traders Use SigmaRevert
Quant-based clarity: removes emotion by relying on statistical extremes.
Volatility-adaptive: automatically adjusts to changing market noise.
Low drawdown: filters avoid over-exposure during strong trends.
Multi-market ready: works across stocks, indices, and crypto with parameter tuning.
Modular design: every component can be toggled without breaking the core logic.
🧩 Why This Is NOT a Mash-Up
Unlike “mash-up” scripts that randomly combine indicators, this strategy is built around one cohesive hypothesis:
“Price deviations from a statistically stable mean (Z-Score) tend to revert.”
Every module — ATR scaling, cooldown, HTF trend gating, exits — reinforces that single hypothesis rather than mixing unrelated systems (like RSI + MACD + EMA).
The structure is minimal yet expandable, maintaining research integrity and transparency.
⚙️ Input Configuration (Simplified Table)
Core
`maLen` 120 Lookback for mean (SMA)
`zLen` 60 Window for Z-score deviation
`zEntry` 1.5 Entry when Z exceeds threshold
`zExit` 0.3 Exit when Z normalizes
Filters (optional)
`useReCross` false Requires re-entry confirmation
`useTrend` false / true Enables HTF SMA bias
`htfTF` “60” HTF timeframe (e.g. 60-min)
`useATRDist` false Demands min distance from mean
`atrK` 1.0 ATR distance multiplier
`useCooldown` false / true Forces rest after exit
Risk
`useATRSL` false / true Adaptive stop-loss via ATR
`atrLen` 14 ATR lookback
`atrX` 1.4 ATR multiplier for stop
Session
`useSession` false Restrict to market hours
`sess` “0915-1530” NSE timing
`skipOpenBars` 0–3 Avoid early volatility
UI
`showBands` true Displays ±1σ & ±2σ
`showMarks` true Shows triggers and exits
🎯 Entry & Exit Logic
Long Entry
Trigger: `Z < -zEntry`
Optional re-cross: prior Z < −zEntry, current Z −zEntry
Optional trend bias: current close above HTF SMA
Optional ATR filter: distance from mean ATR × K
Short Entry
Trigger: `Z +zEntry`
Optional re-cross: prior Z +zEntry, current Z < +zEntry
Optional trend bias: current close below HTF SMA
Optional ATR filter: distance from mean ATR × K
Exit Conditions
Primary exit: `Z < zExit` (price normalized)
Time stop: `bars since entry timeStop`
Optional ATR stop-loss: ±ATR × multiplier
Optional cooldown: no new trade for X bars after exit
🕒 When to Use
Intraday (5m)
`maLen=120`, `zEntry=1.5`, `zExit=0.3`, `useTrend=false`, `cooldownBars=6` Capture intraday oscillations Minutes → hours
Swing (30m–1H)
`maLen=200`, `zEntry=1.8`, `zExit=0.4`, `useTrend=true`, `htfTF="D"` Mean-reversion between daily pivots 1–2 days
Positional (4H–1D)
`maLen=300`, `zEntry=2.0`, `zExit=0.5`, `useTrend=true` Capture multi-day mean reversions Days → weeks
📘 Glossary
Z-Score
Statistical measure of how far current price deviates from its mean, normalized by standard deviation.
Mean Reversion
The tendency of price to return to its average after temporary divergence.
ATR
Average True Range — measures volatility and defines adaptive stop distances.
Re-Cross
Secondary signal confirming reversal after an extreme.
HTF
Higher Timeframe — provides macro trend bias (e.g. 1-hour or daily).
Cooldown
Minimum bars to wait before re-entering after a trade closes.
❓ FAQ
Q1: Why are there no trades sometimes?
➡ Check that all filters are off. If still no trades, Z-scores might not breach the thresholds. Lower `zEntry` (1.2–1.4) to increase frequency.
Q2: Why does it sometimes fade breakouts?
➡ Mean reversion assumes overextension — disable it during strong trending days or use the HTF filter.
Q3: Can I use this for Forex or Crypto?
➡ Yes — but adjust session filters (`useSession=false`) and increase `maLen` for smoother means.
Q4: Why is profit factor so high but small overall gain?
➡ Because this script focuses on capital efficiency — low drawdown and steady scaling. Increase position size once stable.
Q5: Can I automate this on broker integration?
➡ Yes — the strategy uses standard `strategy.entry` and `strategy.exit` calls, compatible with TradingView webhooks.
🧭 How It Helps Traders
This strategy gives:
Discipline: no impulsive trades — strict statistical rules.
Consistency: removes emotional bias; same logic applies every bar.
Scalability: works across instruments and timeframes.
Transparency: all signals are derived from visible Z-Score math.
It’s ideal for quant-inclined discretionary traders who want rule-based entries but maintain human judgment for context (earnings days, macro news, etc.).
🧱 Final Notes
Best used on liquid stocks with continuous price movement.
Avoid illiquid or gap-heavy tickers.
Validate parameters per instrument — Z behavior differs between equities and indices.
Remember: Mean reversion works best in range-bound volatility, not during explosive breakouts.
⚠️ Disclaimer
This script is provided for educational purposes only.
Past performance does not guarantee future results.
Trading involves risk, and users should exercise caution and use proper risk management when applying this strategy.
Adaptive Trend Kernel📘 Adaptive Trend Kernel — Smoothed Regression Trend with Dynamic Bands
The Adaptive Trend Kernel is a regression-based trend indicator that dynamically adapts to market volatility.
It combines linear regression with standard deviation bands to identify directional bias, momentum shifts, and potential entry zones with high precision.
This tool helps traders visualize the underlying trend and filter out market noise by plotting a smooth regression line (the "kernel") surrounded by upper and lower deviation bands.
The indicator also provides crossover-based buy and sell signals when price crosses above or below the adaptive regression line.
🔍 How It Works
Regression Line: A linear regression line smooths the closing price to represent the dominant market direction.
Volatility Bands: The upper and lower bands (based on standard deviation) expand or contract according to market volatility.
Signal Triggers:
• Long Signal (Green Triangle): When price crosses above the regression line.
• Short Signal (Red Triangle): When price crosses below the regression line.
Trend Labels: Optional “Up” and “Down” labels appear on crossover points for better visual clarity.
💡 Trading Strategy
Trend Following: Enter long when a green “Up” signal appears, confirming an upward crossover.
Exit when the price touches the upper band or when a red “Down” signal appears.
Reversal Catching: In ranging markets, watch for quick crossovers near the bands — these often precede short-term pullbacks.
Volatility Filter: When the bands widen, volatility is high — consider using smaller position sizes or waiting for confirmation.
Narrowing bands often indicate consolidation and upcoming breakout potential.
⚙️ Features
Adjustable Regression Length and Band Multiplier
Customizable colors, transparency, and label visibility
Lightweight and repaint-free by design
Works well on all timeframes and asset classes (Forex, Crypto, Stocks, Gold)
🧭 Recommended Use
Use this indicator as a trend confirmation tool or entry filter in combination with momentum or volume indicators.
Best results occur when aligned with higher timeframe trend direction.
Volatility Spike AlertsVolatility Spike Alerts can be configured to alert on a manually set multiple of volatility or dynamically. Volatility is calculated off a customizable True Range and alerts upon bar close.
XAUUSD Multi-Timeframe Supertrend Alert v2**Indicator Overview: XAUUSD Multi-Timeframe Supertrend Alert v2**
**Core Components:**
1. **Multi-Timeframe Supertrend System**
- Two Supertrend indicators (ST1 & ST2) with customizable timeframes
- ST1 typically set to Daily, ST2 to Weekly as main trend
- Visualized with distinct colors and background fills
2. **Customizable SMA**
- Adjustable period and timeframe
- Plotted as blue line for additional trend reference
3. **Neutral Zone System**
- Creates a neutral line offset from ST1 by customizable tick distance
- Yellow dashed line that adjusts based on ST1 trend direction
- **Alert Conditions:**
- **Test Buy Zone**: Both ST1 & ST2 in uptrend AND price enters neutral zone above ST1
- **Test Sell Zone**: Both ST1 & ST2 in downtrend AND price enters neutral zone below ST1
4. **Distance Lines from ST2**
- Upper/lower lines at customizable tick distance from ST2
- Purple dashed lines with touch alerts
**Trading Signals:**
- **Bullish Signal**: Price above ST2 but below ST1 (potential buy)
- **Bearish Signal**: Price below ST2 but above ST1 (potential sell)
- **Neutral Zone Alerts**: Price enters defined zone when both trends align
- **Line Touch Alerts**: Price touches distance lines from ST2
**Alert System:**
- Limited to 3 consecutive alerts per signal type
- Visual markers (triangles, diamonds, circles)
- Background coloring for signal zones
- Separate alert conditions for each signal type
**Visual Features:**
- Candles colored green/red based on signals
- Clear trend visualization with colored backgrounds
- Real-time alert markers without information table clutter
This indicator provides multi-timeframe trend analysis with precise entry zone detection and comprehensive alert system for XAUUSD trading. SAM89 M15, ST1 (5:10) M5, ST2 ( 1,5:20) H1, Test Buy Sell 7000, Line 15000
SuperTrend Cyan — Split ST & Triple Bands (A/B/C)SuperTrend Cyan — Split ST & Triple Bands (A/B/C)
✨ Concept:
The SuperTrend Cyan indicator expands the classical SuperTrend logic into a split-line + triple-band visualization for clearer structure and volatility mapping.
Instead of a single ATR-based line, this tool separates SuperTrend direction from volatility envelopes (A/B/C), providing a layered view of both regime and range compression.
✨ The design goal:
Preserve the simplicity of SuperTrend
Add volatility context via multi-band envelopes
Provide a compact MTF (Multi-Timeframe) summary for broader trend alignment
✨ How It Works
1. SuperTrend Core (Active & Opposite Lines)
Uses ATR-based bands (Factor × ATR-Length).
Active SuperTrend is plotted according to current regime.
Opposite SuperTrend (optional) shows potential reversal threshold.
2. Triple Band System (A/B/C)
Each band (A, B, C) scales from the median price (hl2) by different ATR multipliers.
A: Outer band (wider, long-range context)
B: Inner band (mid-range activity)
C: Core band (closest to price, short-term compression)
Smoothness can be controlled with EMA.
Uptrend fills are lime-toned, downtrend fills are red-toned, with adjustable opacity (gap intensity).
3. Automatic Directional Switch
When the regime flips from up → down (or vice versa), the overlay automatically switches between lower and upper bands for a clean transition.
4. Multi-Timeframe SuperTrend Table
Displays SuperTrend direction across 5m, 15m, 1h, 4h, and 1D frames.
Green ▲ = Uptrend, Red ▼ = Downtrend.
Useful for checking cross-timeframe trend alignment.
✨ How to Read It
Green SuperTrend + Lime Bands
- Uptrend regime; volatility expanding upward
Red SuperTrend + Red Bands
- Downtrend regime; volatility expanding downward
Narrow gaps (A–C)
- Low volatility / compression (potential squeeze)
Wide gaps
- High volatility / active trend phase
Opposite ST line close to price
- Early warning for regime transition
✨ Practical Use
Identify trend direction (SuperTrend color & line position).
Assess volatility conditions (band width and gap transparency).
Watch for MTF alignment: consistent up/down signals across 1h–4h–1D = strong structural trend.
Combine with momentum indicators (e.g., RSI, DFI, PCI) for confirmation of trend maturity or exhaustion.
✨ Customization Tips
ST Factor / ATR Length
- Adjust sensitivity of SuperTrend direction changes
Band ATR Length
- Controls overall smoothness of volatility envelopes
Band Multipliers (A/B/C)
- Define how wide each volatility band extends
Gap Opacity
- Affects visual contrast between layers
MTF Table
- Enable/disable multi-timeframe display
✨ Educational Value
This script visualizes the interaction between trend direction (SuperTrend) and volatility envelopes, helping traders understand how price reacts within layered ATR zones.
It also introduces a clean MTF (multi-timeframe) perspective — ideal for discretionary and system traders alike.
✨ Disclaimer
This indicator is provided for educational and research purposes only.
It does not constitute financial advice or a trading signal.
Use at your own discretion and always confirm with additional tools.
───────────────────────────────
📘 한국어 설명 (Korean translation below)
───────────────────────────────
✨개념
SuperTrend Cyan 지표는 기존의 SuperTrend를 확장하여,
추세선 분리(Split Line) + 3중 밴드 시스템(Triple Bands) 으로
시장의 구조적 흐름과 변동성 범위를 동시에 시각화합니다.
단순한 SuperTrend의 강점을 유지하면서도,
ATR 기반의 A/B/C 밴드를 통해 변동성 압축·확장 구간을 직관적으로 파악할 수 있습니다.
✨ 작동 방식
1. SuperTrend 코어 (활성/반대 라인)
ATR×Factor를 기반으로 추세선을 계산합니다.
현재 추세 방향에 따라 활성 라인이 표시되고, “Show Opposite” 옵션을 켜면 반대편 경계선도 함께 보입니다.
2. 트리플 밴드 시스템 (A/B/C)
hl2(중간값)를 기준으로 ATR 배수에 따라 세 개의 밴드를 계산합니다.
A: 외곽 밴드 (가장 넓고 장기 구조 반영)
B: 중간 밴드 (중기적 움직임)
C: 코어 밴드 (가격에 가장 근접, 단기 변동성 반영)
EMA 스무딩으로 부드럽게 조정 가능.
업트렌드 구간은 라임색, 다운트렌드는 빨간색 음영으로 표시됩니다.
3. 자동 전환 시스템
추세가 전환될 때(Up ↔ Down), 밴드 오버레이도 자동으로 교체되어 깔끔한 시각적 구조를 유지합니다.
4. MTF SuperTrend 테이블
5m / 15m / 1h / 4h / 1D 프레임별 SuperTrend 방향을 표시합니다.
초록 ▲ = 상승, 빨강 ▼ = 하락.
복수 타임프레임 정렬 확인용으로 유용합니다.
✨ 해석 방법
초록 SuperTrend + 라임 밴드
- 상승 추세 및 확장 구간
빨강 SuperTrend + 레드 밴드
- 하락 추세 및 확장 구간
밴드 폭이 좁음
- 변동성 축소 (스퀴즈)
밴드 폭이 넓음
- 변동성 확장, 추세 강화
반대선이 근접
- 추세 전환 가능성 높음
✨ 활용 방법
SuperTrend 색상으로 추세 방향을 확인
A/B/C 밴드 폭으로 변동성 수준을 판단
MTF 테이블을 통해 복수 타임프레임 정렬 여부 확인
RSI, DFI, PCI 등 다른 지표와 함께 활용 시, 추세 피로·모멘텀 변화를 조기에 파악 가능
✨ 교육적 가치
이 스크립트는 추세 구조(SuperTrend) 와 변동성 레이어(ATR Bands) 의 상호작용을
시각적으로 학습하기 위한 교육용 지표입니다.
또한, MTF 구조를 통해 시장의 “위계적 정렬(hierarchical alignment)”을 쉽게 인식할 수 있습니다.
✨ 면책
이 지표는 교육 및 연구 목적으로만 제공됩니다.
투자 판단의 책임은 사용자 본인에게 있으며, 본 지표는 매매 신호를 보장하지 않습니다.
Directional Flow Index (DFI) — v2.4Directional Flow Index (DFI) — v2.4
✨ 1) What DFI measures (conceptual)
DFI aims to quantify directional flow —i.e., whether trading activity is skewed toward buying (supportive pressure) or selling (resistive pressure) —and then present it as a normalized oscillator that is easy to compare across symbols and timeframes. It is designed to highlight high-confidence thrusts within a prevailing trend and to detect fatigue as momentum decays.
Positive DFI (> 0) : net buy-side pressure dominates.
Negative DFI (< 0) : net sell-side pressure dominates.
Magnitude reflects intensity after de-trending and Z-score normalization.
While multiple “flow” proxies exist, this version emphasizes a True Volume Delta (TVD) workflow (default) that tallies buy vs. sell volume from a lower timeframe (LTF) inside an anchor timeframe bar, producing a more realistic per-bar delta when supported by the symbol’s data.
✨ 2) Core pipeline (how it works)
Flow construction (TVD default).
Using ta.requestVolumeDelta(LTF, Anchor), the script approximates up-volume vs. down-volume inside each anchor bar.
A per-bar delta is derived (with a reset on anchor switches to avoid jumps).
If TVD is unsupported on the symbol, DFI can fall back to synthetic proxies (e.g., Synthetic Delta Volume: (close-low)/(high-low) × vol), but TVD is the intended default.
CVD-style accumulation.
Per-bar delta is cumulatively summed into a running flow line (CVD-like), providing temporal context to the net pressure.
High-pass de-trending + smoothing.
A high-pass step (EMA-based) removes slow drifts (trend bias) from the CVD line.
A short EMA smoothing reduces noise while preserving thrust.
Z-score normalization.
The de-trended series is standardized (rolling mean/std), so DFI readings are comparable across markets/timeframes.
The Signal line is an EMA of DFI and is used for momentum cross checks.
SuperTrend (regime filter).
A lightweight SuperTrend (ATR len=5, factor=6 by default) provides up/down regime.
DFI coloring and alerts can be conditioned on the regime (optional).
Fatigue % (0–100).
Tracks energy (EMA of |DFI|) vs. peak energy (with adaptive half-life decay).
When energy stays far below the decaying peak, Fatigue% rises, suggesting momentum exhaustion.
The decay rate adapts to DFI volatility and regime alignment, so decay is faster when thrusts are misaligned with trend, slower when aligned and orderly.
Gradient highlight (confidence shading).
Histogram color transparency blends three ingredients:
DFI strength (|DFI| vs user-set bands)
Low fatigue (fresher thrusts score higher)
Regime alignment (DFI sign vs SuperTrend direction)
Result: darker bars indicate higher confidence in thrust quality; faint bars warn of weaker, stale, or misaligned pushes.
✨ 3) Interpreting the plots
DFI histogram (columns):
Green above zero for buy-side thrust, Red below zero for sell-side thrust.
Opacity encodes confidence (darker = stronger alignment & lower fatigue).
Signal (line): EMA of DFI used for momentum regime checks.
Zero line: structural reference for thrust crossovers.
Fatigue Table (optional): shows Fatigue%, SuperTrend regime, and selected Flow Method.
✨ 4) Alerts (examples)
Long Thrust: DFI crosses above zero while in Up regime.
Short Thrust: DFI crosses below zero while in Down regime.
Loss of Momentum (Up): DFI crosses below Signal while DFI > 0 (warns of weakening long thrust).
Loss of Momentum (Down): DFI crosses above Signal while DFI < 0 (warns of weakening short thrust).
✨ 5) How to set the TVD Lower TF (important)
TVD needs a sensible LTF/Anchor ratio for balanced accuracy and performance. As a rule of thumb, aim for ~30–120 LTF bars inside one anchor bar:
1h chart → 1–2m LTF (if seconds not available).
4h → 3–5m.
1D → 15–30m.
1W → 1–2h.
1M → 4h–1D.
Notes: Some symbols/exchanges do not provide seconds. Too small an LTF can be heavy/noisy; too large becomes coarse/laggy.
✨ 6) Practical usage patterns
Trend-following entries:
Look for DFI > 0 in Up regime (green) with low Fatigue%, and DFI crossing above zero or above its Signal.
Prefer darker (higher-confidence) histogram bars.
Trend-following exits / de-risking:
Rising Fatigue% toward your high threshold (e.g., 80–90) suggests exhaustion.
DFI vs Signal crosses against your position can be used to scale down.
Avoid chop:
When DFI oscillates around zero with faint bars and Fatigue% rises quickly, quality is low—be selective.
✨ 7) Inputs (summary)
Flow Method: default True Volume Delta (LTF scan); synthetic fallbacks available.
Processing: Detrend length, smoothing EMA, Z-score window, Signal EMA.
Regime: SuperTrend ATR length & factor (default 5 & 6).
Fatigue%: EMA length, base half-life, adaptive volatility coupling (enable/disable, sensitivity).
UI Highlight: strength thresholds, fatigue cap, alignment weights, opacity range.
Table: toggle Fatigue table, decimals, position.
✨ 8) Compatibility & performance notes
TVD requires supported data for the symbol; if unavailable, DFI can switch to synthetic deltas.
Smaller LTFs increase request load and may introduce noise; prefer a balanced ratio.
The indicator is designed to be self-contained; no other overlays are needed to read the outputs.
✨ 9) Limitations and good practice
This is an oscillator, not a price predictor. Extreme values can persist in strong trends.
Normalization (Z-score) makes values comparable, but distributions differ across assets/timeframes.
Always combine with risk management and position sizing; avoid interpreting any single condition as a guarantee.
✨ 10) Disclaimer
This script is for educational purposes only and does not constitute financial advice. Trading involves risk, including possible loss of principal.
---------------------------------------------------------------------------------------------------------------------
한국어 번역 / Korean version below
✨DFI란 무엇인가?
DFI는 시장의 매수·매도 우위를 Flow(흐름) 형태로 분석하여
그 에너지를 정규화된 오실레이터로 표현하는 지표입니다.
가격의 단순 변동이 아니라, “얼마나 일관성 있는 압력(Flow)이 유지되는가”를 보여줍니다.
DFI > 0: 매수세 우위 (상방 압력)
DFI < 0: 매도세 우위 (하방 압력)
값의 크기: 모멘텀의 강도 (Z-score 기반 정규화)
기본 방식인 True Volume Delta (TVD) 는 상위 봉(Anchor) 내부의 하위 타임프레임(LTF) 데이터를 스캔해
실제 매수/매도 체결량 차이를 계산합니다.
이로써 단순 가격 변화가 아닌 실제 체결 흐름의 방향성을 반영합니다.
✨DFI의 계산 과정 (개념적 흐름)
1. Flow 계산 (TVD 또는 대체 방식)
ta.requestVolumeDelta()를 사용하여 상·하위 TF간 볼륨 델타를 계산합니다.
TVD 미지원 심볼은 자동으로 Synthetic Delta Volume 등 대체 방식으로 전환됩니다.
2. 누적(CVD) 구성
Flow를 CVD처럼 누적하여 순매수/순매도 압력을 누적 추적합니다.
3. 고역통과(High-pass) 필터
누적 흐름(CVD)에서 장기 추세 성분을 제거하여 순수한 변동 에너지만 남깁니다.
4. Z-score 정규화
평균과 표준편차로 표준화해 DFI의 크기를 **일정한 스케일(0 중심)**로 만듭니다.
다른 종목·시간대 간 비교가 용이합니다.
5. SuperTrend 레짐(추세 상태) 인식
ATR 기반 ST(기본: Length=5, Factor=6)를 통해 시장이 상승/하락/중립 중 어디에 있는지를 감지합니다.
DFI 컬럼 색상 및 알림은 이 ST 방향에 따라 동작합니다
6. Fatigue% (피로도 지수)
최근 에너지 평균과 역사적 피크(감쇠)를 비교해 0~100%로 “신선도”를 표현합니다.
높을수록 피로한 상태, 낮을수록 신선한 추세.
또한 변동성과 정렬 여부에 따라 Adaptive Half-Life로 감쇠 속도가 자동 조정됩니다.
7. 그라디언트 하이라이트 (Gradient Highlight)
DFI 강도(|DFI|), Fatigue%, 레짐 정렬 상태를 종합해 히스토그램의 투명도를 연속적으로 변화시킵니다.
강하고 신선하며 정렬된 추세일수록 더 진하게 표시, 반대로 약하거나 피로한 구간은 흐리게 표시됩니다.
✨DFI 차트 해석법
DFI 히스토그램 (컬럼):
위로 향한 초록색 = 매수 우위,
아래로 향한 빨강색 = 매도 우위.
진할수록 “신뢰도 높은 흐름(Aligned + Low Fatigue)”
흐릴수록 “노이즈성 움직임 / 피로 구간”
Signal 선:
DFI의 EMA.
DFI와의 교차는 모멘텀 전환 신호로 사용.
Zero 선:
추세 전환의 기준선.
Fatigue Table:
Fatigue%, Regime, Flow Method 정보를 실시간 표시.
✨알림 조건 (Alerts)
DFI Long Thrust: 상승 레짐에서 DFI가 0 위로 돌파.
DFI Short Thrust: 하락 레짐에서 DFI가 0 아래로 돌파.
Loss of Momentum (Up): DFI>0 상태에서 Signal 아래로 하락.
Loss of Momentum (Down): DFI<0 상태에서 Signal 위로 상승.
TVD (True Volume Delta) 설정 가이드
TVD는 Anchor:LowerTF = 약 30~120배 비율이 가장 효율적입니다.
1시간봉 -> 30초~2분
4시간봉 -> 2~8분
일봉(1D) -> 12~48분
주봉(1W) -> 1~4시간
월봉(1M) -> 4시간~ 1일
참고:
일부 거래소는 초 단위를 지원하지 않습니다 → 분 단위로 대체.
너무 짧은 LTF → 과부하/노이즈,
너무 긴 LTF → 신호 지연/정밀도 저하.
✨활용 전략 예시
추세 추종 (Trend-following):
Up Regime에서 DFI>0 & Fatigue% 낮을 때 롱 신호 우선.
DFI가 Signal 위로 돌파하는 시점이 thrust 시작점.
리스크 축소 (De-risking):
Fatigue%가 80~90 이상이면 추세 과열로 간주.
DFI가 Signal을 역방향으로 교차 시 포지션 축소 고려.
횡보 회피:
DFI가 0선 부근에서 얕게 진동하며 흐릿하게 표시될 때는
방향성이 약한 구간 → 진입 회피.
✨한계 및 권장 사용법
TVD는 심볼/거래소의 지원 여부에 따라 제한될 수 있습니다.
Z-score 정규화로 수치 간 비교는 용이하지만, 자산마다 분포 특성이 달라 절대값 해석은 주의 필요.
Fatigue%는 “모멘텀 신선도” 개념이지, 반전 타이밍이 아닙니다.
리스크 관리 및 전략적 컨텍스트 안에서 사용하세요.
✨면책 (Disclaimer)
이 스크립트는 교육용 도구(Educational purpose)이며,
투자 조언(Financial advice)이 아닙니다.
모든 트레이딩에는 손실의 위험이 있으며,
DFI의 신호나 수치가 수익을 보장하지 않습니다.
✨정리
DFI는 단순한 “추세 오실레이터”가 아니라,
에너지의 흐름 + 피로도 + 레짐 정렬이라는 3요소를 결합해
“지속 가능한 방향성”을 시각적으로 표현하는 지표입니다.
즉, 단순한 ‘방향’이 아니라 “추세의 질(Quality)”을 보여주는
새로운 형태의 Flow 분석 도구입니다.
[INVX] Trading Range
Trading Range
The “ Trading Range” indicator visualizes short-term price ranges (typically 1–2 days) based on statistical percentiles of high and low prices relative to the previous day’s close. It provides a clear view of potential support and resistance zones and includes optional EMA overlays for trend context.
Concept & Calculation
Uses the previous daily close as a reference point.
Calculates percentile-based levels for highs and lows over a configurable lookback period.
Plots two resistance zones and two support zones as shaded areas.
Includes up to 3 optional EMA lines for trend visualization.
Trading range zones are designed for daily-based calculations. If the indicator is applied to a chart timeframe larger than 1 day (e.g., weekly, monthly), the trading range zones will not be displayed.
Key Features
Short-Term Trading Range:
Displays zones that reflect short-term price behavior (1–2 days).
Percentile-Based Levels:
Levels are calculated using percentile interpolation for highs and lows.
Historical Lines Option:
Toggle to show past levels for context.
Realtime Calculation update:
Update calculations dynamically with the current bar.
EMA Overlay:
Up to three customizable EMA lines for trend analysis.
Display Line Values:
Option to show level values on the chart with adjustable label size.
Trading Range Settings
Historical Lines: Show or hide past support/resistance levels.
Realtime Calculation: Enable or disable real-time updates.
Display Line Values: Show numeric values for levels.
Size: Adjust label size when values are displayed.
EMA Line Settings
Enable/disable each EMA line.
Configure length and color for each EMA.
Usage Tips
Use the shaded zones as visual reference areas for short-term price interaction.
Combine with other tools such as trend indicators or volume analysis to strengthen the analysis.
Historical lines can help assess how price has reacted to these zones in the past.
Limitations & Disclaimer
This indicator is provided for informational purposes only. It does not constitute financial advice or a recommendation to buy or sell any asset.
Market conditions, asset volatility, and timeframe selection may significantly affect indicator performance.
Users should always validate signals with additional analysis and apply appropriate risk management strategies.
Past performance is not indicative of future results. Use indicator at your own discretion and risk.
Under no circumstances shall InnovestX be liable for any loss or damage you or anyone else incur as a result of any trading or investment activity that you or anyone else engages in based on any information or material you receive through InnovestX or TradingView.






















