Trendlines Oscillator [LuxAlgo]The Trendlines Oscillator helps traders identify trends and momentum based on the normalized distances between the current price and the most recently detected bullish and bearish trend lines.
The indicator features bullish and bearish momentum, a signal line with crossings, and multiple smoothing options.
🔶 USAGE
The indicator displays three lines: two for momentum and one for the signal. When one of the momentum lines (bullish or bearish) crosses the signal line, the tool displays a dot to indicate which momentum is gaining strength.
As a general rule, when the green bullish momentum line is above the red bearish momentum line, it indicates buyer strength. This means that the actual prices are farther from the support trend lines than the resistance trend lines. The opposite is true for seller strength.
To calculate bullish momentum, the tool first identifies bullish trend lines acting as support below the price. Then, it measures the delta between the price and those trend lines and normalizes the reading into the displayed momentum values.
The same process is used for bearish momentum, but with bearish trendlines acting as resistance above the price.
🔹 Length & Memory
Modifying the Length and Memory values will cause the tool to display different momentum values.
Traders can adjust the length to detect larger trendlines and adjust the memory to indicate how many trendlines the tool should consider.
As the chart above shows, smaller values make the tool more responsive, while larger values are useful for detecting larger trends.
🔹 Smoothing
By default, the data is not smoothed, and the signal uses a triangular moving average with a length of 10. Traders can smooth both the data and the signal line.
Traders can choose from up to ten different methods, or none. Some examples are shown on the chart above.
🔶 DETAILS
The steps for the calculations are as follows:
1. Gather the pivots, highs, and lows.
ph = fixnan(ta.pivothigh(lengthInput, lengthInput))
pl = fixnan(ta.pivotlow(lengthInput, lengthInput))
2. Calculate the slope and y-intercept for each trendline between contiguous lower highs (resistance) or higher lows (support).
if ph < ph
slope = (ph - ph )/(n-lengthInput - phx1)
res.unshift(l.new(ph - slope * phx1, slope))
if pl > pl
slope = (pl - pl )/(n-lengthInput - plx1)
sup.unshift(l.new(pl - slope * plx1, slope))
3. Calculate the value of each trendline on the current bar, then calculate the difference with the current price (delta). To calculate the relative sum of deltas, only consider trendlines below the price for support or above the price for resistance.
method get_point(l id, x)=>
id.slope * x + id.intercept
for element in sup
point = element.get_point(n)
if sourceInput > point
sup_sum += sourceInput - point
sup_den += math.abs(sourceInput - point)
for element in res
point = element.get_point(n)
if sourceInput < point
res_sum += point - sourceInput
res_den += math.abs(point - sourceInput)
4. Normalize the value from 0 to 100 by taking the sum of the relative values of the deltas divided by the sum of the absolute values of the deltas.
float supportLine = sup_sum / sup_den * 100
float resistanceLine = res_sum / res_den * 100
5. Smooth both values, then calculate the signal line as the difference between them.
float smoothSupport = smooth(supportLine,dataSmoothingInput,dataSmoothingLengthInput)
float smoothResistance = smooth(resistanceLine,dataSmoothingInput,dataSmoothingLengthInput)
float signal = math.abs(smoothSupport - smoothResistance)
float signalLine = smooth(signal,smoothingInput,smoothingLengthInput)
6. Calculate the crossing signals against the signal line, using only the first signal from each series of bullish or bearish crossings.
bullSignal = smoothSupport > signalLine and smoothSupport < signalLine
bearSignal = smoothResistance > signalLine and smoothResistance < signalLine
lastSignal := bullSignal and lastSignal == BEAR ? BULL : bearSignal and lastSignal == BULL ? BEAR : lastSignal
firstBull = ta.change(lastSignal) > 0
firstBear = ta.change(lastSignal) < 0
🔶 SETTINGS
Length: The size of the market structure used for trendline detection.
Memory: The number of trendlines used in calculations.
Source: The source for the calculations is closing prices by default.
🔹 Smoothing
Data Smoothing: Choose the smoothing method and length
Signal Smoothing: Choose the smoothing method and length
Cerca negli script per "bear"
Tide Tracker ZonesTide Tracker Zones – Advanced Trend & Pullback Visualizer
Overview
Tide Tracker Zones is a sophisticated trading tool designed for traders who require clarity, precision, and actionable insights in real time. The indicator converts price action into dynamic trend zones, allowing users to instantly recognize market direction, potential reversals, and low-risk entry opportunities. By visualizing the market in this way, traders can focus on execution rather than deciphering complex charts.
Unlike static indicators, Tide Tracker Zones adapts to market volatility, providing a clear picture of bullish and bearish pressure across multiple timeframes. Its visual design, including color-coded trend zones, a prominent guide line, and carefully placed signals, ensures that market behavior is easy to interpret, making it suitable for scalping, swing trading, and longer-term strategies alike.
How It Works
The indicator relies on dynamic upper and lower bands derived from recent price ranges and a configurable multiplier. These bands expand during volatile periods and contract when price action stabilizes, creating flexible zones that reflect the dominant market tide.
A guide line tracks the active band, serving as a continuous reference for trend direction. Unlike traditional moving averages, the guide line does not clutter the chart but instead provides a subtle, intuitive indication of whether the market is in a bullish or bearish phase. Background shading reinforces this trend visually, highlighting bullish zones in one color and bearish zones in another, so the prevailing market flow is immediately clear.
The system continuously evaluates price relative to the bands to determine trend direction and detect potential reversals. When price crosses a band and flips the trend, the guide line updates, and signals are generated, providing traders with actionable information without overwhelming the chart.
Signals and Pullbacks
Tide Tracker Zones offers visual cues that make entry points more obvious and less speculative. Trend reversal arrows are plotted when the market changes direction: BUY arrows indicate a shift from bearish to bullish, and SELL arrows indicate a shift from bullish to bearish.
The indicator also highlights first pullbacks within an active trend. These pullback dots mark low-risk opportunities to enter a trend in progress, filtered to ensure that only the most relevant signals are displayed. The system uses ATR-based spacing to place arrows and dots vertically on the chart, preventing visual clutter and ensuring readability even during periods of high volatility.
Color-coded zones enhance situational awareness. Bullish zones are displayed in a customizable orange, while bearish zones are shown in green. Transparency is dynamically adjusted to maintain chart clarity while still providing a clear indication of trend strength.
Strategy Integration
Tide Tracker Zones can be used effectively for both trend-following and pullback strategies. Traders may enter positions in the direction of the guide line and colored zone, using trend reversal arrows for confirmation. First pullback dots offer tactical entries with reduced risk, allowing traders to enter a trend after a brief retracement.
Stop-loss levels can be placed just beyond the opposing trend zone, while take-profit targets may be determined using the width of the bands to account for market volatility. The indicator adapts seamlessly across multiple timeframes. Higher timeframes provide context and filter noise, while lower timeframes allow traders to refine entry timing. This makes it a versatile tool for scalping, swing trading, or longer-term positions.
Advanced Techniques
For traders seeking greater precision, Tide Tracker Zones can be combined with volume or momentum indicators to validate signals. Observing the sequence of trend arrows and pullback dots allows users to develop a systematic approach to entries and exits. Monitoring the width and behavior of the bands over time can also provide insights into periods of expanding or contracting volatility, helping traders anticipate market shifts.
Adjustments to the spread length and multiplier allow the indicator to be tuned for different assets and market conditions. By understanding the interaction between the guide line, trend zones, and pullback signals, traders can create a robust framework for decision-making, reducing guesswork and improving consistency.
Why Use Tide Tracker Zones
Tide Tracker Zones provides instant clarity and actionable insight in any market. Its dynamic zones and guide line give a clear visual understanding of trend direction, while trend reversal arrows and pullback dots highlight potential entry points. Unlike traditional indicators, it adapts to volatility and changing conditions, making it reliable across multiple asset classes and timeframes.
By combining trend detection, pullback analysis, and intuitive visual guidance, Tide Tracker Zones equips traders with a complete framework for disciplined, confident trading, transforming complex price action into a visual map of opportunity.
SmartPlusSmartPlus
Overview
The SmartPlus indicator is a complete framework for intraday traders. It combines key market reference points (VWAP, moving averages, and the first 15-minute high/low range) with predictive levels based on historical daily moves. Together, these elements allow traders to build directional bias, spot breakouts, and manage risk throughout the session.
Key Features
1. VWAP (Volume-Weighted Average Price)
- Plots the intraday VWAP in real time.
- VWAP acts as a central “fair value” reference point for institutional order flow.
- Price trading above VWAP generally suggests bullish bias, while below VWAP leans bearish.
2. Exponential Moving Averages (EMAs)
- Two configurable EMAs are included:
- Fast EMA (default: 21 periods)
- Slow EMA (default: 34 periods)
- Each EMA is plotted with a single, user-selectable color for clarity.
- Crossovers or alignment between price, VWAP, and EMAs help define market structure.
3. Smart Bar Coloring
- Candles automatically change color when conditions align:
- Bull Zone: Price above VWAP, Fast EMA, and Slow EMA.
- Bear Zone: Price below VWAP, Fast EMA, and Slow EMA.
- Fluorescent bar coloring helps highlight momentum zones visually without additional analysis.
4. First 15-Minute High/Low/Mid (Automatic)
- Automatically detects the first 15 minutes of each new trading day (no manual input required).
- Plots horizontal lines for:
- First 15-Minute High (green)
- First 15-Minute Low (red)
- Midpoint of that range (gray)
- Once the initial 15-minute window ends, these levels remain projected throughout the session as breakout or support/resistance zones.
- Alerts trigger when price breaks above the high or below the low after the window.
5. Daily Support/Resistance Forecast
- Uses a rolling lookback of recent daily ranges (default: 126 days).
- Tracks average up moves and down moves from the daily open.
- Optionally incorporates standard deviation for wider confidence bands.
- Plots forecast levels above/below the current day’s open for reference.
Trading Logic (How to Use)
- Bullish Bias:
- Price is above VWAP, above both EMAs, and ideally above the first 15-minute high.
- This setup suggests trend continuation or breakout opportunities on the long side.
- Bearish Bias:
- Price is below VWAP, below both EMAs, and ideally below the first 15-minute low.
- This setup suggests downward pressure or breakout opportunities on the short side.
- Neutral / Caution Zone:
- Price caught between VWAP, EMAs, or inside the 15-minute range often signals indecision.
- Best to wait for confirmation or breakout before committing to trades.
Expectations After Using It
- The script provides context and structure, not trading signals.
- It highlights where price is relative to meaningful market levels so traders can act with greater confidence.
- Combining VWAP, EMAs, and the 15-minute breakout framework helps traders stay aligned with the market’s natural rhythm.
Disclaimer
This script is a tool for market analysis and educational purposes only.
It does not constitute financial advice, trading recommendations, or guaranteed profitability.
Markets are inherently risky, and past patterns do not ensure future results.
Always combine this tool with sound risk management, personal research, and professional guidance before making any trading decisions.
Volatility Zones (VStop + Bands) — Fixed (v2)📝 What this indicator is
This script is called “Volatility Zones (VStop + Bands)”.
It is an ATR-based volatility indicator that combines dynamic volatility bands, a Volatility Stop line (VStop), and volatility spike detection into a single tool.
Unlike moving average–based indicators, this tool does not rely on averages of price direction. Instead, it measures the market’s true volatility and reacts to expansions or contractions in price ranges.
________________________________________
⚙️ How it is built
The indicator uses several volatility-based components:
1. Average True Range (ATR)
o ATR is calculated over a user-defined length.
o It measures how much price typically moves in a given number of bars, making it the foundation of this indicator.
2. Volatility Bands
o Upper band = close + ATR × factor
o Lower band = close - ATR × factor
o The area between them is shaded.
o This gives traders an immediate visual sense of market volatility width — wide bands = high volatility, narrow bands = quiet market.
3. Volatility Stop (VStop)
o A stateful trailing stop based on ATR.
o It tracks the highest (or lowest) price in the current trend and places a stop offset by ATR × multiplier.
o When price crosses this stop, the indicator flips trend direction.
o This creates a dynamic stop-and-reverse mechanism that adapts to volatility.
4. Trend Zones
o When the trend is bullish, the stop is green and the chart background is shaded softly green.
o When bearish, the stop is red and the background is shaded softly red.
o This makes the market’s directional bias visually clear at all times.
5. Flip Signals (Buy/Sell Arrows)
o Whenever the VStop flips, arrows appear:
Green BUY arrows below price when the trend turns bullish.
Red SELL arrows above price when the trend turns bearish.
o These are also tied to built-in alerts for automation.
6. Volatility Spike Detection
o The script compares current ATR to its recent average.
o If ATR suddenly expands above a threshold, a small yellow “VOL” marker appears at the top of the chart.
o This highlights potential breakout phases or unusual volatility events.
7. Stop Labels
o At every trend flip, a small label appears at the bar, showing the exact stop level.
o This makes it easy to use the stop as a reference for risk management.
________________________________________
📊 How it works in practice
• When price is above the VStop line, the market is considered in an uptrend.
• When price is below the VStop line, the market is in a downtrend.
• The bands expand/contract with volatility, helping traders gauge risk and position sizing.
• Flip arrows signal when trend direction changes.
• Volatility spikes warn traders that the market is entering a higher-risk phase, often before strong moves.
________________________________________
🎯 How it may help traders
• Trend following → Helps traders identify whether the market is trending up or down.
• Stop placement → Provides a dynamic stop level that adjusts to volatility.
• Volatility awareness → Shaded bands and spike markers show when the market is likely to become unstable.
• Trade timing → Flip arrows and labels help identify potential entry or exit points.
• Risk management → Wide bands indicate higher risk; narrow bands suggest safer, tighter ranges.
________________________________________
🌍 In what markets it is useful
Because the indicator is based purely on volatility, it works across all asset classes and timeframes:
• Stocks & ETFs → Helps identify breakouts and long-term trends.
• Forex → Very useful in spot FX where volatility shifts frequently.
• Crypto → ATR reacts strongly to high volatility, helping traders adapt stops dynamically.
• Futures & Commodities → Great for tracking trending commodities and managing risk.
Scalpers, swing traders, and position traders can all benefit by adjusting the ATR length and multipliers to suit their trading style.
________________________________________
💡 Originality of this script
This is not just a mashup of existing indicators. It integrates:
• ATR-based Volatility Bands for context,
• A stateful Volatility Stop (adapted and rewritten cleanly),
• Flip arrows and labels for actionable trading signals,
• Volatility spike detection to highlight regime shifts.
The result is a comprehensive volatility-aware trading tool that goes beyond just plotting ATR or trend stops.
________________________________________
🔔 Alerts
• Buy Flip → triggers when the trend changes bullish.
• Sell Flip → triggers when the trend changes bearish.
Traders can connect these alerts to automated strategies, bots, or notification systems.
Volume Profile Grid [Alpha Extract]A sophisticated volume distribution analysis system that transforms market activity into institutional-grade visual profiles, revealing hidden support/resistance zones and market participant behavior. Utilizing advanced price level segmentation, bullish/bearish volume separation, and dynamic range analysis, the Volume Profile Grid delivers comprehensive market structure insights with Point of Control (POC) identification, Value Area boundaries, and volume delta analysis. The system features intelligent visualization modes, real-time sentiment analysis, and flexible range selection to provide traders with clear, actionable volume-based market context.
🔶 Dynamic Range Analysis Engine
Implements dual-mode range selection with visible chart analysis and fixed period lookback, automatically adjusting to current market view or analyzing specified historical periods. The system intelligently calculates optimal bar counts while maintaining performance through configurable maximum limits, ensuring responsive profile generation across all timeframes with institutional-grade precision.
// Dynamic period calculation with intelligent caching
get_analysis_period() =>
if i_use_visible_range
chart_start_time = chart.left_visible_bar_time
current_time = last_bar_time
time_span = current_time - chart_start_time
tf_seconds = timeframe.in_seconds()
estimated_bars = time_span / (tf_seconds * 1000)
range_bars = math.floor(estimated_bars)
final_bars = math.min(range_bars, i_max_visible_bars)
math.max(final_bars, 50) // Minimum threshold
else
math.max(i_periods, 50)
🔶 Advanced Bull/Bear Volume Separation
Employs sophisticated candle classification algorithms to separate bullish and bearish volume at each price level, with weighted distribution based on bar intersection ratios. The system analyzes open/close relationships to determine volume direction, applying proportional allocation for doji patterns and ensuring accurate representation of buying versus selling pressure across the entire price spectrum.
🔶 Multi-Mode Volume Visualization
Features three distinct display modes for bull/bear volume representation: Split mode creates mirrored profiles from a central axis, Side by Side mode displays sequential bull/bear segments, and Stacked mode separates volumes vertically. Each mode offers unique insights into market participant behavior with customizable width, thickness, and color parameters for optimal visual clarity.
// Bull/Bear volume calculation with weighted distribution
for bar_offset = 0 to actual_periods - 1
bar_high = high
bar_low = low
bar_volume = volume
// Calculate intersection weight
weight = math.min(bar_high, next_level) - math.max(bar_low, current_level)
weight := weight / (bar_high - bar_low)
weighted_volume = bar_volume * weight
// Classify volume direction
if bar_close > bar_open
level_bull_volume += weighted_volume
else if bar_close < bar_open
level_bear_volume += weighted_volume
else // Doji handling
level_bull_volume += weighted_volume * 0.5
level_bear_volume += weighted_volume * 0.5
🔶 Point of Control & Value Area Detection
Implements institutional-standard POC identification by locating the price level with maximum volume accumulation, providing critical support/resistance zones. The Value Area calculation uses sophisticated sorting algorithms to identify the price range containing 70% of trading volume, revealing the market's accepted value zone where institutional participants concentrate their activity.
🔶 Volume Delta Analysis System
Incorporates real-time volume delta calculation with configurable dominance thresholds to identify significant bull/bear imbalances. The system visually highlights price levels where buying or selling pressure exceeds threshold percentages, providing immediate insight into directional volume flow and potential reversal zones through color-coded delta indicators.
// Value Area calculation using 70% volume accumulation
total_volume_sum = array.sum(total_volumes)
target_volume = total_volume_sum * 0.70
// Sort volumes to find highest activity zones
for i = 0 to array.size(sorted_volumes) - 2
for j = i + 1 to array.size(sorted_volumes) - 1
if array.get(sorted_volumes, j) > array.get(sorted_volumes, i)
// Swap and track indices for value area boundaries
// Accumulate until 70% threshold reached
for i = 0 to array.size(sorted_indices) - 1
accumulated_volume += vol
array.push(va_levels, array.get(volume_levels, idx))
if accumulated_volume >= target_volume
break
❓How It Works
🔶 Weighted Volume Distribution
Implements proportional volume allocation based on the percentage of each bar that intersects with price levels. When a bar spans multiple levels, volume is distributed proportionally based on the intersection ratio, ensuring precise representation of trading activity across the entire price spectrum without double-counting or volume loss.
🔶 Real-Time Profile Generation
Profiles regenerate on each bar close when in visible range mode, automatically adapting to chart zoom and scroll actions. The system maintains optimal performance through intelligent caching mechanisms and selective line updates, ensuring smooth operation even with maximum resolution settings and extended analysis periods.
🔶 Market Sentiment Analysis
Features comprehensive volume analysis table displaying total volume metrics, bullish/bearish percentages, and overall market sentiment classification. The system calculates volume dominance ratios in real-time, providing immediate insight into whether buyers or sellers control the current price structure with percentage-based sentiment thresholds.
🔶 Visual Profile Mapping
Provides multi-layered visual feedback through colored volume bars, POC line highlighting, Value Area boundaries, and optional delta indicators. The system supports profile mirroring for alternative perspectives, line extension for future reference, and customizable label positioning with detailed price information at critical levels.
Why Choose Volume Profile Grid
The Volume Profile Grid represents the evolution of volume analysis tools, combining traditional volume profile concepts with modern visualization techniques and intelligent analysis algorithms. By integrating dynamic range selection, sophisticated bull/bear separation, and multi-mode visualization with POC/Value Area detection, it provides traders with institutional-quality market structure analysis that adapts to any trading style. The comprehensive delta analysis and sentiment monitoring system eliminates guesswork while the flexible visualization options ensure optimal clarity across all market conditions, making it an essential tool for traders seeking to understand true market dynamics through volume-based price discovery.
Chart-Only Scanner — Pro Table v2.5.1Chart-Only Scanner — Pro Table v2.5
User Manual (Pine Script v6)
What this tool does (in one line)
A compact, on-chart table that scores the current chart symbol (or an optional override) using momentum, volume, trend, volatility, and pattern checks—so you can quickly decide UP, DOWN, or WAIT.
Quick Start (90 seconds)
Add the indicator to any chart and timeframe (1m…1M).
Leave “Override chart symbol” = OFF to auto-use the chart’s symbol.
Choose your layout:
Row (wide horizontal strip), or Grid (title + labeled cells).
Pick a size preset (Micro, Small, Medium, Large, Mobile).
Optional: turn on “Use Higher TF (EMA 20/50)” and set HTF Multiplier (e.g., 4 ⇒ if chart is 15m, HTF is 60m).
Watch the table:
DIR (↑/↓/→), ROC%, MOM, VOL, EMA stack, HTF, REV, SCORE, ACT.
Add an alert if you want: the script fires when |SCORE| ≥ Action threshold.
What to expect
A small table appears on the chart corner you choose, updating each bar (or only at bar close if you keep default smart-update).
The ACT cell shows 🔥 (strong), 👀 (medium), or ⏳ (weak).
Panels & Settings (every option explained)
Core
Momentum Period: Lookback for rate-of-change (ROC%). Shorter = more reactive; longer = smoother.
ROC% Threshold: Minimum absolute ROC% to call direction UP (↑) or DOWN (↓); otherwise →.
Require Volume Confirmation: If ON and VOL ≤ 1.0, the SCORE is forced to 0 (prevents low-volume false positives).
Override chart symbol + Custom symbol: By default, the indicator uses the chart’s symbol. Turn this ON to lock to a specific ticker (e.g., a perpetual).
Higher TF
Use Higher TF (EMA 20/50): Compares EMA20 vs EMA50 on a higher timeframe.
HTF Multiplier: Higher TF = (chart TF × multiplier).
Example: on 3H chart with multiplier 2 ⇒ HTF = 6H.
Volatility & Oscillators
ATR Length: Used to show ATR% (ATR relative to price).
RSI Length: Standard RSI; colors: green ≤30 (oversold), red ≥70 (overbought).
Stoch %K Length: With %D = SMA(%K, 3).
MACD Fast/Slow/Signal: Standard MACD values; we display Line, Signal, Histogram (L/S/H).
ADX Length (Wilder): Wilder’s smoothing (internal derivation); also shows +DI / −DI if you enable the ADX column.
EMAs / Trend
EMA Fast/Mid/Slow: We compute EMA(20/50/200) by default (editable).
EMA Stack: Bull if Fast > Mid > Slow; Bear if Fast < Mid < Slow; Flat otherwise.
Benchmark (optional, OFF by default)
Show Relative Strength vs Benchmark: Displays RS% = ROC(symbol) − ROC(benchmark) over the Momentum Period.
Benchmark Symbol: Ticker used for comparison (e.g., BTCUSDT as a market proxy).
Columns (show/hide)
Toggle which fields appear in the table. Hiding unused fields keeps the layout clean (especially on mobile).
Display
Layout Mode:
Row = a single two-row strip; each column is a metric.
Grid = a title row plus labeled pairs (label/value) arranged in rows.
Size Preset: Micro, Small, Medium, Large, Mobile change text size and the grid density.
Table Corner: Where the panel sits (e.g., Top Right).
Opaque Table Background: ON = dark card; OFF = transparent(ish).
Update Every Bar: ON = update intra-bar; OFF = smart update (last bar / real-time / confirmed history).
Action threshold (|score|): The cutoff for 🔥 and alert firing (default 70).
How to read each field
CHART: The active symbol name (or your custom override).
DIR: ↑ (ROC% > threshold), ↓ (ROC% < −threshold), → otherwise.
ROC%: Rate of change over Momentum Period.
Formula: (Close − Close ) / Close × 100.
MOM: A scaled momentum score: min(100, |ROC%| × 10).
VOL: Volume ratio vs 20-bar SMA: Volume / SMA(Volume,20).
1.5 highlights as yellow (significant participation).
ATR%: (ATR / Close) × 100 (volatility relative to price).
RSI: Colored for extremes: ≤30 green, ≥70 red.
Stoch K/D: %K and %D numbers.
MACD L/S/H: Line, Signal, Histogram. Histogram color reflects sign (green > 0, red < 0).
ADX, +DI, −DI: Trend strength and directional components (Wilder). ADX ≥ 25 is highlighted.
EMA 20/50/200: Current EMA values (editable lengths).
STACK: Bull/Bear/Flat as defined above.
VWAP%: (Close − VWAP) / Close × 100 (premium/discount to VWAP).
HTF: ▲ if HTF EMA20 > EMA50; ▼ if <; · if flat/off.
RS%: Symbol’s ROC% − Benchmark ROC% (positive = outperforming).
REV (reversal):
🟢 Eng/Pin = bullish engulfing or bullish pin detected,
🔴 Eng/Pin = bearish engulfing or bearish pin,
· = none.
SCORE (absolute shown as a number; sign shown via DIR and ACT):
Components:
base = MOM × 0.4
volBonus = VOL > 1.5 ? 20 : VOL × 13.33
htfBonus = use_mtf ? (HTF == DIR ? 30 : HTF == 0 ? 15 : 0) : 0
trendBonus = (STACK == DIR) ? 10 : 0
macdBonus = 0 (placeholder for future versions)
scoreRaw = base + volBonus + htfBonus + trendBonus + macdBonus
SCORE = DIR ≥ 0 ? scoreRaw : −scoreRaw
If Require Volume Confirmation and VOL ≤ 1.0 ⇒ SCORE = 0.
ACT:
🔥 if |SCORE| ≥ threshold
👀 if 50 < |SCORE| < threshold
⏳ otherwise
Practical examples
Strong long (trend + participation)
DIR = ↑, ROC% = +3.2, MOM ≈ 32, VOL = 1.9, STACK = Bull, HTF = ▲, REV = 🟢
SCORE: base(12.8) + volBonus(20) + htfBonus(30) + trend(10) ≈ 73 → ACT = 🔥
Action idea: look for longs on pullbacks; confirm risk with ATR%.
Weak long (no volume)
DIR = ↑, ROC% = +1.0, but VOL = 0.8 and Require Volume Confirmation = ON
SCORE forced to 0 → ACT = ⏳
Action: wait for volume > 1.0 or turn off confirmation knowingly.
Bearish reversal warning
DIR = →, REV = 🔴 (bearish engulfing), RSI = 68, HTF = ▼
SCORE may be mid-range; ACT = 👀
Action: watch for breakdown and rising VOL.
Alerts (how to use)
The script calls alert() whenever |SCORE| ≥ Action threshold.
To receive pop-ups, sounds, or emails: click “⏰ Alerts” in TradingView, choose this indicator, and pick “Any alert() function call.”
The alert message includes: symbol, |SCORE|, DIR.
Layout, Size, and Corner tips
Row is best when you want a compact status ribbon across the top.
Grid is clearer on big screens or when you enable many columns.
Size:
Mobile = one pair per row (tall, readable)
Micro/Small = dense; good for many fields
Large = presentation/screenshots
Corner: If the table overlaps price, change the corner or set Opaque Background = OFF.
Repaint & timeframe behavior
Default smart update prefers stability (last bar / live / confirmed history).
For a stricter, “close-only” behavior (less repaint): turn Update Every Bar = OFF and avoid Heikin Ashi when you want raw market OHLC (HA modifies price inputs).
HTF logic is derived from a clean, integer multiple of your chart timeframe (via multiplier). It works with 3H/4H and any TF.
Performance notes
The script analyzes one symbol (chart or override) with multiple metrics using efficient tuple requests.
If you later want a multi-symbol grid, do it with pages (10–15 per page + rotate) to stay within platform limits (recommended future add-on).
Troubleshooting
No table visible
Ensure the indicator is added and not hidden.
Try toggling Opaque Background or switch Corner (it might be behind other drawings).
Keep Columns count reasonable for the chosen Size.
If you turned ON Override, verify the Custom symbol exists on your data provider.
Numbers look different on HA candles
Heikin Ashi modifies OHLC; switch to regular candles if you need raw price metrics.
3H/4H issues
Use integer HTF Multiplier (e.g., 2, 4). The tool builds the correct string internally; no manual timeframe strings needed.
Power user tips
Volume gating: keeping Require Volume Confirmation = ON filters most fake moves; if you’re a scalper, reduce strictness or turn it off.
Action threshold: 60–80 is typical. Higher = fewer but stronger signals.
Benchmark RS%: great for spotting leaders/laggards; positive RS% = outperformance vs benchmark.
Change policy & safety
This version doesn’t alter your historical logic you tested (no radical changes).
Any future “radical” change (score weights, HTF logic, UI hiding data) will ship with a toggle and an Impact Statement so you can keep old behavior if you prefer.
Glossary (quick)
ROC%: Percent change over N bars.
MOM: Scaled momentum (0–100).
VOL ratio: Volume vs 20-bar average.
ATR%: ATR as % of price.
ADX/DI: Trend strength / direction components (Wilder).
EMA stack: Relationship between EMAs (bullish/bearish/flat).
VWAP%: Premium/discount to VWAP.
RS%: Relative strength vs benchmark.
Markov Chain [3D] | FractalystWhat exactly is a Markov Chain?
This indicator uses a Markov Chain model to analyze, quantify, and visualize the transitions between market regimes (Bull, Bear, Neutral) on your chart. It dynamically detects these regimes in real-time, calculates transition probabilities, and displays them as animated 3D spheres and arrows, giving traders intuitive insight into current and future market conditions.
How does a Markov Chain work, and how should I read this spheres-and-arrows diagram?
Think of three weather modes: Sunny, Rainy, Cloudy.
Each sphere is one mode. The loop on a sphere means “stay the same next step” (e.g., Sunny again tomorrow).
The arrows leaving a sphere show where things usually go next if they change (e.g., Sunny moving to Cloudy).
Some paths matter more than others. A more prominent loop means the current mode tends to persist. A more prominent outgoing arrow means a change to that destination is the usual next step.
Direction isn’t symmetric: moving Sunny→Cloudy can behave differently than Cloudy→Sunny.
Now relabel the spheres to markets: Bull, Bear, Neutral.
Spheres: market regimes (uptrend, downtrend, range).
Self‑loop: tendency for the current regime to continue on the next bar.
Arrows: the most common next regime if a switch happens.
How to read: Start at the sphere that matches current bar state. If the loop stands out, expect continuation. If one outgoing path stands out, that switch is the typical next step. Opposite directions can differ (Bear→Neutral doesn’t have to match Neutral→Bear).
What states and transitions are shown?
The three market states visualized are:
Bullish (Bull): Upward or strong-market regime.
Bearish (Bear): Downward or weak-market regime.
Neutral: Sideways or range-bound regime.
Bidirectional animated arrows and probability labels show how likely the market is to move from one regime to another (e.g., Bull → Bear or Neutral → Bull).
How does the regime detection system work?
You can use either built-in price returns (based on adaptive Z-score normalization) or supply three custom indicators (such as volume, oscillators, etc.).
Values are statistically normalized (Z-scored) over a configurable lookback period.
The normalized outputs are classified into Bull, Bear, or Neutral zones.
If using three indicators, their regime signals are averaged and smoothed for robustness.
How are transition probabilities calculated?
On every confirmed bar, the algorithm tracks the sequence of detected market states, then builds a rolling window of transitions.
The code maintains a transition count matrix for all regime pairs (e.g., Bull → Bear).
Transition probabilities are extracted for each possible state change using Laplace smoothing for numerical stability, and frequently updated in real-time.
What is unique about the visualization?
3D animated spheres represent each regime and change visually when active.
Animated, bidirectional arrows reveal transition probabilities and allow you to see both dominant and less likely regime flows.
Particles (moving dots) animate along the arrows, enhancing the perception of regime flow direction and speed.
All elements dynamically update with each new price bar, providing a live market map in an intuitive, engaging format.
Can I use custom indicators for regime classification?
Yes! Enable the "Custom Indicators" switch and select any three chart series as inputs. These will be normalized and combined (each with equal weight), broadening the regime classification beyond just price-based movement.
What does the “Lookback Period” control?
Lookback Period (default: 100) sets how much historical data builds the probability matrix. Shorter periods adapt faster to regime changes but may be noisier. Longer periods are more stable but slower to adapt.
How is this different from a Hidden Markov Model (HMM)?
It sets the window for both regime detection and probability calculations. Lower values make the system more reactive, but potentially noisier. Higher values smooth estimates and make the system more robust.
How is this Markov Chain different from a Hidden Markov Model (HMM)?
Markov Chain (as here): All market regimes (Bull, Bear, Neutral) are directly observable on the chart. The transition matrix is built from actual detected regimes, keeping the model simple and interpretable.
Hidden Markov Model: The actual regimes are unobservable ("hidden") and must be inferred from market output or indicator "emissions" using statistical learning algorithms. HMMs are more complex, can capture more subtle structure, but are harder to visualize and require additional machine learning steps for training.
A standard Markov Chain models transitions between observable states using a simple transition matrix, while a Hidden Markov Model assumes the true states are hidden (latent) and must be inferred from observable “emissions” like price or volume data. In practical terms, a Markov Chain is transparent and easier to implement and interpret; an HMM is more expressive but requires statistical inference to estimate hidden states from data.
Markov Chain: states are observable; you directly count or estimate transition probabilities between visible states. This makes it simpler, faster, and easier to validate and tune.
HMM: states are hidden; you only observe emissions generated by those latent states. Learning involves machine learning/statistical algorithms (commonly Baum–Welch/EM for training and Viterbi for decoding) to infer both the transition dynamics and the most likely hidden state sequence from data.
How does the indicator avoid “repainting” or look-ahead bias?
All regime changes and matrix updates happen only on confirmed (closed) bars, so no future data is leaked, ensuring reliable real-time operation.
Are there practical tuning tips?
Tune the Lookback Period for your asset/timeframe: shorter for fast markets, longer for stability.
Use custom indicators if your asset has unique regime drivers.
Watch for rapid changes in transition probabilities as early warning of a possible regime shift.
Who is this indicator for?
Quants and quantitative researchers exploring probabilistic market modeling, especially those interested in regime-switching dynamics and Markov models.
Programmers and system developers who need a probabilistic regime filter for systematic and algorithmic backtesting:
The Markov Chain indicator is ideally suited for programmatic integration via its bias output (1 = Bull, 0 = Neutral, -1 = Bear).
Although the visualization is engaging, the core output is designed for automated, rules-based workflows—not for discretionary/manual trading decisions.
Developers can connect the indicator’s output directly to their Pine Script logic (using input.source()), allowing rapid and robust backtesting of regime-based strategies.
It acts as a plug-and-play regime filter: simply plug the bias output into your entry/exit logic, and you have a scientifically robust, probabilistically-derived signal for filtering, timing, position sizing, or risk regimes.
The MC's output is intentionally "trinary" (1/0/-1), focusing on clear regime states for unambiguous decision-making in code. If you require nuanced, multi-probability or soft-label state vectors, consider expanding the indicator or stacking it with a probability-weighted logic layer in your scripting.
Because it avoids subjectivity, this approach is optimal for systematic quants, algo developers building backtested, repeatable strategies based on probabilistic regime analysis.
What's the mathematical foundation behind this?
The mathematical foundation behind this Markov Chain indicator—and probabilistic regime detection in finance—draws from two principal models: the (standard) Markov Chain and the Hidden Markov Model (HMM).
How to use this indicator programmatically?
The Markov Chain indicator automatically exports a bias value (+1 for Bullish, -1 for Bearish, 0 for Neutral) as a plot visible in the Data Window. This allows you to integrate its regime signal into your own scripts and strategies for backtesting, automation, or live trading.
Step-by-Step Integration with Pine Script (input.source)
Add the Markov Chain indicator to your chart.
This must be done first, since your custom script will "pull" the bias signal from the indicator's plot.
In your strategy, create an input using input.source()
Example:
//@version=5
strategy("MC Bias Strategy Example")
mcBias = input.source(close, "MC Bias Source")
After saving, go to your script’s settings. For the “MC Bias Source” input, select the plot/output of the Markov Chain indicator (typically its bias plot).
Use the bias in your trading logic
Example (long only on Bull, flat otherwise):
if mcBias == 1
strategy.entry("Long", strategy.long)
else
strategy.close("Long")
For more advanced workflows, combine mcBias with additional filters or trailing stops.
How does this work behind-the-scenes?
TradingView’s input.source() lets you use any plot from another indicator as a real-time, “live” data feed in your own script (source).
The selected bias signal is available to your Pine code as a variable, enabling logical decisions based on regime (trend-following, mean-reversion, etc.).
This enables powerful strategy modularity : decouple regime detection from entry/exit logic, allowing fast experimentation without rewriting core signal code.
Integrating 45+ Indicators with Your Markov Chain — How & Why
The Enhanced Custom Indicators Export script exports a massive suite of over 45 technical indicators—ranging from classic momentum (RSI, MACD, Stochastic, etc.) to trend, volume, volatility, and oscillator tools—all pre-calculated, centered/scaled, and available as plots.
// Enhanced Custom Indicators Export - 45 Technical Indicators
// Comprehensive technical analysis suite for advanced market regime detection
//@version=6
indicator('Enhanced Custom Indicators Export | Fractalyst', shorttitle='Enhanced CI Export', overlay=false, scale=scale.right, max_labels_count=500, max_lines_count=500)
// |----- Input Parameters -----| //
momentum_group = "Momentum Indicators"
trend_group = "Trend Indicators"
volume_group = "Volume Indicators"
volatility_group = "Volatility Indicators"
oscillator_group = "Oscillator Indicators"
display_group = "Display Settings"
// Common lengths
length_14 = input.int(14, "Standard Length (14)", minval=1, maxval=100, group=momentum_group)
length_20 = input.int(20, "Medium Length (20)", minval=1, maxval=200, group=trend_group)
length_50 = input.int(50, "Long Length (50)", minval=1, maxval=200, group=trend_group)
// Display options
show_table = input.bool(true, "Show Values Table", group=display_group)
table_size = input.string("Small", "Table Size", options= , group=display_group)
// |----- MOMENTUM INDICATORS (15 indicators) -----| //
// 1. RSI (Relative Strength Index)
rsi_14 = ta.rsi(close, length_14)
rsi_centered = rsi_14 - 50
// 2. Stochastic Oscillator
stoch_k = ta.stoch(close, high, low, length_14)
stoch_d = ta.sma(stoch_k, 3)
stoch_centered = stoch_k - 50
// 3. Williams %R
williams_r = ta.stoch(close, high, low, length_14) - 100
// 4. MACD (Moving Average Convergence Divergence)
= ta.macd(close, 12, 26, 9)
// 5. Momentum (Rate of Change)
momentum = ta.mom(close, length_14)
momentum_pct = (momentum / close ) * 100
// 6. Rate of Change (ROC)
roc = ta.roc(close, length_14)
// 7. Commodity Channel Index (CCI)
cci = ta.cci(close, length_20)
// 8. Money Flow Index (MFI)
mfi = ta.mfi(close, length_14)
mfi_centered = mfi - 50
// 9. Awesome Oscillator (AO)
ao = ta.sma(hl2, 5) - ta.sma(hl2, 34)
// 10. Accelerator Oscillator (AC)
ac = ao - ta.sma(ao, 5)
// 11. Chande Momentum Oscillator (CMO)
cmo = ta.cmo(close, length_14)
// 12. Detrended Price Oscillator (DPO)
dpo = close - ta.sma(close, length_20)
// 13. Price Oscillator (PPO)
ppo = ta.sma(close, 12) - ta.sma(close, 26)
ppo_pct = (ppo / ta.sma(close, 26)) * 100
// 14. TRIX
trix_ema1 = ta.ema(close, length_14)
trix_ema2 = ta.ema(trix_ema1, length_14)
trix_ema3 = ta.ema(trix_ema2, length_14)
trix = ta.roc(trix_ema3, 1) * 10000
// 15. Klinger Oscillator
klinger = ta.ema(volume * (high + low + close) / 3, 34) - ta.ema(volume * (high + low + close) / 3, 55)
// 16. Fisher Transform
fisher_hl2 = 0.5 * (hl2 - ta.lowest(hl2, 10)) / (ta.highest(hl2, 10) - ta.lowest(hl2, 10)) - 0.25
fisher = 0.5 * math.log((1 + fisher_hl2) / (1 - fisher_hl2))
// 17. Stochastic RSI
stoch_rsi = ta.stoch(rsi_14, rsi_14, rsi_14, length_14)
stoch_rsi_centered = stoch_rsi - 50
// 18. Relative Vigor Index (RVI)
rvi_num = ta.swma(close - open)
rvi_den = ta.swma(high - low)
rvi = rvi_den != 0 ? rvi_num / rvi_den : 0
// 19. Balance of Power (BOP)
bop = (close - open) / (high - low)
// |----- TREND INDICATORS (10 indicators) -----| //
// 20. Simple Moving Average Momentum
sma_20 = ta.sma(close, length_20)
sma_momentum = ((close - sma_20) / sma_20) * 100
// 21. Exponential Moving Average Momentum
ema_20 = ta.ema(close, length_20)
ema_momentum = ((close - ema_20) / ema_20) * 100
// 22. Parabolic SAR
sar = ta.sar(0.02, 0.02, 0.2)
sar_trend = close > sar ? 1 : -1
// 23. Linear Regression Slope
lr_slope = ta.linreg(close, length_20, 0) - ta.linreg(close, length_20, 1)
// 24. Moving Average Convergence (MAC)
mac = ta.sma(close, 10) - ta.sma(close, 30)
// 25. Trend Intensity Index (TII)
tii_sum = 0.0
for i = 1 to length_20
tii_sum += close > close ? 1 : 0
tii = (tii_sum / length_20) * 100
// 26. Ichimoku Cloud Components
ichimoku_tenkan = (ta.highest(high, 9) + ta.lowest(low, 9)) / 2
ichimoku_kijun = (ta.highest(high, 26) + ta.lowest(low, 26)) / 2
ichimoku_signal = ichimoku_tenkan > ichimoku_kijun ? 1 : -1
// 27. MESA Adaptive Moving Average (MAMA)
mama_alpha = 2.0 / (length_20 + 1)
mama = ta.ema(close, length_20)
mama_momentum = ((close - mama) / mama) * 100
// 28. Zero Lag Exponential Moving Average (ZLEMA)
zlema_lag = math.round((length_20 - 1) / 2)
zlema_data = close + (close - close )
zlema = ta.ema(zlema_data, length_20)
zlema_momentum = ((close - zlema) / zlema) * 100
// |----- VOLUME INDICATORS (6 indicators) -----| //
// 29. On-Balance Volume (OBV)
obv = ta.obv
// 30. Volume Rate of Change (VROC)
vroc = ta.roc(volume, length_14)
// 31. Price Volume Trend (PVT)
pvt = ta.pvt
// 32. Negative Volume Index (NVI)
nvi = 0.0
nvi := volume < volume ? nvi + ((close - close ) / close ) * nvi : nvi
// 33. Positive Volume Index (PVI)
pvi = 0.0
pvi := volume > volume ? pvi + ((close - close ) / close ) * pvi : pvi
// 34. Volume Oscillator
vol_osc = ta.sma(volume, 5) - ta.sma(volume, 10)
// 35. Ease of Movement (EOM)
eom_distance = high - low
eom_box_height = volume / 1000000
eom = eom_box_height != 0 ? eom_distance / eom_box_height : 0
eom_sma = ta.sma(eom, length_14)
// 36. Force Index
force_index = volume * (close - close )
force_index_sma = ta.sma(force_index, length_14)
// |----- VOLATILITY INDICATORS (10 indicators) -----| //
// 37. Average True Range (ATR)
atr = ta.atr(length_14)
atr_pct = (atr / close) * 100
// 38. Bollinger Bands Position
bb_basis = ta.sma(close, length_20)
bb_dev = 2.0 * ta.stdev(close, length_20)
bb_upper = bb_basis + bb_dev
bb_lower = bb_basis - bb_dev
bb_position = bb_dev != 0 ? (close - bb_basis) / bb_dev : 0
bb_width = bb_dev != 0 ? (bb_upper - bb_lower) / bb_basis * 100 : 0
// 39. Keltner Channels Position
kc_basis = ta.ema(close, length_20)
kc_range = ta.ema(ta.tr, length_20)
kc_upper = kc_basis + (2.0 * kc_range)
kc_lower = kc_basis - (2.0 * kc_range)
kc_position = kc_range != 0 ? (close - kc_basis) / kc_range : 0
// 40. Donchian Channels Position
dc_upper = ta.highest(high, length_20)
dc_lower = ta.lowest(low, length_20)
dc_basis = (dc_upper + dc_lower) / 2
dc_position = (dc_upper - dc_lower) != 0 ? (close - dc_basis) / (dc_upper - dc_lower) : 0
// 41. Standard Deviation
std_dev = ta.stdev(close, length_20)
std_dev_pct = (std_dev / close) * 100
// 42. Relative Volatility Index (RVI)
rvi_up = ta.stdev(close > close ? close : 0, length_14)
rvi_down = ta.stdev(close < close ? close : 0, length_14)
rvi_total = rvi_up + rvi_down
rvi_volatility = rvi_total != 0 ? (rvi_up / rvi_total) * 100 : 50
// 43. Historical Volatility
hv_returns = math.log(close / close )
hv = ta.stdev(hv_returns, length_20) * math.sqrt(252) * 100
// 44. Garman-Klass Volatility
gk_vol = math.log(high/low) * math.log(high/low) - (2*math.log(2)-1) * math.log(close/open) * math.log(close/open)
gk_volatility = math.sqrt(ta.sma(gk_vol, length_20)) * 100
// 45. Parkinson Volatility
park_vol = math.log(high/low) * math.log(high/low)
parkinson = math.sqrt(ta.sma(park_vol, length_20) / (4 * math.log(2))) * 100
// 46. Rogers-Satchell Volatility
rs_vol = math.log(high/close) * math.log(high/open) + math.log(low/close) * math.log(low/open)
rogers_satchell = math.sqrt(ta.sma(rs_vol, length_20)) * 100
// |----- OSCILLATOR INDICATORS (5 indicators) -----| //
// 47. Elder Ray Index
elder_bull = high - ta.ema(close, 13)
elder_bear = low - ta.ema(close, 13)
elder_power = elder_bull + elder_bear
// 48. Schaff Trend Cycle (STC)
stc_macd = ta.ema(close, 23) - ta.ema(close, 50)
stc_k = ta.stoch(stc_macd, stc_macd, stc_macd, 10)
stc_d = ta.ema(stc_k, 3)
stc = ta.stoch(stc_d, stc_d, stc_d, 10)
// 49. Coppock Curve
coppock_roc1 = ta.roc(close, 14)
coppock_roc2 = ta.roc(close, 11)
coppock = ta.wma(coppock_roc1 + coppock_roc2, 10)
// 50. Know Sure Thing (KST)
kst_roc1 = ta.roc(close, 10)
kst_roc2 = ta.roc(close, 15)
kst_roc3 = ta.roc(close, 20)
kst_roc4 = ta.roc(close, 30)
kst = ta.sma(kst_roc1, 10) + 2*ta.sma(kst_roc2, 10) + 3*ta.sma(kst_roc3, 10) + 4*ta.sma(kst_roc4, 15)
// 51. Percentage Price Oscillator (PPO)
ppo_line = ((ta.ema(close, 12) - ta.ema(close, 26)) / ta.ema(close, 26)) * 100
ppo_signal = ta.ema(ppo_line, 9)
ppo_histogram = ppo_line - ppo_signal
// |----- PLOT MAIN INDICATORS -----| //
// Plot key momentum indicators
plot(rsi_centered, title="01_RSI_Centered", color=color.purple, linewidth=1)
plot(stoch_centered, title="02_Stoch_Centered", color=color.blue, linewidth=1)
plot(williams_r, title="03_Williams_R", color=color.red, linewidth=1)
plot(macd_histogram, title="04_MACD_Histogram", color=color.orange, linewidth=1)
plot(cci, title="05_CCI", color=color.green, linewidth=1)
// Plot trend indicators
plot(sma_momentum, title="06_SMA_Momentum", color=color.navy, linewidth=1)
plot(ema_momentum, title="07_EMA_Momentum", color=color.maroon, linewidth=1)
plot(sar_trend, title="08_SAR_Trend", color=color.teal, linewidth=1)
plot(lr_slope, title="09_LR_Slope", color=color.lime, linewidth=1)
plot(mac, title="10_MAC", color=color.fuchsia, linewidth=1)
// Plot volatility indicators
plot(atr_pct, title="11_ATR_Pct", color=color.yellow, linewidth=1)
plot(bb_position, title="12_BB_Position", color=color.aqua, linewidth=1)
plot(kc_position, title="13_KC_Position", color=color.olive, linewidth=1)
plot(std_dev_pct, title="14_StdDev_Pct", color=color.silver, linewidth=1)
plot(bb_width, title="15_BB_Width", color=color.gray, linewidth=1)
// Plot volume indicators
plot(vroc, title="16_VROC", color=color.blue, linewidth=1)
plot(eom_sma, title="17_EOM", color=color.red, linewidth=1)
plot(vol_osc, title="18_Vol_Osc", color=color.green, linewidth=1)
plot(force_index_sma, title="19_Force_Index", color=color.orange, linewidth=1)
plot(obv, title="20_OBV", color=color.purple, linewidth=1)
// Plot additional oscillators
plot(ao, title="21_Awesome_Osc", color=color.navy, linewidth=1)
plot(cmo, title="22_CMO", color=color.maroon, linewidth=1)
plot(dpo, title="23_DPO", color=color.teal, linewidth=1)
plot(trix, title="24_TRIX", color=color.lime, linewidth=1)
plot(fisher, title="25_Fisher", color=color.fuchsia, linewidth=1)
// Plot more momentum indicators
plot(mfi_centered, title="26_MFI_Centered", color=color.yellow, linewidth=1)
plot(ac, title="27_AC", color=color.aqua, linewidth=1)
plot(ppo_pct, title="28_PPO_Pct", color=color.olive, linewidth=1)
plot(stoch_rsi_centered, title="29_StochRSI_Centered", color=color.silver, linewidth=1)
plot(klinger, title="30_Klinger", color=color.gray, linewidth=1)
// Plot trend continuation
plot(tii, title="31_TII", color=color.blue, linewidth=1)
plot(ichimoku_signal, title="32_Ichimoku_Signal", color=color.red, linewidth=1)
plot(mama_momentum, title="33_MAMA_Momentum", color=color.green, linewidth=1)
plot(zlema_momentum, title="34_ZLEMA_Momentum", color=color.orange, linewidth=1)
plot(bop, title="35_BOP", color=color.purple, linewidth=1)
// Plot volume continuation
plot(nvi, title="36_NVI", color=color.navy, linewidth=1)
plot(pvi, title="37_PVI", color=color.maroon, linewidth=1)
plot(momentum_pct, title="38_Momentum_Pct", color=color.teal, linewidth=1)
plot(roc, title="39_ROC", color=color.lime, linewidth=1)
plot(rvi, title="40_RVI", color=color.fuchsia, linewidth=1)
// Plot volatility continuation
plot(dc_position, title="41_DC_Position", color=color.yellow, linewidth=1)
plot(rvi_volatility, title="42_RVI_Volatility", color=color.aqua, linewidth=1)
plot(hv, title="43_Historical_Vol", color=color.olive, linewidth=1)
plot(gk_volatility, title="44_GK_Volatility", color=color.silver, linewidth=1)
plot(parkinson, title="45_Parkinson_Vol", color=color.gray, linewidth=1)
// Plot final oscillators
plot(rogers_satchell, title="46_RS_Volatility", color=color.blue, linewidth=1)
plot(elder_power, title="47_Elder_Power", color=color.red, linewidth=1)
plot(stc, title="48_STC", color=color.green, linewidth=1)
plot(coppock, title="49_Coppock", color=color.orange, linewidth=1)
plot(kst, title="50_KST", color=color.purple, linewidth=1)
// Plot final indicators
plot(ppo_histogram, title="51_PPO_Histogram", color=color.navy, linewidth=1)
plot(pvt, title="52_PVT", color=color.maroon, linewidth=1)
// |----- Reference Lines -----| //
hline(0, "Zero Line", color=color.gray, linestyle=hline.style_dashed, linewidth=1)
hline(50, "Midline", color=color.gray, linestyle=hline.style_dotted, linewidth=1)
hline(-50, "Lower Midline", color=color.gray, linestyle=hline.style_dotted, linewidth=1)
hline(25, "Upper Threshold", color=color.gray, linestyle=hline.style_dotted, linewidth=1)
hline(-25, "Lower Threshold", color=color.gray, linestyle=hline.style_dotted, linewidth=1)
// |----- Enhanced Information Table -----| //
if show_table and barstate.islast
table_position = position.top_right
table_text_size = table_size == "Tiny" ? size.tiny : table_size == "Small" ? size.small : size.normal
var table info_table = table.new(table_position, 3, 18, bgcolor=color.new(color.white, 85), border_width=1, border_color=color.gray)
// Headers
table.cell(info_table, 0, 0, 'Category', text_color=color.black, text_size=table_text_size, bgcolor=color.new(color.blue, 70))
table.cell(info_table, 1, 0, 'Indicator', text_color=color.black, text_size=table_text_size, bgcolor=color.new(color.blue, 70))
table.cell(info_table, 2, 0, 'Value', text_color=color.black, text_size=table_text_size, bgcolor=color.new(color.blue, 70))
// Key Momentum Indicators
table.cell(info_table, 0, 1, 'MOMENTUM', text_color=color.purple, text_size=table_text_size, bgcolor=color.new(color.purple, 90))
table.cell(info_table, 1, 1, 'RSI Centered', text_color=color.purple, text_size=table_text_size)
table.cell(info_table, 2, 1, str.tostring(rsi_centered, '0.00'), text_color=color.purple, text_size=table_text_size)
table.cell(info_table, 0, 2, '', text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 1, 2, 'Stoch Centered', text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 2, 2, str.tostring(stoch_centered, '0.00'), text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 0, 3, '', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 1, 3, 'Williams %R', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 2, 3, str.tostring(williams_r, '0.00'), text_color=color.red, text_size=table_text_size)
table.cell(info_table, 0, 4, '', text_color=color.orange, text_size=table_text_size)
table.cell(info_table, 1, 4, 'MACD Histogram', text_color=color.orange, text_size=table_text_size)
table.cell(info_table, 2, 4, str.tostring(macd_histogram, '0.000'), text_color=color.orange, text_size=table_text_size)
table.cell(info_table, 0, 5, '', text_color=color.green, text_size=table_text_size)
table.cell(info_table, 1, 5, 'CCI', text_color=color.green, text_size=table_text_size)
table.cell(info_table, 2, 5, str.tostring(cci, '0.00'), text_color=color.green, text_size=table_text_size)
// Key Trend Indicators
table.cell(info_table, 0, 6, 'TREND', text_color=color.navy, text_size=table_text_size, bgcolor=color.new(color.navy, 90))
table.cell(info_table, 1, 6, 'SMA Momentum %', text_color=color.navy, text_size=table_text_size)
table.cell(info_table, 2, 6, str.tostring(sma_momentum, '0.00'), text_color=color.navy, text_size=table_text_size)
table.cell(info_table, 0, 7, '', text_color=color.maroon, text_size=table_text_size)
table.cell(info_table, 1, 7, 'EMA Momentum %', text_color=color.maroon, text_size=table_text_size)
table.cell(info_table, 2, 7, str.tostring(ema_momentum, '0.00'), text_color=color.maroon, text_size=table_text_size)
table.cell(info_table, 0, 8, '', text_color=color.teal, text_size=table_text_size)
table.cell(info_table, 1, 8, 'SAR Trend', text_color=color.teal, text_size=table_text_size)
table.cell(info_table, 2, 8, str.tostring(sar_trend, '0'), text_color=color.teal, text_size=table_text_size)
table.cell(info_table, 0, 9, '', text_color=color.lime, text_size=table_text_size)
table.cell(info_table, 1, 9, 'Linear Regression', text_color=color.lime, text_size=table_text_size)
table.cell(info_table, 2, 9, str.tostring(lr_slope, '0.000'), text_color=color.lime, text_size=table_text_size)
// Key Volatility Indicators
table.cell(info_table, 0, 10, 'VOLATILITY', text_color=color.yellow, text_size=table_text_size, bgcolor=color.new(color.yellow, 90))
table.cell(info_table, 1, 10, 'ATR %', text_color=color.yellow, text_size=table_text_size)
table.cell(info_table, 2, 10, str.tostring(atr_pct, '0.00'), text_color=color.yellow, text_size=table_text_size)
table.cell(info_table, 0, 11, '', text_color=color.aqua, text_size=table_text_size)
table.cell(info_table, 1, 11, 'BB Position', text_color=color.aqua, text_size=table_text_size)
table.cell(info_table, 2, 11, str.tostring(bb_position, '0.00'), text_color=color.aqua, text_size=table_text_size)
table.cell(info_table, 0, 12, '', text_color=color.olive, text_size=table_text_size)
table.cell(info_table, 1, 12, 'KC Position', text_color=color.olive, text_size=table_text_size)
table.cell(info_table, 2, 12, str.tostring(kc_position, '0.00'), text_color=color.olive, text_size=table_text_size)
// Key Volume Indicators
table.cell(info_table, 0, 13, 'VOLUME', text_color=color.blue, text_size=table_text_size, bgcolor=color.new(color.blue, 90))
table.cell(info_table, 1, 13, 'Volume ROC', text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 2, 13, str.tostring(vroc, '0.00'), text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 0, 14, '', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 1, 14, 'EOM', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 2, 14, str.tostring(eom_sma, '0.000'), text_color=color.red, text_size=table_text_size)
// Key Oscillators
table.cell(info_table, 0, 15, 'OSCILLATORS', text_color=color.purple, text_size=table_text_size, bgcolor=color.new(color.purple, 90))
table.cell(info_table, 1, 15, 'Awesome Osc', text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 2, 15, str.tostring(ao, '0.000'), text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 0, 16, '', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 1, 16, 'Fisher Transform', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 2, 16, str.tostring(fisher, '0.000'), text_color=color.red, text_size=table_text_size)
// Summary Statistics
table.cell(info_table, 0, 17, 'SUMMARY', text_color=color.black, text_size=table_text_size, bgcolor=color.new(color.gray, 70))
table.cell(info_table, 1, 17, 'Total Indicators: 52', text_color=color.black, text_size=table_text_size)
regime_color = rsi_centered > 10 ? color.green : rsi_centered < -10 ? color.red : color.gray
regime_text = rsi_centered > 10 ? "BULLISH" : rsi_centered < -10 ? "BEARISH" : "NEUTRAL"
table.cell(info_table, 2, 17, regime_text, text_color=regime_color, text_size=table_text_size)
This makes it the perfect “indicator backbone” for quantitative and systematic traders who want to prototype, combine, and test new regime detection models—especially in combination with the Markov Chain indicator.
How to use this script with the Markov Chain for research and backtesting:
Add the Enhanced Indicator Export to your chart.
Every calculated indicator is available as an individual data stream.
Connect the indicator(s) you want as custom input(s) to the Markov Chain’s “Custom Indicators” option.
In the Markov Chain indicator’s settings, turn ON the custom indicator mode.
For each of the three custom indicator inputs, select the exported plot from the Enhanced Export script—the menu lists all 45+ signals by name.
This creates a powerful, modular regime-detection engine where you can mix-and-match momentum, trend, volume, or custom combinations for advanced filtering.
Backtest regime logic directly.
Once you’ve connected your chosen indicators, the Markov Chain script performs regime detection (Bull/Neutral/Bear) based on your selected features—not just price returns.
The regime detection is robust, automatically normalized (using Z-score), and outputs bias (1, -1, 0) for plug-and-play integration.
Export the regime bias for programmatic use.
As described above, use input.source() in your Pine Script strategy or system and link the bias output.
You can now filter signals, control trade direction/size, or design pairs-trading that respect true, indicator-driven market regimes.
With this framework, you’re not limited to static or simplistic regime filters. You can rigorously define, test, and refine what “market regime” means for your strategies—using the technical features that matter most to you.
Optimize your signal generation by backtesting across a universe of meaningful indicator blends.
Enhance risk management with objective, real-time regime boundaries.
Accelerate your research: iterate quickly, swap indicator components, and see results with minimal code changes.
Automate multi-asset or pairs-trading by integrating regime context directly into strategy logic.
Add both scripts to your chart, connect your preferred features, and start investigating your best regime-based trades—entirely within the TradingView ecosystem.
References & Further Reading
Ang, A., & Bekaert, G. (2002). “Regime Switches in Interest Rates.” Journal of Business & Economic Statistics, 20(2), 163–182.
Hamilton, J. D. (1989). “A New Approach to the Economic Analysis of Nonstationary Time Series and the Business Cycle.” Econometrica, 57(2), 357–384.
Markov, A. A. (1906). "Extension of the Limit Theorems of Probability Theory to a Sum of Variables Connected in a Chain." The Notes of the Imperial Academy of Sciences of St. Petersburg.
Guidolin, M., & Timmermann, A. (2007). “Asset Allocation under Multivariate Regime Switching.” Journal of Economic Dynamics and Control, 31(11), 3503–3544.
Murphy, J. J. (1999). Technical Analysis of the Financial Markets. New York Institute of Finance.
Brock, W., Lakonishok, J., & LeBaron, B. (1992). “Simple Technical Trading Rules and the Stochastic Properties of Stock Returns.” Journal of Finance, 47(5), 1731–1764.
Zucchini, W., MacDonald, I. L., & Langrock, R. (2017). Hidden Markov Models for Time Series: An Introduction Using R (2nd ed.). Chapman and Hall/CRC.
On Quantitative Finance and Markov Models:
Lo, A. W., & Hasanhodzic, J. (2009). The Heretics of Finance: Conversations with Leading Practitioners of Technical Analysis. Bloomberg Press.
Patterson, S. (2016). The Man Who Solved the Market: How Jim Simons Launched the Quant Revolution. Penguin Press.
TradingView Pine Script Documentation: www.tradingview.com
TradingView Blog: “Use an Input From Another Indicator With Your Strategy” www.tradingview.com
GeeksforGeeks: “What is the Difference Between Markov Chains and Hidden Markov Models?” www.geeksforgeeks.org
What makes this indicator original and unique?
- On‑chart, real‑time Markov. The chain is drawn directly on your chart. You see the current regime, its tendency to stay (self‑loop), and the usual next step (arrows) as bars confirm.
- Source‑agnostic by design. The engine runs on any series you select via input.source() — price, your own oscillator, a composite score, anything you compute in the script.
- Automatic normalization + regime mapping. Different inputs live on different scales. The script standardizes your chosen source and maps it into clear regimes (e.g., Bull / Bear / Neutral) without you micromanaging thresholds each time.
- Rolling, bar‑by‑bar learning. Transition tendencies are computed from a rolling window of confirmed bars. What you see is exactly what the market did in that window.
- Fast experimentation. Switch the source, adjust the window, and the Markov view updates instantly. It’s a rapid way to test ideas and feel regime persistence/switch behavior.
Integrate your own signals (using input.source())
- In settings, choose the Source . This is powered by input.source() .
- Feed it price, an indicator you compute inside the script, or a custom composite series.
- The script will automatically normalize that series and process it through the Markov engine, mapping it to regimes and updating the on‑chart spheres/arrows in real time.
Credits:
Deep gratitude to @RicardoSantos for both the foundational Markov chain processing engine and inspiring open-source contributions, which made advanced probabilistic market modeling accessible to the TradingView community.
Special thanks to @Alien_Algorithms for the innovative and visually stunning 3D sphere logic that powers the indicator’s animated, regime-based visualization.
Disclaimer
This tool summarizes recent behavior. It is not financial advice and not a guarantee of future results.
Coin Jin Multi SMA+ BB+ SMA forecast Ver 2.0Coin Jin Multi SMA + BB + SMA Forecast 2.0
개요
여러 개의 단순이동평균(SMA: 5/20/60/112/224/448/896 + 사용자 정의 X1/X2), 볼린저 밴드(BB), 그리고 접선 기반 곡선 예측선을 한 번에 표시합니다. 예측선은 선형회귀 기울기와 그 변화율(가속도)을 EMA로 스무딩해 곡선 외삽으로 앞으로 그려지며, 어떤 줌에서도 깔끔하게 보이도록 점선(dotted) 스타일을 강제할 수 있습니다.
스택 마커(정배열/역배열) 안내
조건: 이동평균이 정배열(5>20>60>112>224>448>(896)) 또는 역배열(5<20<60<112<224<448<(896))로 새로 전환되는 순간 삼각형 마커가 생성됩니다.
896일선 포함(with 896): SOLID 마커로 표시, Bull = 초록색, Bear = 빨간색.
896일선 미포함(no 896): HOLLOW(윤곽) 마커로 표시, 시선을 덜 끌도록 투명도 70 적용(Bull = 연두, Bear = 빨강 동일색).
방향: Bull = ▼(위, abovebar) / Bear = ▲(아래, belowbar) 로 배치됩니다.
주요 기능
SMA 7종 기본 + 사용자 정의 SMA 2개(X1/X2) 추가(기본 꺼짐, 길이/색/두께/타입 자유).
BB: 길이/배수/선두께/밴드 채움(기본 90% 투명) 지원.
예측선: Forward bars(1–100, 기본 30), 기울기 산출 길이, 스무딩 강도, 세그먼트 개수, 점/대시 스타일 선택 및 도트 강제.
스택(정/역배열) 전환 마커: with 896=SOLID, no 896=HOLLOW(투명도 70).
처음 사용하는 분들을 위한 팁 (중요)
가격 스케일을 ‘우측’으로 고정하세요.
방법 ① 차트 우측 축을 사용(기본).
방법 ② 지표 레전드의 ‘⋯’ 메뉴 → Move to → Right scale.
예측선이 본선과 어긋나 보이면 스케일이 좌측/양측으로 되어 있거나 자동 합침된 경우이니 Right scale로 맞춰주세요.
입력 요약
MA Source, 각 SMA on/off·길이·색·두께·타입
BB length/mult/width/fill/opacity(기본 90)
Forecast bars ahead(1–100), slope lookback, smoothing, segments, style/opacity, 적용 대상 선택(SMA별)
주의/면책
예측선은 가격 예언 도구가 아니라 시각적 외삽 보조지표입니다. 단독 매매 판단에 사용하지 마세요.
공개 스크린샷은 본 지표만 보이도록 깔끔하게 캡처해 주세요(다른 지표/드로잉 혼합 금지).
변경사항(v2.0)
곡선 예측선 안정화 및 도트 강제 개선.
스택 마커 no 896 상태 HOLLOW 투명도 70 적용(가독성 향상).
사용자 정의 SMA X1/X2 추가(기본 OFF).
Coin Jin Multi SMA + BB + SMA Forecast 2.0 (English)
Overview
This indicator plots multiple Simple Moving Averages (SMA: 5/20/60/112/224/448/896 + two user-defined X1/X2), Bollinger Bands, and a tangent-based curved forecast in one overlay. The forecast extrapolates forward using the linear-regression slope and its rate of change (acceleration) smoothed by EMA, and you can force a dotted look so it stays clean at any zoom level.
Stack Markers (Bullish/Bearish alignment)
Markers appear only when a full bullish stack (5>20>60>112>224>448>(896)) or bearish stack (5<20<60<112<224<448<(896)) is newly formed.
With 896 included: shown as SOLID triangles — Bull = green, Bear = red.
Without 896: shown as HOLLOW (outline) with 70 transparency to reduce visual weight — Bull = lime, Bear = red (same hue).
Orientation: Bull = ▼ abovebar, Bear = ▲ belowbar.
Features
7 standard SMAs + two custom SMAs (X1/X2) (default OFF; fully configurable length/color/width/style).
BB with length/multiplier/width/fill (default fill opacity 90%).
Forecast controls: forward bars (1–100, default 30), slope window, smoothing, segment count, style/opacity, force dotted option.
Stack markers: with 896 = SOLID, without 896 = HOLLOW (70 transparency).
First-time setup (Important)
Pin the indicator to the Right price scale.
Option A: Use the right price axis.
Option B: Indicator legend “⋯” → Move to → Right scale.
If the forecast appears detached from the MA, your series is likely on the left/both scales; switch to Right scale.
Inputs
MA source; per-SMA on/off, length, color, width, style
BB length/multiplier/width/fill/opacity (default 90)
Forecast bars ahead (1–100), slope lookback, smoothing, segments, style/opacity, per-SMA apply switches
Disclaimer
The forecast is a visual extrapolation, not a price prediction. Do not use it alone to make trading decisions.
For publication, please use a clean screenshot that shows only this indicator (no mixed overlays).
What’s new in v2.0
More robust curved forecast with improved “force dotted” rendering.
HOLLOW (no 896) markers now use 70 transparency for better readability.
Added two user-defined SMAs (X1/X2), OFF by default.
Volume Stack with Dollar Volume ScoreThis script is designed to analyze candles for buy/sell pressure, volume flows, and generate intuitive emoji-based signals. Its core function is to help traders visually and quantitatively interpret price and volume behavior for potential bullish, bearish, or neutral market states.
Key Features and Logic
Price Range Analysis: Calculates the candle's price range and determines the proportion of volume attributed to buyers and sellers using buy_percent and sell_percent.
Market State Classification:
Bullish/Bearish/Neutral: Based on buy/sell percentage comparisons.
Strong Signals: Flags when buy/sell pressure exceeds defined thresholds (≥0.75).
Transitions: Detects when states shift sharply (e.g., from bull to strong bear).
Visual Cue System:
Uses different emojis (📈, 📉, 🚀, 🔥, 💎, 💀, ❌) to mark normal, strong, transition, and neutral signals for easy chart interpretation.
Dollar Volume Calculation: Multiplies close price by volume to derive "dollar volume" per bar. Normalizes this with a moving average for context-sensitive spike detection.
Scoring Mechanism:
Dollar Volume Score: Evaluates the normalized change in dollar volume, assigning scores for strong (±2), mild (±1), or neutral (0) changes.
Buy/Sell Pressure Score: Calculates a simple pressure score based on buy/sell proportions for each candle.
Composite Score: Combines both scores to define the overall bullish/bearish/neutral state.
State & Emoji Plotting:
Plots respective emojis at the chart bottom depending on composite score and state (bullish, bearish, strong moves, transitions, neutral).
Alerts:
Sends alerts for key transitions (like bull-to-strong-bear), strong moves, and neutral states, aiding automated signal handling and decision-making.
What This Script Helps You Achieve
Quick Visual Insights: Instantly see important market states and transitions with chart emojis.
Volume Context Awareness: Incorporates both price action and normalized volume changes for more reliable signals.
Automated Alerts: Supports smart trading decisions via pop-up notifications on major shifts or important conditions.
This script provides a layered analysis approach for volume and price action, blending quantifiable scores with intuitive chart markers and automated alerts, making it highly suited for traders who rely on both visual and quantitative cues in their strategy.
Engulfing Pattern[SpeculationLab]Overview
This script detects two types of engulfing / outer bar patterns and marks them directly on the chart:
Body Engulfing – The current candle’s body range (open–close) completely covers the entire range (high–low) of the previous candle.
Range Engulfing – The current candle’s full range (high–low, including wicks) completely covers the entire range (high–low) of the previous candle.
Direction logic:
Bull – The previous candle is bearish and the selected engulfing rule is met.
Bear – The previous candle is bullish and the selected engulfing rule is met.
Optional: Require the current candle to have the opposite color of the previous one.
This is an open-source pattern recognition tool for learning, backtesting, and chart review. It is not financial advice.
Key Features
Two detection modes:
body – Body engulfs previous entire range
range – Wicks engulf previous entire range
Direction detection based on the previous candle’s color, with optional opposite-color confirmation
Chart markers: “BULL” /“BEAR” above bars
Alert-ready: built-in conditions for bullish and bearish engulfing patterns
Parameters
Engulfing Type: body / range
body: Current body must fully cover the previous candle’s high–low range
range: Current full range (high–low) must fully cover the previous candle’s high–low range
Require Opposite Previous Candle (default: off):
When enabled, the engulfing pattern must also have the opposite color from the previous candle to trigger
Usage Tips
Engulfing patterns are price action structures; combine with trend, key levels, and volume for context
Signals confirm on bar close (barstate.isconfirmed) to reduce repainting
Can be used with personal risk management rules (stop-loss, take-profit, filters)
Disclaimer
For educational and research purposes only – not financial advice
Past performance of patterns does not guarantee future results
Trading involves risk; always manage it responsibly
This script is open-source – feel free to learn from or modify it, but credit the original source and author (SpeculationLab)
脚本简介
本脚本用于识别两类包裹/外包形态,并在图表上以标记提示:
Body(实体包裹):当前K线的实体区间(开—收)完全覆盖上一根K线的整个区间(上一根的高—低)。
Range(影线外包):当前K线的影线区间(高—低)完全覆盖上一根K线的整个区间(上一根的高—低)。
方向判定:
Bull(多):上一根为阴线且满足所选包裹规则;
Bear(空):上一根为阳线且满足所选包裹规则;
可选项:要求“当前K线颜色与上一根相反”后再确认(见参数)。
本脚本为开源形态识别工具,适合技术分析学习、回测与复盘,不构成任何投资建议。
主要功能
两种识别模式:body(实体包裹上一根整段) / range(影线包裹上一根整段)。
方向识别:按上一根K线颜色判断多空;可选“当前颜色与上一根相反”的二次确认。
图表提示:plotshape 在K线上方标注 “BULL / BEAR”。
提醒支持:内置 Bullish Engulf / Bearish Engulf 提醒条件。
参数说明
Engulfing Type:body / range
body:当前实体须完全覆盖上一根的高—低整段;
range:当前高—低须完全覆盖上一根的高—低整段。
Require Opposite Previous Candle(默认关闭):
开启后,除满足包裹规则外,还需当前K线颜色与上一根相反才触发标记。
使用建议
包裹/外包是价格行为结构,建议结合趋势、关键价位、成交量等因素综合判断。
信号在收盘时确认(barstate.isconfirmed),以减少重绘干扰。
可与个人风格的风险控制规则(止损、止盈、过滤条件)配合使用。
合规与免责声明
本脚本仅用于技术研究与学习,不构成任何形式的投资建议或收益承诺。
历史形态并不代表未来结果,交易有风险,请自行评估并承担责任。
本脚本开源,欢迎学习与二次开发;转载或改用请注明来源与作者(SpeculationLab / 投机实验室)。
Ichimoku Cloud Signals [sgbpulse] Ichimoku Cloud Signals – Your Advanced Trading Tool
Meet Ichimoku Cloud Signals, the enhanced and interactive version of the classic Ichimoku Cloud indicator, designed specifically for TradingView traders seeking precision and flexibility in their trading decisions. This indicator allows you to maximize the Ichimoku's potential by customizing trend criteria, receiving clear visual signals for entering and exiting positions, and getting alerts to keep you informed.
Introduction to the Ichimoku Cloud
The Ichimoku Cloud, also known as Ichimoku Kinko Hyo, is a comprehensive technical analysis tool developed in Japan. It provides a broad view of the market: trend direction, momentum, and support and resistance levels. "Ichimoku Cloud Signals" takes this power and amplifies it with advanced features.
Key Components of the Ichimoku Cloud
The indicator displays all five familiar Ichimoku lines, along with the "Cloud" (Kumo):
Tenkan-sen (Conversion Line): Calculated as the average of the highest high and lowest low over the past 9 periods. A fast, short-term indicator used as a measure of immediate momentum.
Kijun-sen (Base Line): Calculated as the average of the highest high and lowest low over the past 26 periods. A medium-term reference line serving as a significant support/resistance level.
Senkou Span A (Leading Span A): The average of the Tenkan-sen and Kijun-sen, shifted 26 periods forward into the future.
Senkou Span B (Leading Span B): The average of the highest high and lowest low over the past 52 periods, also shifted 26 periods forward into the future.
Kumo (Cloud): The area between Senkou Span A and Senkou Span B. Its color changes: green for an uptrend (when Senkou Span A is above Senkou Span B) and red for a downtrend (when Senkou Span B is above Senkou Span A). The Cloud serves as a dynamic area of support/resistance and a tool for forecasting future trends.
Chikou Span (Lagging Span): The current closing price, shifted 26 periods backward into the past. It serves as a powerful trend confirmation tool.
How the Ichimoku Cloud Works and How to Interpret It
Trend Identification :
- Uptrend (Bullish): The price is above the Cloud. The higher the price is above the Cloud, the stronger the trend.
- Downtrend (Bearish): The price is below the Cloud. The lower the price is below the Cloud, the stronger the trend.
- Range/Consolidation: The price is within the Cloud. This indicates a market without a clear direction or one that is consolidating.
Support and Resistance:
- The Cloud itself acts as a dynamic area of support and resistance. In an uptrend, the Cloud serves as support. In a downtrend, it serves as resistance.
- A thick Cloud indicates stronger support/resistance levels, while a thin Cloud indicates weaker levels.
The Cloud as a Predictive Indicator:
The uniqueness of the Kumo (Cloud) lies in its ability to be shifted 26 periods forward. This part of the Cloud provides forecasts for future support and resistance levels and even suggests expected trend changes (like a "Kumo Twist" – a change in Cloud color), giving you a planning advantage.
Unique Advantages of Ichimoku Cloud Signals:
Ichimoku Cloud Signals takes the classic Ichimoku principles and gives you unprecedented control:
Focused Trend Selection:
Choose whether you want to analyze a bullish (uptrend) or bearish (downtrend) trend. The indicator will focus on the relevant criteria for your selection.
Customizable Trend Confirmation Criteria (8 Criteria):
The indicator relies on 8 key criteria for clear trend confirmation. You can enable or disable each criterion individually based on your trading strategy and desired risk level. Each criterion plays a vital role in confirming the strength of the trend:
- Price position relative to the Cloud (Kumo) (Default: true): Determines the main trend direction and whether it's bullish or bearish.
- Price position relative to Kijun-sen (Base Line) (Default: true): Indicates the medium-term trend and acts as a critical equilibrium level.
- Price position relative to Tenkan-sen (Conversion Line) (Default: false): Provides quick confirmation of current momentum and short-term market changes.
- Tenkan-sen (Conversion Line) / Kijun-sen (Base Line) Crossover (Default: true): A classic signal for momentum change, crucial for identifying entry points.
- Current Cloud trend (Kumo) (Default: false): Cloud color confirms the main trend direction in real-time.
- Projected Future Cloud trend (Kumo) (Default: true): Indicates an expected future change in the Cloud's trend, providing strong visual insight.
- Chikou Span (Lagging Span) position relative to the Cloud (Kumo) (Default: true): Confirms the current trend strength by comparing the price to the Ichimoku 26 periods ago.
- Chikou Span (Lagging Span) position relative to the Price (Default: false): Additional confirmation of trend strength, indicating buyer/seller dominance.
Full Customization of Ichimoku Parameters:
You can change the period lengths for each Ichimoku component, depending on your strategy:
- Conversion Line Length (Default: 9)
- Base Line Length (Default: 26)
- Leading Span Length (Default: 52)
- Cloud Lagging Length (Default: 26)
- Lagging Span Length (Default: 26)
Visual Criteria Table on the Chart:
Get immediate and clear feedback! A visual table is placed on the chart, showing in real-time which of the 8 criteria you have defined are met for your chosen trend. Criteria you have enabled will be highlighted with a blue color and a "➤" symbol, while disabled criteria will appear in a subtle gray shade. For each criterion, the table shows its real-time status with a "✔" symbol if the condition is met and an "✘" symbol if it is not met. This powerful visual tool provides a quick assessment, helps with learning, and allows for strategy optimization at the click of a button.
Precise Criteria Details in the Data Window:
Beyond the visual table, the indicator provides an additional critical layer of detail: for any point on the chart, you can hover over a candle and see in TradingView's Data Window the precise status and values of all eight criteria. For each criterion, you'll see a clear numerical value (1 or 0) indicating whether it's fully met (1) or not met (0). Additionally, you can inspect the exact numerical values of the Ichimoku lines (Tenkan-sen, Kijun-sen, etc.) at that specific moment. This comprehensive data supports in-depth analysis, strategy debugging, and long-term optimization, providing complete transparency regarding every component of the signal.
Smart and Customizable Alerts:
Ichimoku Cloud Signals provides a powerful alert system to keep you informed of key market movements, so you never miss an opportunity. There are eight unique alerts you can enable in TradingView's alert panel:
Uptrend Entry Alert: Triggers when all of your selected criteria for an uptrend are met on a new candle.
Uptrend Exit Alert: Triggers when one of your selected uptrend criteria is no longer met, signaling a potential exit point.
Downtrend Entry Alert: Triggers when all of your selected criteria for a downtrend are met on a new candle.
Downtrend Exit Alert: Triggers when one of your selected downtrend criteria is no longer met, signaling a potential exit point.
Bullish Crossover Alert: Triggers when the Conversion Line (Tenkan-sen) crosses above the Base Line (Kijun-sen), a classic signal for an upward momentum shift.
Bearish Crossover Alert: Triggers when the Conversion Line (Tenkan-sen) crosses below the Base Line (Kijun-sen), signaling a potential shift to downward momentum.
Bullish Cloud Breakout Alert: Triggers when the price closes above the Ichimoku Cloud (Kumo), indicating a strong bullish trend.
Bearish Cloud Breakout Alert: Triggers when the price closes below the Ichimoku Cloud (Kumo), indicating a strong bearish trend.
Each alert can be independently configured in TradingView's alert panel, allowing you to tailor your notifications to fit your exact trading strategy and risk management preferences.
Summary:
Ichimoku Cloud Signals is an essential tool for TradingView traders seeking control, clarity, and precision. It combines the power of the classic Ichimoku Cloud indicator with advanced customization capabilities, a convenient visual table, and clear signals, empowering you to make informed trading decisions and stay focused on managing your positions.
Important Note: Trading Risk
This indicator is intended for educational and informational purposes only and does not constitute investment advice or a recommendation for trading in any form whatsoever.
Trading in financial markets involves significant risk of capital loss. It is important to remember that past performance is not indicative of future results. All trading decisions are your sole responsibility. Never trade with money you cannot afford to lose.
ABS NR — Fail-Safe Confirm (v4.2.2)
# ABS NR — Fail-Safe Confirm (v4.2.2)
## What it is (quick take)
**ABS NR FS** is a **non-repainting “arm → confirm” entry framework** for intraday and swing execution. It blends:
* **Regime** (EMA stack + 60-min slope),
* **Location** (Keltner basis/edges),
* **Stretch** (session-anchored **VWAP Z-score**),
* **Momentum gating** (TSI cross/slope),
* **Guards** (session window, minimum ATR%, gap filter, optional market alignment).
You’ll see a **small dot** when a setup is **armed** (candidate) and a **triangle** when that setup **confirms** within a user-defined number of bars. A **gray “X”** marks a timeout (candidate canceled).
> Tip: This entry tool works best when paired with a trend context filter and a dedicated exit tool.
---
## How to use it (operational workflow)
1. **Read the regime**
* **Bull trend**: fast > slow > long EMA **and** 60-min slope up.
* **Bear trend**: fast < slow < long EMA **and** 60-min slope down.
* **Range**: neither bull nor bear.
2. **Wait for a candidate (dot)**
Two families:
* **Reclaim (trend-following):** price crosses the **KC basis** with acceptable |Z| (not overstretched) and passes the TSI gate.
* **Fade (range-revert):** price **pokes a KC band**, prints a **reversal wick**, |Z| is stretched, and TSI gate agrees.
3. **Trade the confirmation (triangle)**
The confirm must occur **within N bars** and follow your chosen **Confirm mode** logic (see Inputs). If confirmation doesn’t arrive in time, an **X** cancels the candidate.
4. **Use guards to avoid junk**
Session windows (US focus), minimum ATR%, gap guard, and optional **market alignment** (e.g., SPY above EMA20 for longs).
5. **Manage the position**
* Entries: take **triangles** in the direction of your playbook (reclaims with trend; fades in clean ranges).
* Filters and exits: use your own process or pair with a trend/exit companion.
---
## Visual semantics & alerts
* **Candidate L / S (dot)** → a setup armed on this bar.
* **CONFIRM L / S (triangle)** → actionable signal that met confirm rules within your time window.
* **Cancel L / S (X)** → candidate expired without confirmation; ignore the dot.
**Alerts (stable names for automation):**
* **ABS FS — Confirmed** → fires on confirmed long or short.
* **ABS FS — Candidate Armed** → fires as a candidate arms.
---
## Non-repainting behavior (why signals don’t repaint)
* All HTF requests use **lookahead\_off**.
* With **Strict NR = true**, the 60-min slope uses the **prior completed** 60-min bar and arming/confirming only occurs on confirmed bars.
* Confirmation triangles finalize on bar close.
* If you disable strictness, signals may appear slightly earlier but with more intrabar sensitivity.
---
## Inputs reference (what each control does and the trade-offs)
### A) Behavior / Modes
**Mode** (`Turbo / Aggressive / Balanced / Conservative`)
Changes multiple internal thresholds:
* **Turbo** → most signals; relaxes prior-bar break & VWAP-side checks and time/vol/gap guards. Highest frequency, highest noise.
* **Aggressive** → more signals than Balanced, fewer than Turbo.
* **Balanced** → default; steady trade-off of frequency vs. quality.
* **Conservative** → tightens |Z| and other checks; fewest but cleanest signals.
**Strict NR (bar close + prior HTF 60m)**
* **true** = safer: uses prior 60-min slope; arms/confirms on confirmed bars → **fewer/cleaner** signals.
* **false** = earlier and more reactive; slightly noisier.
---
### B) Keltner Channel (location engine)
* **KC EMA Length (`kcLen`)**
Higher → smoother basis (fewer basis crosses). Lower → snappier basis (more crosses).
* **ATR Length (`atrLen`)**
Higher → steadier band width; Lower → more reactive band width.
* **KC ATR Mult (`kcMult`)**
Higher → wider bands (fewer edge pokes → fewer fades). Lower → narrower (more fades).
---
### C) Trend & HTF slope
* **Trend EMA Fast/Slow/Long (`emaFastLen / emaSlowLen / emaLongLen`)**
Larger = slower regime flips (fewer reclaims); smaller = faster flips (more reclaims).
* **HTF EMA Len (60m) (`htfLen`)**
Larger = steadier HTF slope (fewer signals); smaller = more sensitive (more signals).
---
### D) VWAP Z-Score (stretch / mean-revert logic)
* **VWAP Z-Length (`zLen`)**
Window for Z over session-anchored VWAP distance. Larger = smoother |Z| (fewer fades/re-entries). Smaller = more reactive (more).
* **Range Fade |Z| (base) (`zFadeBase`)**
Minimum |Z| to allow **fades** in ranges. Raise to demand more stretch (fewer fades). Lower to take more fades.
* **Max |Z| Trend Re-entry (base) (`maxZTrendBase`)**
Caps how stretched price can be and still permit **reclaims** with trend. Lower = stricter (avoid chases). Higher = will chase further.
---
### E) TSI Momentum Gate
* **TSI Long/Short/Signal (`tsiLong / tsiShort / tsiSig`)**
Larger = smoother/laggier momentum; smaller = snappier.
* **TSI gate (`CrossOnly / CrossOrSlope / Off`)**
* **CrossOnly**: require TSI cross of its signal (strict).
* **CrossOrSlope**: cross *or* favorable slope (balanced default).
* **Off**: no momentum gate (most signals, most noise).
---
### F) Guards (filters to avoid low-quality tape)
* **US focus 09:35–10:30 & 14:00–15:45 (base) (`useTimeBase`)**
`true` limits to high-quality windows. `false` trades all session.
* **Skip N bars after 09:30 ET (`skipFirst`)**
Skips the open scramble. Larger = skip longer.
* **Min volatility ATR% (base)** = `useVolMinBase` + `atrPctMinBase`
Requires `ATR(10)/Close*100 ≥ atrPctMinBase`. Raise threshold to avoid dead tape; lower to accept quieter sessions.
* **Gap guard (base)** = `gapGuardBase` + `gapMul`
Blocks signals when the opening gap exceeds `gapMul * ATR`. Increase `gapMul` to allow more gapped opens; decrease to be stricter.
---
### G) Visuals & Sides
* **Plot Keltner (`plotKC`)** → show/hide basis & bands.
* **Show Longs / Show Shorts** → enable/disable each side.
---
### H) Fail-Safe Confirmation
* **Confirm mode (`BreakHighOnly / BreakHigh+Hold / TwoBarImpulse`)**
* **BreakHighOnly**: confirm by taking out the armed bar’s extreme. Fastest, most frequent.
* **BreakHigh+Hold**: must **break**, have **body ≥ X·ATR**, **and** hold above/below the basis → higher quality, fewer signals.
* **TwoBarImpulse**: decisive follow-through vs. prior bar with **body ≥ X·ATR** → momentum-biased confirmations.
* **Confirm within N bars (`confirmBars`)**
Confirmation window size. Smaller = faster validation; larger = more patience (can be later).
* **Impulse body ≥ X·ATR (`impulseBodyATR`)**
Raise for stronger confirmations (fewer weak triangles). Lower to accept lighter pushes.
* **Require market alignment (`needMarket`) + `marketTicker`**
When enabled: Longs require **market > EMA20 (5m)**; Shorts require **market < EMA20 (5m)**.
* **Diagnostics: Show debug letters (`debug`)**
Tiny “B/C” audit marks for base/confirm while tuning.
---
## Tuning recipes (quick, practical)
* **If you’re getting chopped:**
* Set **Mode = Conservative**
* **Confirm mode = BreakHigh+Hold**
* Raise **impulseBodyATR** (e.g., 0.45)
* Keep **needMarket = true**
* Keep **Strict NR = true**
* **If you need more signals:**
* **Mode = Aggressive** (or Turbo if you accept more noise)
* **Confirm mode = BreakHighOnly**
* Lower **impulseBodyATR** (0.25–0.30)
* Increase **confirmBars** to 3
* **Range-day focus (fades):**
* Keep session guard on
* Raise **zFadeBase** to demand real stretch
* Keep **maxZTrendBase** moderate (don’t chase)
* **Trend-day focus (reclaims):**
* Slightly **lower `maxZTrendBase`** (avoid chasing excessive stretch)
* Use **CrossOrSlope** TSI gating
* Consider turning **needMarket** on
---
## Best practices & notes
* **Instrument specificity:** Tune Z, TSI, and guards per symbol and timeframe.
* **Session awareness:** Session filter uses **exchange-local** time; adjust for non-US markets.
* **Automation:** Use the two provided alert names; they’re stable.
* **Risk management:** Confirmation improves quality but doesn’t remove risk. Always pre-define stop/size logic.
---
## Suggested starting point (balanced profile)
* **Mode = balanced**
* **Strict NR = true**
* **Confirm mode = BreakHigh+Hold**
* **confirmBars = 2**
* **impulseBodyATR ≈ 0.35**
* **needMarket = off** (turn on for extra confluence)
* Leave Keltner/TSI defaults; then nudge `zFadeBase` and `maxZTrendBase` to match your symbol.
---
*This tool is a signal generator, not a broker or strategy. Validate on your markets/timeframes and integrate with your risk plan.*
RSI Momentum Divergence Zones [ChartPrime]⯁ OVERVIEW
RSI Momentum Divergence Zones is a hybrid oscillator and chart overlay tool that detects RSI-based momentum divergences and projects them as key zones on the chart. By combining RSI divergence logic with horizontal level plotting, this indicator reveals high-probability support and resistance areas where price has historically reacted to hidden or classic divergences.
⯁ KEY FEATURES
Momentum-Based RSI Source:
Instead of the classic RSI input, this tool uses the momentum of price as the RSI source:
rsiSrc = ta.mom(close, 10)
This emphasizes acceleration and deceleration of price moves, sharpening divergence signals and making them more responsive to early shifts in momentum.
Automatic Divergence Detection (Optional):
When enabled, the indicator continuously scans for:
— Bullish Divergence : Price makes a Lower Low while RSI forms a Higher Low
— Bearish Divergence : Price makes a Higher High while RSI forms a Lower High
It ensures divergence is valid by checking the spacing between pivots (min 5, max 50 bars).
Divergence Labels & Markers (RSI Pane + Chart):
When a valid divergence is detected:
— On RSI pane:
Labels appear at HL/LH points (“Bull” / “Bear”)
Colored lines show pivot structures
— On price chart:
Labels (“▲ Bull” / “Bear ▼”) mark price pivot that triggered the divergence
Lines highlight the exact price level at the divergence origin
Divergence Zones / Levels (Toggleable):
The indicator projects horizontal zones across the chart based on confirmed divergence points.
These levels dynamically extend as long as price respects them, and auto-expire once broken.
They act as S/R levels created by market imbalance caused by divergence reactions.
Dynamic Zone Extension Logic:
Once plotted, divergence levels will extend to the right:
— If price respects the level, the zone keeps growing
— If broken in the opposite direction, the level stops extending and turns dashed (visually showing break)
Zone Layering and Limit Control:
You can limit the number of simultaneous zones shown on the chart (e.g., 10 most recent).
Old zones automatically expire and are removed to keep the chart clean and focused.
Color Customization and Intensity:
Different colors for bullish and bearish zones let you easily distinguish trend direction.
Background fill, line width, and transparency are all adjustable.
Clean Zone Management with Arrays:
Behind the scenes, the script uses custom divLevel type arrays to manage plotted levels, ensuring they stay up-to-date, extend correctly, and delete once invalidated.
⯁ USAGE
Use bullish divergence zones as potential demand areas and bearish ones as supply zones.
Combine RSI pane labels with price-level zones to confirm strength of reversal.
Watch for price approaching a divergence level to anticipate reactions or breakouts.
Use divergence levels as trade triggers, stop-loss guides, or take-profit markers.
Limit signal count using the “Qty Divergence Zones” setting to reduce chart clutter.
Enable divergence detection only when you want to focus on key structural zones — ideal for swing or positional setups.
⯁ CONCLUSION
RSI Momentum Divergence Zones blends oscillator divergence logic with price action structure to uncover hidden strength or weakness in the market. With flexible zone plotting and clean visual signals, this tool empowers traders to identify where momentum turns into structure — turning hidden signals into tradable edges.
Market Regime Matrix [Alpha Extract]A sophisticated market regime classification system that combines multiple technical analysis components into an intelligent scoring framework to identify and track dominant market conditions. Utilizing advanced ADX-based trend detection, EMA directional analysis, volatility assessment, and crash protection protocols, the Market Regime Matrix delivers institutional-grade regime classification with BULL, BEAR, and CHOP states. The system features intelligent scoring with smoothing algorithms, duration filters for stability, and structure-based conviction adjustments to provide traders with clear, actionable market context.
🔶 Multi-Component Regime Engine Integrates five core analytical components: ADX trend strength detection, EMA-200 directional bias, ROC momentum analysis, Bollinger Band volatility measurement, and zig-zag structure verification. Each component contributes to a sophisticated scoring system that evaluates market conditions across multiple dimensions, ensuring comprehensive regime assessment with institutional precision.
// Gate Keeper: ADX determines market type
is_trending = adx_value > adx_trend_threshold
is_ranging = adx_value <= adx_trend_threshold
is_maximum_chop = adx_value <= adx_chop_threshold
// BULL CONDITIONS with Structure Veto
if price_above_ema and di_bullish
if use_structure_filter and isBullStructure
raw_bullScore := 5.0 // MAXIMUM CONVICTION: Strong signals + Bull structure
else if use_structure_filter and not isBullStructure
raw_bullScore := 3.0 // REDUCED: Strong signals but broken structure
🔶 Intelligent Scoring System Employs a dynamic 0-5 scale scoring mechanism for each regime type (BULL/BEAR/CHOP) with adaptive conviction levels. The system automatically adjusts scores based on signal alignment, market structure confirmation, and volatility conditions. Features decision margin requirements to prevent false regime changes and includes maximum conviction thresholds for high-probability setups.
🔶 Advanced Structure Filter Implements zig-zag based market structure analysis using configurable deviation thresholds to identify significant pivot points. The system tracks Higher Highs/Higher Lows (HH/HL) for bullish structure and Lower Lows/Lower Highs (LL/LH) for bearish structure, applying structure veto logic that reduces conviction when price action contradicts the underlying trend framework.
// Define Market Structure (Bull = HH/HL, Bear = LL/LH)
isBullStructure = not na(last_significant_high) and not na(prev_significant_high) and
not na(last_significant_low) and not na(prev_significant_low) and
last_significant_high > prev_significant_high and last_significant_low > prev_significant_low
isBearStructure = not na(last_significant_high) and not na(prev_significant_high) and
not na(last_significant_low) and not na(prev_significant_low) and
last_significant_low < prev_significant_low and last_significant_high < prev_significant_high
🔶 Superior Engine Components Features dual-layer regime stabilization through score smoothing and duration filtering. The score smoothing component reduces noise by averaging raw scores over configurable periods, while the duration filter requires minimum regime persistence before confirming changes. This eliminates whipsaws and ensures regime transitions represent genuine market shifts rather than temporary fluctuations.
🔶 Crash Detection & Active Penalties Incorporates sophisticated crash detection using Rate of Change (ROC) analysis with severity classification. When crash conditions are detected, the system applies active penalties (-5.0) to BULL and CHOP scores while boosting BEAR conviction based on crash severity. This ensures immediate regime response to major market dislocations and drawdown events.
// === CRASH OVERRIDE (Active Penalties) ===
is_crash = roc_value < crash_threshold
if is_crash
// Calculate crash severity
crash_severity = math.abs(roc_value / crash_threshold)
crash_bonus = 4.0 + (crash_severity - 1.0) * 2.0
// ACTIVE PENALTIES: Force bear dominance
raw_bearScore := math.max(raw_bearScore, crash_bonus)
raw_bullScore := -5.0 // ACTIVE PENALTY
raw_chopScore := -5.0 // ACTIVE PENALTY
❓How It Works
🔶 ADX-Based Market Classification The Market Regime Matrix uses ADX (Average Directional Index) as the primary gatekeeper to distinguish between trending and ranging market conditions. When ADX exceeds the trend threshold, the system activates BULL/BEAR regime logic using DI+/DI- crossovers and EMA positioning. When ADX falls below the ranging threshold, CHOP regime logic takes precedence, with maximum conviction assigned during ultra-low ADX periods.
🔶 Dynamic Conviction Scaling Each regime receives conviction ratings from UNCERTAIN to MAXIMUM based on signal alignment and score magnitude. MAXIMUM conviction (5.0 score) requires perfect signal alignment plus favorable market structure. The system progressively reduces conviction when signals conflict or structure breaks, ensuring traders understand the reliability of each regime classification.
🔶 Regime Transition Management Implements decision margin requirements where new regimes must exceed existing regimes by configurable thresholds before transitions occur. Combined with duration filtering, this prevents premature regime changes and maintains stability during consolidation periods. The system tracks both raw regime signals and final regime output for complete transparency.
🔶 Visual Regime Mapping Provides comprehensive visual feedback through colored candle overlays, background regime highlighting, and real-time information tables. The system displays regime history, conviction levels, structure status, and key metrics in an organized dashboard format. Regime changes trigger immediate visual alerts with detailed transition information.
🔶 Performance Optimization Features efficient array management for zig-zag calculations, smart variable updating to prevent recomputation, and configurable debug modes for strategy development. The system maintains optimal performance across all timeframes while providing institutional-grade analytical depth.
Why Choose Market Regime Matrix ?
The Market Regime Matrix represents the evolution of market regime analysis, combining traditional technical indicators with modern algorithmic decision-making frameworks. By integrating multiple analytical dimensions with intelligent scoring, structure verification, and crash protection, it provides traders with institutional-quality market context that adapts to changing conditions. The sophisticated filtering system eliminates noise while preserving responsiveness, making it an essential tool for traders seeking to align their strategies with dominant market regimes and avoid adverse market environments.
Institutional Momentum Zones (ADX+ROC+DI+MACD+Filters)Institutional Momentum Zones (ADX + ROC + DI + MACD + Filters)
This indicator is designed to help traders visually identify Bullish, Neutral, and Bearish momentum zones on Nifty, indices, or any liquid asset, using a rules-based, institutional-style approach.
It combines multiple professional-grade momentum and trend filters into a single framework:
ADX (Average Directional Index) – Measures trend strength, filters out choppy conditions.
Directional Indicators (+DI / –DI) – Confirms whether bulls or bears are in control.
ROC (Rate of Change) – Quantifies momentum speed and direction.
MACD (optional) – Adds confirmation by checking multi-timeframe momentum alignment.
EMA Filters (optional) – Ensures price is in alignment with long-term trend bias.
Supertrend (optional) – Can be enabled for additional trend confirmation.
How it works:
Bullish Zone (Green) → Strong trend (ADX > threshold) + upward momentum (ROC > 0, +DI > –DI) + optional EMA/MACD/Supertrend confirmation.
Bearish Zone (Red) → Strong trend (ADX > threshold) + downward momentum (ROC < 0, –DI > +DI) + optional EMA/MACD/Supertrend confirmation.
Neutral Zone (Yellow) → Low trend strength (ADX < threshold) or mixed momentum signals.
Features:
Automatic background coloring for zone detection.
On-chart labels marking new zone changes.
EMA50 / EMA200 and Supertrend overlay options.
Signal markers for bullish/bearish entries.
Info panel with live ADX, ROC, DI values, and MACD histogram.
Alert conditions for zone changes (Bull, Bear, Neutral).
Best used for:
Index momentum tracking (e.g., Nifty, Bank Nifty, Dow, S&P500)
Swing trading & positional trading strategies
Filtering trades to avoid entering during low-momentum chop
Tip: For Nifty positional trading, use Daily or 4H charts with EMA & MACD filters enabled for cleaner, high-confidence signals.
Leader-Lagger DashboardSummary:
The ultimate frustration for a trader: being right on the idea, but wrong on the asset.
You correctly predict a market move, develop a solid bullish or bearish thesis, but the instrument you choose fails to follow through. Meanwhile, a correlated asset makes the exact move you anticipated, leaving you with a losing trade or a missed opportunity.
This common pitfall is precisely what the Leader/Lagger Dashboard is designed to solve.
The Solution: Instant Clarity on Relative Strength
The Leader/Lagger Dashboard provides a clear, real-time verdict on the relative strength between two correlated assets, such as ES (S&P 500 futures) and NQ (Nasdaq 100 futures).
By instantly identifying the Leader (the stronger asset) and the Lagger (the weaker asset), it empowers you to focus your capital on the instrument with the highest probability of performing in line with your market view.
As shown in the example image, if your idea is to short the market, choosing the "Weak" asset (ES) results in a winning trade, while shorting the "Strong" asset (NQ) would have failed. This tool helps you make that critical distinction before you enter.
How It Works
The engine at the core of this dashboard analyzes the price action of two assets on a higher timeframe (defaulting to 90 minutes). It measures how the current bar's high and low are performing relative to the previous bar's range for each asset. By comparing these normalized values, it generates a score to determine which asset is exhibiting stronger momentum (the Leader) and which is showing weakness (the Lagger).
A tie-breaking mechanism using a lower timeframe ensures you always have a decisive verdict.
How to Use It
The principle is simple: Go long the leader, and short the lagger.
If you are Bullish: Look for the asset marked "Strong." This is the instrument most likely to lead the upward move.
If you are Bearish: Look for the asset marked "Weak." This is the instrument most likely to lead the downward move.
By aligning your trade execution with the market's internal momentum, you dramatically increase your odds of success and avoid the frustration of trading against underlying strength or weakness.
Key Features
Instant Verdict: A simple on-chart table displays a "Strong" or "Weak" verdict for each asset.
Focus on the Leader: Easily identify which asset is leading the move to align your trades with momentum.
Avoid the Lagger: Steer clear of the weaker asset that might chop around or reverse, even if your directional bias is correct.
Fully Customizable: Change the two assets to any symbols you trade (e.g., GOLD vs. SILVER, EURUSD vs. GBPUSD).
Adjustable Display: Control the table's position and font size to perfectly fit your chart layout. The table is designed to be visible on lower timeframes (5-minutes and under) to assist with day trading execution.
This tool is designed to be a crucial part of your decision-making process, providing an objective layer of confirmation for your trading ideas. so Stop guessing and start trading the right asset.
As always, use this indicator in conjunction with your own complete analysis and risk management strategy.
cd_HTF_bias_CxOverview:
No matter our trading style or model, to increase our success rate, we must move in the direction of the trend and align with the Higher Time Frame (HTF). Trading "gurus" call this the HTF bias. While we small fish tend to swim in all directions, the smart way is to flow with the big wave and the current. This indicator is designed to help us anticipate that major wave.
________________________________________
Details and Usage:
This indicator observes HTF price action across preferably seven different pairs, following specific rules. It confirms potential directional moves using CISD levels on a Medium Time Frame (MTF). In short, it forecasts the likely direction (HTF bias). The user can then search for trade opportunities aligned with this bias on a Lower Time Frame (LTF), using their preferred pair, entry model, and style.
________________________________________
Timeframe Alignment:
The commonly accepted LTF/MTF/HTF combinations include:
• 1m – 15m – H4
• 3m – H1 – Daily / 3m – 30m – Daily
• 5m – H1 – Daily
• 15m – H4 – Weekly
• H1 – Daily – Monthly
• H4 – Weekly – Quarterly
Example: If you're trading with a 3m model on a 30m/3m setup, you should seek trades in the direction of the H1/Daily bias.
________________________________________
How It Works:
The indicator first looks for sweeps on the selected HTF — when any of the last four candles are swept, the first condition is met.
The second step is confirmation with a CISD close on the MTF — once a candle closes above/below the CISD level, the second condition is fulfilled. This suggests the price has made its directional decision.
Example: If a previous HTF candle is swept and we receive a bearish CISD confirmation on H1, the HTF bias becomes bearish.
After this, you may switch to a more granular setup like HTF: 30m and MTF: 3m to look for trade entries aligned with the bias (e.g., 30m sweep + 3m CISD).
________________________________________
How Is Bias Determined?
• HTF Sweep + MTF CISD = SC (Sweep & CISD)
• Latest Bullish SC → Bias: Bullish
• Latest Bearish SC → Bias: Bearish
• Price closes above the last Bearish SC → Bias: Strong Bullish
• Price closes below the last Bullish SC → Bias: Strong Bearish
• Strong Bullish bias + Bearish CISD (without HTF sweep) → Bias: Bullish
• Strong Bearish bias + Bullish CISD (without HTF sweep) → Bias: Bearish
• Bearish price violates SC high, but Bullish SC is untouched → Bias: Bullish
• Bullish price violates SC low, but Bearish SC is untouched → Bias: Bearish
• If neither side generates SC → Bias: No Bias
The logic is built on the idea that a price overcoming resistance is stronger, and encountering resistance is weaker. This model is based on the well-known “Daily Bias” structure, but with personal refinements.
________________________________________
What’s on the Screen?
• Classic HTF zones (boxes)
• Potential MTF CISD levels
• Confirmed MTF lines
• Sweep zones when HTF sweeps occur
• Result table showing current bias status
________________________________________
Usage:
• Select HTF and MTF timeframes aligned with your trading timeframe.
• Adjust color and position settings as needed.
• Enter up to seven pairs to track via the menu.
• Use the checkbox next to each pair to enable/disable them.
• If “Ignore these assets” is checked, all pairs will be disabled, and only the currently open chart pair will be tracked.
________________________________________
Alerts:
You can choose alerts for Bullish, Bearish, Strong Bullish, or Strong Bearish conditions.
There are two types of alert sources:
1. From the indicator’s internal list
2. From TradingView’s watchlist
Visual example:
________________________________________
How I Use It:
• For spot trades, I use HTF: Weekly and MTF: H4 and look for Bullish or Strong Bullish pairs.
• For scalping, I follow bias from HTF: Daily and MTF: H1.
Example: If the indicator shows a Bearish HTF Bias, I switch to HTF: 30m and MTF: 3m and enter trades once bearish conditions are met (timeframe alignment).
________________________________________
Important Notes:
• The indicator defines CISD levels only at HTF high and low levels.
• If your chart is on a higher timeframe than your selected HTF/MTF, no data will appear.
Example: If HTF = H1 and MTF = 5m, opening a chart on H4 will result in a blank screen.
• The drawn CISD level on screen is the MTF CISD level.
• Not every alert should be traded. Always confirm with personal experience and visual validation.
• Receiving multiple Strong Bullish/Bearish alerts is intentional. (Trick 😊)
• Please share your feedback and suggestions!
________________________________________
And Most Importantly:
Don't leave street animals without water and food!
Happy trading!
Volume Imbalance# Volume Imbalance Indicator
## Description
The Volume Imbalance Indicator is a technical analysis tool that measures the imbalance between bullish and bearish volume over a specified period. This indicator helps traders identify the prevailing market sentiment and potential reversal points.
## How It Works
The indicator analyzes trading volume for each candle:
- **Bull Volume** - volume of candles where the closing price is higher than the opening price (green candles)
- **Bear Volume** - volume of candles where the closing price is lower than the opening price (red candles)
- **Imbalance** is calculated as the difference between the sum of bull volume and bear volume over the set period
## Signal Interpretation
- **Positive values (green histogram)** - bullish volume dominates, indicating buyer strength
- **Negative values (red histogram)** - bearish volume dominates, indicating seller strength
- **Zero line** - equilibrium between buyers and sellers
## Trading Applications
1. **Trend Confirmation** - imbalance in the direction of the trend confirms its strength
2. **Divergence Analysis** - divergence between price and indicator may signal potential reversals
3. **Accumulation/Distribution Zones** - prolonged periods of imbalance indicate large player activity
## Settings
- **Period** - number of candles for calculating the imbalance (default: 20)
## Features
- Displays in a separate panel below the main chart
- Histogram format for better visualization
- Color coding: green for bullish imbalance, red for bearish imbalance
- Suitable for all timeframes and trading instruments
This indicator is particularly effective when combined with other technical analysis tools for comprehensive market assessment.
caracalla ema long short signal📌 Indicator Name
caracalla ema long short signal
This script generates long and short trading signals using multiple technical indicators: EMAs, MACD, RSI, Stochastic, and volume.
🔧 Indicators Used
1. Exponential Moving Averages (EMA)
ema5, ema20, ema60, ema120 — used to determine overall trend direction.
2. Trend Confirmation (MA Alignment)
Bullish alignment: ema5 > ema20 > ema60 > ema120
Bearish alignment: ema5 < ema20 < ema60 < ema120
3. Crossover Signals
Golden Cross: ema5 crosses above ema20
Dead Cross: ema5 crosses below ema20
4. MACD
Standard parameters: 12, 26, 9
MACD Long: MACD line crosses above signal line
MACD Short: MACD line crosses below signal line
5. RSI & Stochastic
RSI(14): checks momentum
Stochastic (%K, %D)
Bullish: RSI > 50 and Stochastic %K crosses above %D
Bearish: RSI < 50 and Stochastic %K crosses below %D
6. Volume Filter
20-period simple average volume
Volume Up: Current volume > 120% of average
Volume Down: Current volume < 80% of average
✅ Signal Logic
📈 Long Signal (longSignal)
Triggered when 3 or more of the following are true:
EMA bullish alignment
Golden cross
MACD bullish crossover
RSI > 50 and Stochastic bullish crossover
High volume
📉 Short Signal (shortSignal)
Triggered when 3 or more of the following are true:
EMA bearish alignment
Dead cross
MACD bearish crossover
RSI < 50 and Stochastic bearish crossover
Low volume
📊 Visual Elements
Long Signal: Green “롱” label below the candle
Short Signal: Red “숏” label above the candle
EMA Lines:
EMA5 (Blue)
EMA20 (Orange)
EMA60 (Green)
EMA120 (Red)
Simple Trend Indicator (Heikin-Ashi) | Lyro RSSimple Trend Indicator (Heikin-Ashi)
A momentum oscillator using Heikin-Ashi smoothed data to filter trend direction with zero-line crosses.
This indicator calculates the normalized deviation of Heikin-Ashi OHLC values from their Simple Moving Average (SMA), then averages these deviations into a single oscillator. It simplifies trend detection by:
Reducing noise via Heikin-Ashi smoothing.
Highlighting momentum shifts through a zero-line cross system (bullish/bearish).
Providing clear visual signals with color-coded plots and directional dots.
Originality:
Unlike standard momentum oscillators, this tool uniquely combines:
Heikin-Ashi normalization for cleaner trend analysis.
Multi-component averaging (high, open, low, close) to balance sensitivity.
Minimalist design for clutter-free charting.
How It Works:
Data Input: Fetches Heikin-Ashi OHLC values using request.security().
Momentum Calculation: For each Heikin-Ashi component:
Computes % deviation from its SMA: (value − SMA(value, length)) / SMA(value, length) * 100.
Oscillator: Averages deviations of all four components into one line (sum).
Signals:
Bullish: Oscillator > 0 (green).
Bearish: Oscillator < 0 (red).
Cross Confirmation: Dots (⦿) mark zero-line crosses.
Usage:
Trend Following: Enter long/short on sustained oscillator breaks above/below zero.
Reversal Watch: Zero-line crosses may hint at weakening momentum.
Filter: Combine with volume or support/resistance levels.
⚠️Disclaimer: This indicator is a tool for technical analysis and does not provide guaranteed results. It should be used in conjunction with other analysis methods and proper risk management practices. The creators of this indicator are not responsible for any financial decisions made based on its signals.
Ratio-Adjusted McClellan Summation Index RASI NASIRatio-Adjusted McClellan Summation Index (RASI NASI)
In Book "The Complete Guide to Market Breadth Indicators" Author Gregory L. Morris states
"It is the author’s opinion that the McClellan indicators, and in particular, the McClellan Summation Index, is the single best breadth indicator available. If you had to pick just one, this would be it."
What It Does: The Ratio-Adjusted McClellan Summation Index (RASI) is a market breadth indicator that tracks the cumulative strength of advancing versus declining issues for a user-selected exchange (NASDAQ, NYSE, or AMEX). Derived from the McClellan Oscillator, it calculates ratio-adjusted net advances, applies 19-day and 39-day EMAs, and sums the oscillator values to produce the RASI. This indicator helps traders assess market health, identify bullish or bearish trends, and detect potential reversals through divergences.
Key features:
Exchange Selection : Choose NASDAQ (USI:ADVN.NQ, USI:DECL.NQ), NYSE (USI:ADVN.NY, USI:DECL.NY), or AMEX (USI:ADVN.AM, USI:DECL.AM) data.
Trend-Based Coloring : RASI line displays user-defined colors (default: black for uptrend, red for downtrend) based on its direction.
Customizable Moving Average: Add a moving average (SMA, EMA, WMA, VWMA, or RMA) with user-defined length and color (default: EMA, 21, green).
Neutral Line at Zero: Marks the neutral level for trend interpretation.
Alerts: Six custom alert conditions for trend changes, MA crosses, and zero-line crosses.
How to Use
Add to Chart: Apply the indicator to any TradingView chart. Ensure access to advancing and declining issues data for the selected exchange.
Select Exchange: Choose NASDAQ, NYSE, or AMEX in the input settings.
Customize Settings: Adjust EMA lengths, RASI colors, MA type, length, and color to match your trading style.
Interpret the Indicator :
RASI Line: Black (default) indicates an uptrend (RASI rising); red indicates a downtrend (RASI falling).
Above Zero: Suggests bullish market breadth (more advancing issues).
Below Zero : Indicates bearish breadth (more declining issues).
MA Crosses: RASI crossing above its MA signals bullish momentum; crossing below signals bearish momentum.
Divergences: Compare RASI with the market index (e.g., NASDAQ Composite) to identify potential reversals.
Large Moves : A +3,600-point move from a low (e.g., -1,550 to +1,950) may signal a significant bull run.
Set Alerts:
Add the indicator to your chart, open the TradingView alert panel, and select from six conditions (see Alerts section).
Configure notifications (e.g., email, webhook, or popup) for each condition.
Settings
Market Selection:
Exchange: Select NASDAQ, NYSE, or AMEX for advancing/declining issues data.
EMA Settings:
19-day EMA Length: Period for the shorter EMA (default: 19).
39-day EMA Length: Period for the longer EMA (default: 39).
RASI Settings:
RASI Uptrend Color: Color for rising RASI (default: black).
RASI Downtrend Color: Color for falling RASI (default: red).
RASI MA Settings:
MA Type: Choose SMA, EMA, WMA, VWMA, or RMA (default: EMA).
MA Length: Set the MA period (default: 21).
MA Color: Color for the MA line (default: green).
Alerts
The indicator uses alertcondition() to create custom alerts. Available conditions:
RASI Trend Up: RASI starts rising (based on RASI > previous RASI, shown as black line).
RASI Trend Down: RASI starts falling (based on RASI ≤ previous RASI, shown as red line).
RASI Above MA: RASI crosses above its moving average.
RASI Below MA: RASI crosses below its moving average.
RASI Bullish: RASI crosses above zero (bullish market breadth).
RASI Bearish: RASI crosses below zero (bearish market breadth).
To set alerts, add the indicator to your chart, open the TradingView alert panel, and select the desired condition.
Notes
Data Requirements: Requires access to advancing/declining issues data (e.g., USI:ADVN.NQ, USI:DECL.NQ for NASDAQ). Some symbols may require a TradingView premium subscription.
Limitations: RASI is a medium- to long-term indicator and may lag in volatile or range-bound markets. Use alongside other technical tools for confirmation.
Data Reliability : Verify the selected exchange’s data accuracy, as inconsistencies can affect results.
Debugging: If no data appears, check symbol validity (e.g., try $ADVN/Q, $DECN/Q for NASDAQ) or contact TradingView support.
Credits
Based on the Ratio-Adjusted McClellan Summation Index methodology by McClellan Financial Publications. No external code was used; the implementation is original, inspired by standard market breadth concepts.
Disclaimer
This indicator is for informational purposes only and does not constitute financial advice. Past performance is not indicative of future results. Conduct your own research and combine with other tools for informed trading decisions.
RSI Divergence(CompactFX)This is the standard "RSI" with "divergence" displayed. Additionally, it has the following features:
- The line color shifts above and below the RSI 50 threshold.
- The MA can be displayed on the RSI.
- Signs of an expected reversal are displayed.
**Examples of Use**
*For Swing Traders
In addition to using the standard RSI, the divergence display can serve as a trigger for further consideration.
*For Scalpers
For athletic traders who prefer intuition over logic and calculation, we recommend customizing the RSI color to your liking for bulls and bears. Consider extending the price until the RSI color changes. Below is my example.
-One-Minute Scalping
When prices are moving above the long-term and short-term MAs, you can hold a position as long as the RSI is above 55 (below 45 for bears). In this case, pivot signs can also be used as a guide for closing positions. Of course, this is best done during periods of high momentum. Five- and 15-minute scalping also works well. However, these only work if you adhere to my logic. Don't forget to adhere to your own logic and framework.
The above is just an example. Feel free to use it as you like.
Trend Flow Oscillator (CMF + MFI) + ADX## Trend Flow Oscillator (TFO + ADX) Indicator Description
The Trend Flow Oscillator (TFO+ADX) combines two volume-based indicators, Money Flow Index (MFI) and Chaikin Money Flow (CMF), along with the Average Directional Index (ADX) into one comprehensive oscillator. This indicator provides traders with insights into momentum, volume flow, and trend strength, clearly indicating bullish or bearish market conditions.
### How the Indicator Works:
1. **Money Flow Index (MFI)**:
* Measures buying and selling pressure based on price and volume.
* Scaled from -1 to +1 (where positive values indicate buying pressure, negative values indicate selling pressure).
2. **Chaikin Money Flow (CMF)**:
* Evaluates money flow volume over a set period, reflecting institutional buying or selling.
* Also scaled from -1 to +1 (positive values suggest bullish accumulation, negative values bearish distribution).
3. **Average Directional Index (ADX)**:
* Measures trend strength, indicating whether a market is trending or ranging.
* Scaled from -1 to +1, with values above 0 suggesting strong trends, and values near or below 0 indicating weak trends or sideways markets.
* Specifically, an ADX value of 0 means neutral trend strength; positive values indicate a strong trend.
### Indicator Levels and Interpretation:
* **Zero Line (0)**: Indicates neutral conditions. When the oscillator crosses above zero, it signals increasing bullish momentum; crossing below zero indicates bearish momentum.
* **Extreme Zones (+/- 0.75)**:
* Oscillator values above +0.75 are considered overbought or highly bullish.
* Oscillator values below -0.75 are considered oversold or highly bearish.
* The indicator features subtle background shading to visually highlight these extreme momentum areas for quick identification.
* Shading when values above or below the +/-1.0 level.
* **Color Coding**:
* Bright blue indicates strengthening bullish momentum.
* Dark blue signals weakening bullish momentum.
* Bright red indicates strengthening bearish momentum.
* Dark maroon signals weakening bearish momentum.