Candle 2 Closure [LuxAlgo]The Candle 2 Closure tool detects a specific reversal pattern on the chart spanning four bars. The first bar trades into a key price level. The second bar trades outside the first bar's range, but closes inside, indicating a reversal. The third bar closes outside the second bar's range, in the direction of the reversal, creating a price expansion. The fourth bar is a continuation of prices in that same direction.
This tool features key levels, equilibrium zones, and real-time alarms upon confirmation of the second and third candles of the pattern.
This specific part of the more complete Fractal model by TTrades was requested by a lot of you. We are happy to bring it to you and wish you a merry Christmas!
🔶 USAGE
This pattern is a TTrades concept: a reversal setup that is very easy to understand. It occurs when the current bar trades outside of the previous bar's range, but closes inside it. In other words, traders try to push prices outside of the previous bar's range, but fail. This is considered a reversal, meaning that traders encountered opposing forces that overwhelmed them. Thus, the expectation is that prices will trade in the new direction, changing the market bias from bullish to bearish, or vice versa.
Let's look at the example in the chart, where the four candles of this setup are marked. Note that we have selected a perfect setup, where all conditions are met.
Candle 1: This bar traded into a key price area at the top of the range, spanning several months.
Candle 2: This bar traded outside the range of Candle 1, but failed to close outside. This is the reversal.
Candle 3: The wick of this bar formed at or below the equilibrium zone of Candle 2, and it closed outside the range of Candle 2. This is the expansion.
Candle 4: At this point, the setup is complete, and the expectation for this candle is that it will trade in the same direction. The top of the candle is at or below the equilibrium zone of Candle 3. This is the continuation.
In a strong setup, the top or bottom of the next bar will form inside the equilibrium zone defined by the highlighted areas on candles 2 and 3.
This is a perfect bearish setup, featuring all elements. Not all setups will be like this, but when this setup occurs, it is important for traders to be aware of it.
The tool is highly customizable from the settings panel and features real-time alerts at candle 2 and 3 confirmations.
Now, let's take a broader view of the same chart. We have disabled the display of candle 2 and filtered the setups with a length of 50.
As we can see, most of the last 17 setups found on the EUR/USD daily chart lead to multi-day or multi-month price movements.
🔹 Filtering Reversals
The tool features a reversals filter that is disabled by default. This filter allows us to filter out minor reversals and display only those that are important.
Traders can adjust the length parameter to display reversals only at the top or bottom of the last N specified bars. We can see some examples in the chart.
🔹 Wick Threshold
From the settings panel, traders can fine-tune the equilibrium zone for candle 2.
If the wick exceeds the threshold expressed as a percentage of the total bar range, the equilibrium zone will be calculated based only on the wick. In all other cases, the full bar range will be used.
🔶 SETTINGS
Candle 2 (Reversal): Enable or disable Candle 2 reversals.
Candle 3 (Expansion): Enable or disable Candle 3 expansions.
Reversals Filter: Filter reversals as the highest or lowest of the last N bars.
Wick Threshold %: Filter wicks as percentage of total bar range.
🔹 Style
Bullish Color: Select bullish color.
Bearish Color: Select bearish color.
Transparency: Select the transparency level. 0 is solid and 100 is fully transparent.
Levels: Enable or disable the horizontal levels.
Candle 2 Zone: Enable or disable the Candle 2 equilibrium zones.
Candle 3 Zone: Enable or disable the Candle 3 equilibrium zones.
🔹 Alerts
Candle 2 Alerts: Enable or disable Candle 2 alerts.
Candle 3 Alerts: Enable or disable Candle 3 alerts.
Indicators and strategies
Hybrid Smart Money Concepts [MarkitTick]💡This indicator provides a comprehensive technical analysis system that combines Market Structure concepts (Smart Money Concepts) with advanced Gap Analysis and a statistical Stress Model. It is designed to help traders identify trend direction, structural pivot points, potential reversal zones (Order Blocks), significant price gaps, and moments of market exhaustion.
Unlike standard ZigZag or Fractal indicators, this script integrates volume, trend maturity, and statistical volatility (Z-Score) to contextually classify price action. By overlaying these elements with a robust Market Structure engine—which identifies Change of Character (CHoCH) and Order Blocks—the tool provides a confluent view of price action.
It automates the detection of institutional footprints, allowing traders to see the structural trend, momentum drivers, and potential exhaustion points simultaneously.
● METHODOLOGY
The script operates on three distinct but complementary logic engines:
• Gap Analysis Engine
This module detects gaps between the previous high/low and the current open. It classifies them into three specific types based on volume and structural context:
Breakaway Gaps: Identified when a gap creates a breakout above a recent Pivot High or below a Pivot Low. This signals the start of a potential new trend.
Exhaustion Gaps: Identified when a gap occurs with high relative volume and meets the Trend Maturity criteria. This often signals the end of a trend.
Runaway Gaps: Standard continuation gaps that occur within a trend.
• Market Structure Engine
Swings and CHoCH: The script uses a left-and-right bar lookback to identify Pivot Highs and Lows. A Change of Character (CHoCH) is plotted when price closes beyond the most recent major pivot.
Order Blocks (OB): Upon a continuation of the trend, the script scans backward to find the extreme candle (the origin of the move) and highlights this zone as an Order Block.
Dynamic Cleanup: Gaps and Order Blocks are automatically removed (mitigated) when price aggressively crosses through their levels.
• Exhaustion & Stress Model
This statistical engine measures market "Stress" by analyzing the impact of price range relative to volume (True Range / Volume).
Calculation: It calculates a Z-Score (Standard Deviation) of this impact.
Logic: When the Z-Score exceeds a specific threshold (Sigma), it indicates a statistical anomaly or "Stress."
Signal: If high stress occurs while price is significantly above the trend baseline, it signals "Buyer Exhaustion." Conversely, high stress below the baseline signals "Seller Exhaustion."
● VISUALS & LEGEND
Before trading, you need to know what the indicator is drawing on your chart:
• Change of Character (CHoCH)
Green Dashed Line: Indicates a Bullish reversal.
Red Dashed Line: Indicates a Bearish reversal.
• Order Blocks (OB)
Green Boxes: Bullish support zones (Buy interest).
Red Boxes: Bearish resistance zones (Sell interest).
Note: Invalidated boxes are automatically deleted.
• Gaps
Blue Box (Breakaway): Strong momentum gap starting a new trend.
Orange Box (Runaway): Continuation gap.
Red Box (Exhaustion): Warning signal; trend may be ending.
• Stress Model Signals
Label "BE" (Red): Buyer Exhaustion. Suggests the bullish move is overextended relative to volume participation.
Label "SE" (Green): Seller Exhaustion. Suggests the bearish move is overextended.
● TRADING STRATEGY
You can use a "Pullback, Continuation & Exhaustion" strategy with this indicator.
• Scenario A: Long Setup (Buying)
Trend Change: Look for a CHoCH label with a Green Dashed Line.
Entry Zone: Look for a Green Order Block (OB) to form.
Confirmation: A Breakaway Gap (Blue) validates the breakout.
Entry: Enter Long when price pulls back into the Green OB.
Exit Warning: If a "BE" (Buyer Exhaustion) label appears, consider tightening stops or taking profit.
• Scenario B: Short Setup (Selling)
Trend Change: Look for a CHoCH label with a Red Dashed Line.
Entry Zone: Look for a Red Order Block (OB) to form.
Confirmation: A Breakaway Gap downwards validates the move.
Entry: Enter Short when price rallies back into the Red OB.
Exit Warning: If an "SE" (Seller Exhaustion) label appears, consider tightening stops or taking profit.
● SETTINGS
• Date Range Filter
Use Date Filter: Toggle time-based filtering.
Start Date: Timestamp to begin calculations.
• Gap Analysis
Min Gap Size: Minimum points required to register a gap.
Logic Inputs: Configures lookback periods and volume multipliers for gap classification.
Visuals: Customize colors for Breakaway, Runaway, and Exhaustion gaps.
• Market Structure
Swing Detection Length: Lookback period for pivot points.
Show CHoCH: Toggle for Change of Character labels.
Show Order Blocks: Toggle for OB boxes.
• Exhaustion & Stress Model
Trend Filter Length: Baseline length for determining trend direction (EMA).
Statistical Lookback: Length for the Z-Score calculation.
Stress Threshold (Sigma): The standard deviation requirement to trigger an exhaustion signal (Default: 2.0).
● DISCLAIMER
All provided scripts and indicators are strictly for educational exploration and must not be interpreted as financial advice or a recommendation to execute trades. I expressly disclaim all liability for any financial losses or damages that may result, directly or indirectly, from the reliance on or application of these tools. Market participation carries inherent risk where past performance never guarantees future returns, leaving all investment decisions and due diligence solely at your own discretion.
Pivots MTF -WinCAlgo/// 🇬🇧
Pivots MTF -WinCAlgo is a precision-engineered Price Action tool designed to declutter your chart while providing a comprehensive view of market equilibrium points across multiple timeframes.
Unlike standard Pivot indicators that often flood the screen with too many lines or restrict you to a single timeframe, this tool consolidates Daily, Weekly, Monthly, Quarterly, and Yearly central pivots into a clean, "Step-Line" visual format with an intelligent status dashboard.
It is built for traders who focus on Bias and Equilibrium rather than just S/R lines.
1. Multi-Timeframe Central Pivots (Step-Line Technology)
* Displays Daily (D), Weekly (W), Monthly (M), Quarterly (Q), and Yearly (Y) pivots simultaneously.
* Infinite History: Uses a specialized plot logic instead of limited lines, allowing you to see the pivot history as far back as data exists without gaps.
* Step-Line Visual: Levels remain flat and constant throughout their respective periods (e.g., the Daily pivot draws as a straight line from 00:00 to 23:59), creating a clear "ladder" of price levels.
2. Intelligent Status Dashboard (Auto-Sorting)
* Smart Sorting: The on-chart table automatically sorts all active pivot levels by price (Highest to Lowest). This creates an instant "Support & Resistance Ladder" regardless of the timeframe.
* Dynamic Coloring: Levels in the table light up Green (Support) if the price is above them, or Red (Resistance) if the price is below.
* Touched vs. Naked: The table tracks whether price has tested the level in the current period. "Naked" levels (untested) often act as strong magnets for price action.
3. Optional Deviations (S1 / R1)
* Includes a toggle for Deviations (S1 & R1) for each timeframe.
* Calculated using classic pivot logic based on the previous period's Close:
- R1 = (2 * Pivot) - Low
- S1 = (2 * Pivot) - High
* Deviations are drawn as dashed lines to distinguish them from the main trend bias.
4. Performance & Customization
* History Limit: Adjustable history depth for line objects to ensure maximum chart performance.
* Hybrid Design: Combines the infinite history of plot drawings with the precision of line objects.
* Visual Control: Fully customizable colors, line widths, and table position/size.
* Trend Bias: If price is holding above the Daily and Weekly central pivots, the immediate bias is Bullish.
* Targeting: Use "Naked" pivots shown in the table as high-probability take-profit targets or reversal zones.
* Confluence: Look for areas where a higher timeframe pivot (e.g., Monthly) overlaps with a lower timeframe pivot (e.g., Daily) to identify critical structural levels.
Developed by WinCAlgo. Feel free to use and incorporate into your strategies.
Commodity Pulse Matrix v3 [WavesUnchained]Overview
Multi-Timeframe Confluence Indicator for Commodities. Combines 6 scoring categories across multiple timeframes with advanced entry timing and risk management.
Key Features
6-Category Scoring System
• Flow: Money flow and volume pressure
• Momentum: RSI, CCI, Rate of Change
• Trend: ADX, EMA alignment, directional movement
• Volatility: ATR-based market conditions
• Structure: Price position relative to key MAs
• Divergence: Price/indicator divergence detection
Multi-Timeframe Analysis
• Automatic TF hierarchy based on chart timeframe
• Entry/Bias/Trend from different timeframes
• Consensus scoring across all active TFs
• HTF confirmation mode (non-repainting)
Entry Engine
• Breakout entries with momentum confirmation
• Pullback entries at support/resistance
• Continuation entries in trending markets
• Counter-trend filter (optional)
• Signal density: Few / Moderate / Many
Diamond Zones
• Pivot-based support/resistance detection
• ATR-padded zone boundaries
• Zone strength scoring
• Visual boxes on chart
Signal Quality Gate
• ATR filter: No trend signals in ranging markets
• Volume filter: No entries on low volume
• Mean-reversion allowed in range markets
Heat Score System
• Setup quality assessment (0-1 scale)
• MTF alignment component
• Signal strength component
• Confluence component
Exhaustion Detection
• RSI extreme zones
• Large range candles (ATR expansion)
• High volume spikes
• Rejection wicks
• Small body candles
Mean Reversion System
• WaveTrend-based signals
• Dynamic overbought/oversold zones
• JMA smoothing for reduced lag
• Signal cooldown management
Risk Management
• ATR-based stop-loss calculation
• Multi-target take-profit levels
• Regime-aware position sizing
• Risk quality grading
Visualization
Matrix Table
• 6 category scores per timeframe
• Total score with color coding
• Setup status and confluence
• Heat score and confidence level
• TF action recommendations
Chart Elements
• JMA gradient fill (trend visualization)
• Diamond zone boxes (S/R levels)
• Signal shapes (triangles)
• Volatility stop lines
• HTF midline
• Pivot labels (S/R markers)
Configuration
Timeframes
• Confirmed HTF bars only (prevents repainting)
• Chart TF priority weight
Entry Engine
• Enable/disable entry types (Breakout/Pullback/Continuation)
• Allow counter-trend entries
• Trend JMA settings
• Volatility stop multiplier
Signal Boost
• RSI extreme boost
• WaveTrend extreme boost
• Strength threshold
Take-Profit
• Modes: Simple / Smart / Conservative / Multi-Target
• ATR multipliers for each level
• Regime-adjusted targets
Visualization
• Matrix table position and mode
• JMA lines and gradient
• Diamond zone boxes
• Pivot labels
• Signal age display
• Bottom area indicator
Mean Reversion
• WaveTrend smoothing lengths
• Zone lookback and multiplier
• Signal cooldown
• Show zones/labels/exits
TradingView Alerts
• Entry Long/Short signals
• Strong/Moderate signal differentiation
• Webhook compatible
Recommended Usage
1. Select chart timeframe (15M-Daily recommended)
2. Watch matrix table for MTF confluence
3. Wait for signal shapes on chart
4. Confirm with Heat Score (>0.5 = quality setup)
5. Check Diamond Zones for S/R context
6. Use ATR-based SL/TP from risk management
Input Groups
• Timeframes: HTF confirmation, chart weight
• Entry Engine: Entry types, density, JMA settings
• Signal Boost: RSI/WT boost settings
• Signal Quality: ATR/Volume thresholds
• Technical: ATR length, SL multiplier
• Take-Profit: Mode, ATR multiples, regime adjustment
• Visualization: Matrix, JMA, zones, labels
• HTF Midline: Mode, resolution, color
• Mean Reversion: WaveTrend settings, zones
• Colors: Bull/bear color scheme
---
Educational purposes only. Not financial advice. Test thoroughly before live trading.
tncylyv - Improved Delta Volume BubbleThis script is a specialized modification and structural upgrade of the excellent "Delta Volume Bubble " by tncylyv.
While the original tool provided a fantastic foundation for statistical volume analysis, this "Zero Float" Edition was built to solve specific visual challenges faced by active traders—specifically the issue of indicators "floating" or disconnecting from price when zooming in on lower timeframes.
The Straight Improvements
This version turns a "Signal Indicator" into a complete "Trading System" with five specific upgrades:
1. Visual Stability (The "Zero Float" Fix)
Original: Used complex coordinates that could desynchronize, causing bubbles to drift or float away from candles on fast charts (1m/5m).
My Upgrade: Implemented "Magnetic Anchoring." Labels and bubbles are now physically locked to the candle wicks. They never drift, overlap, or float, no matter how much you zoom or resize the chart.
2. Cognitive Load (The HUD)
Original: Displayed raw numbers inside colored circles, requiring you to memorize color codes.
My Upgrade: Replaced numbers with Semantic Text Labels (e.g., "ABSORB", "SQUEEZE", "MOMENTUM"). You can read the market intent instantly without decoding it.
3. Regime Adaptation (AI Engine)
Original: Used a fixed threshold (e.g., Z-Score > 2.0).
My Upgrade: Added an Adaptive Learning Window. The script scans recent volatility to automatically raise the threshold during choppy markets (filtering noise) and lower it during quiet sessions (catching subtle entries).
4. Market Memory (Smart Structure)
Original: Signals disappeared into history.
My Upgrade: Draws Support/Resistance Rails extending from major volume events. This helps you visualize exactly where institutions are defending their positions.
5. Robust Data Handling
My Upgrade: Added a Hybrid Fallback Engine. If granular 1-minute data isn't available (e.g., on historical charts), the script seamlessly switches to an estimation model so the indicator never "breaks" or disappears.
Core Logic
Z-Score Normalization: We don't look at raw volume; we look at statistical anomalies (Standard Deviations).
Absorption: Detects "Effort vs. Result"—high volume with tiny price movement (Trapped Traders).
Squeeze: Highlights areas where a breakout is imminent due to volatility compression.
Credits
Original Concept & Code: tncylyv (Delta Volume Bubble ). This script would not exist without his brilliant groundwork.
Modifications: Visual Anchoring, HUD Text System, AI Thresholding, and Structure Rails added in this edition.
This script is open-source to keep the spirit of the original author alive. Use it to understand the "Why" behind the move.
Bloomberg Terminal//@version=6
indicator("Bloomberg Terminal ", shorttitle="QUANTLABS", overlay=true, max_lines_count=500, max_labels_count=500)
// =============================================================================
// I. SETTINGS & THEME (ULTIMATE FIDELITY)
// =============================================================================
group_layout = "Terminal Layout"
sz_text = input.string(size.large, "Font Size", options= , group=group_layout)
pos_main = input.string(position.top_right, "Position", options= , group=group_layout)
group_colors = "Terminal Colors"
c_bg_main = color.black
c_bg_alt = color.rgb(15, 15, 15) // Subtle Zebra
c_amber = input.color(#ffb300, "Terminal Amber", group=group_colors)
c_header = input.color(#00294d, "Bloomberg Blue", group=group_colors)
c_bull = input.color(#00e676, " Terminal Green", group=group_colors)
c_bear = input.color(#ff1744, "Terminal Red", group=group_colors)
c_neutral = input.color(#b0bec5, "Terminal Gray", group=group_colors)
c_white = color.white
// =============================================================================
// II. DATA ENGINE & SPARKLINE LOGIC
// =============================================================================
type asset_data
float price
float chg
float rvol
bool is_up
float c1
float c2
float c3
f_get_stats(_sym) =>
= request.security(_sym, timeframe.period, [close, open, volume, ta.sma(volume, 20), close , close ], ignore_invalid_symbol=true)
_chg = (_c - _o) / _o * 100
asset_data.new(_c, _chg, _v / (_avg_v + 0.0001), _chg >= 0, _c, _c1, _c2)
// Market Data
d_spy = f_get_stats("AMEX:SPY")
d_qqq = f_get_stats("NASDAQ:QQQ")
d_iwm = f_get_stats("AMEX:IWM")
d_btc = f_get_stats("BINANCE:BTCUSDT")
d_eth = f_get_stats("BINANCE:ETHUSDT")
d_gold = f_get_stats("TVC:GOLD")
d_oil = f_get_stats("TVC:USOIL")
d_dxy = f_get_stats("TVC:DXY")
d_us10y = f_get_stats("TVC:US10Y")
d_vix = f_get_stats("CBOE:VIX")
// Active Ticker Intelligence
rsi = ta.rsi(close, 14)
= ta.supertrend(3, 10)
avg_vol = ta.sma(volume, 20)
rvol = volume / avg_vol
atr = ta.atr(14)
// Sparkline Generator (Text Based)
// We use simple block characters to simulate a "Trend"
// logic: if Price > Open -> Bullish Block, else Bearish Block.
// Ideally we'd have history but keeping it simple for now.
// Sparkline Generator (3-Bar Mini Chart)
// Sparkline char generator
f_spark_char(_p, _min, _rng) =>
_rel = (_p - _min) / (_rng == 0 ? 1 : _rng)
_rel < 0.33 ? " " : (_rel < 0.66 ? "▃" : "▇")
// Sparkline Generator (3-Bar Mini Chart)
f_spark(_d) =>
// Simple logic: Normalize 3 prices to choose low/med/high blocks
_min = math.min(_d.c1, math.min(_d.c2, _d.c3))
_max = math.max(_d.c1, math.max(_d.c2, _d.c3))
_rng = _max - _min
f_spark_char(_d.c2, _min, _rng) + f_spark_char(_d.c1, _min, _rng) + f_spark_char(_d.c3, _min, _rng)
// =============================================================================
// III. UI RENDERER (TEXT BASED TERMINAL)
// =============================================================================
// Table with thick outer frame but NO inner grid lines
var table term = table.new(pos_main, 4, 30, border_width=0, frame_width=2, frame_color=color.rgb(40,40,40), bgcolor=c_bg_main)
f_txt(_t, _c, _r, _txt, _col, _align, _bg) =>
table.cell(_t, _c, _r, _txt, text_color=_col, text_halign=_align, text_size=sz_text, bgcolor=_bg, text_font_family=font.family_monospace)
// Helper to print a row
// Helper to print a row with Zebra Striping
f_row(_row_idx, _name, _d) =>
_c_p = _d.is_up ? c_bull : c_bear
_bg_row = _row_idx % 2 == 0 ? c_bg_main : c_bg_alt // Zebra Logic
// Col 0: Ticker
f_txt(term, 0, _row_idx, _name, c_amber, text.align_left, _bg_row)
// Col 1: Price
f_txt(term, 1, _row_idx, str.tostring(_d.price, "#.##"), c_white, text.align_right, _bg_row)
// Col 2: Chg%
f_txt(term, 2, _row_idx, str.tostring(_d.chg, "+#.##") + "%", _c_p, text.align_right, _bg_row)
// Col 3: Spark (Simulated Trend)
f_txt(term, 3, _row_idx, f_spark(_d), _c_p, text.align_center, _bg_row)
if barstate.islast
// --- ROW 0: TOP MENU (F-Keys) - BLACK BG ---
_menu = " 1 2 3 4 5 6 7 8 9"
table.cell(term, 0, 0, _menu, text_color=c_amber, bgcolor=c_bg_main, text_halign=text.align_left, text_size=size.tiny, text_font_family=font.family_monospace)
table.merge_cells(term, 0, 0, 3, 0)
// --- ROW 1: BRANDING HEADER - BLACK BG ---
_time = str.format("{0,date,HH:mm:ss} EST", time)
// Simulated "BLOOMBERG" logo text + Time
f_txt(term, 0, 1, "QUANTLABS PROFESSIONAL | " + _time, c_amber, text.align_left, c_bg_main)
table.merge_cells(term, 0, 1, 3, 1)
// --- ROW 2: PANEL HEADERS - BLUE BG ---
f_txt(term, 0, 2, "SECURITY", c_white, text.align_left, c_header)
f_txt(term, 1, 2, "LAST PRICE", c_white, text.align_right, c_header)
f_txt(term, 2, 2, "NET CHANGE", c_white, text.align_right, c_header)
f_txt(term, 3, 2, "TREND", c_white, text.align_center, c_header)
// --- DATA ROWS (WATCHLIST) ---
f_row(3, "SPX Index", d_spy)
f_row(4, "NDX Index", d_qqq)
f_row(5, "RTY Index", d_iwm)
f_row(6, "VIX Index", d_vix)
// Separator
f_txt(term, 0, 7, ">> FX / CRYPTO", c_amber, text.align_left, color.new(c_header, 50))
table.merge_cells(term, 0, 7, 3, 7)
f_row(8, "BTCUSD Curncy", d_btc)
f_row(9, "ETHUSD Curncy", d_eth)
f_row(10, "DXY Curncy", d_dxy)
f_row(11, "XAU Curncy", d_gold)
// --- INTELLIGENCE SECTION ---
f_txt(term, 0, 12, ">> ACTIVE TICKER ANALYTICS", c_amber, text.align_left, color.new(c_header, 50))
table.merge_cells(term, 0, 12, 3, 12)
// Active Stats Row 1
f_txt(term, 0, 13, "RSI(14): " + str.tostring(rsi, "#.0"), c_white, text.align_left, c_bg_main)
c_rsi = rsi > 70 ? c_bear : (rsi < 30 ? c_bull : c_white)
f_txt(term, 1, 13, rsi > 70 ? "OVERBOUGHT" : (rsi < 30 ? "OVERSOLD" : "NEUTRAL"), c_rsi, text.align_right, c_bg_main)
// Active Stats Row 2
f_txt(term, 0, 14, "REL VOL(20): " + str.tostring(rvol, "#.1") + "x", c_white, text.align_left, c_bg_main)
c_vol = rvol > 2.0 ? c_amber : c_neutral
f_txt(term, 1, 14, rvol > 2.0 ? "HIGH ADVISE" : "NORMAL", c_vol, text.align_right, c_bg_main)
// Active Stats Row 3 (Merged)
_tr_txt = close > st_val ? "BULLISH TREND" : "BEARISH TREND"
c_tr = close > st_val ? c_bull : c_bear
f_txt(term, 0, 15, _tr_txt, c_tr, text.align_center, c_bg_main)
table.merge_cells(term, 0, 15, 3, 15)
// --- COMMAND LINE ---
// Blinking cursor effect
_blink = int(timenow / 500) % 2 == 0 ? "_" : " "
_cmd = "COMMAND: MONITOR " + syminfo.ticker + " " + _blink
f_txt(term, 0, 17, _cmd, c_amber, text.align_left, color.new(#222222,0))
table.merge_cells(term, 0, 17, 3, 17)
// --- NEWS TICKER (Multi-Line) ---
// We'll simulate a log by checking conditions
_msg1 = "SYSTEM READY..."
_msg2 = "MONITORING MARKETS..."
_msg3 = "NO ACTIVE ALERTS"
// Priority Alert Overwrite
if rvol > 3.0
_msg3 := ">> WHALE ALERT: VOL SPIKE <<"
else if rsi > 75
_msg3 := ">> EXTREME OB DETECTED <<"
else if rsi < 25
_msg3 := ">> EXTREME OS DETECTED <<"
// Render 3 lines of logs
f_txt(term, 0, 18, "LOG : " + _msg3, _msg3 == "NO ACTIVE ALERTS" ? c_neutral : c_amber, text.align_left, c_bg_main)
table.merge_cells(term, 0, 18, 3, 18)
f_txt(term, 0, 19, "LOG : " + _msg2, c_neutral, text.align_left, c_bg_main)
table.merge_cells(term, 0, 19, 3, 19)
f_txt(term, 0, 20, "LOG : " + _msg1, c_neutral, text.align_left, c_bg_main)
table.merge_cells(term, 0, 20, 3, 20)
S/R HTF (D + 4H) | Clusters+Pivots | Stable | Styles+AlertsThis indicator plots higher-timeframe Support/Resistance levels based on the Daily and 4-Hour charts, and keeps them stable (not dependent on how much history is loaded or how you scroll/zoom).
What it does
Daily levels (D) are calculated from the last lenD closed daily candles (default: 120).
4H levels (240) are calculated from the last lenH4 closed 4H candles (default: 300).
Levels come from two sources:
Clusters (value areas): prices where candle closes occur frequently within a narrow range.
The range width is derived from ATR × step multiplier.
Pivots: recent pivot highs and pivot lows (with left/right pivot settings).
The script merges nearby levels (within a tolerance) to avoid duplicates.
Stability / update logic
Levels are computed with request.security() on "D" and "240", so the result is independent of the chart timeframe you’re currently viewing.
Lines are drawn using bar time anchoring and extend mode, so they remain fixed to price and do not “jump” when you zoom or scroll.
Levels are recalculated on a calendar schedule (default: every 2 days, timeframe "2D"). Between recalculations, levels remain unchanged.
Visual customization
From the settings panel you can configure:
Show/hide Daily and/or 4H levels
Show/hide Clusters and/or Pivots
Line width for clusters and pivots
Line style (Solid / Dashed / Dotted) for clusters and pivots
Colors and opacity for Daily and 4H lines
Line extension: Left / Right / Both
Alerts
The indicator can trigger alerts when price:
Touches a level (bar range crosses the level: high >= level and low <= level)
Approaches a level (distance is within a threshold)
Approach threshold can be defined as:
Ticks
ATR multiplier
Percent of price
To use dynamic alert text (level + distance):
Create an alert in TradingView using: “Any alert() function call”.
Notes / limitations
“Last N candles” depends on available symbol history; if the symbol doesn’t have enough Daily/4H history, some levels may be na.
Cluster quality depends on ATR-based bin size; adjusting the step multipliers can improve results per instrument and volatility regime.
CRR Nemesis - Institutional Multi Layer Gold Decision SystemCRR Nemesis is an institutional multi-layer decision system designed specifically for XAUUSD scalping and intraday trading.
It is not a simple combination of indicators.
Nemesis is a structured permission-based engine that filters market conditions using hierarchical multi-timeframe logic, smart money structure, institutional timing, Fibonacci mitigation zones and candlestick power confirmation.
Instead of producing constant buy/sell signals, Nemesis creates trade permission states.
A trade is only allowed when all institutional layers agree.
System architecture
Multi-timeframe direction engine
Nemesis analyzes trend permission across 1m, 5m, 15m and 1D.
Lower timeframes must align with or not contradict higher-timeframe structure.
Smart money structure (SMC)
Tracks HH, HL, LH, LL sequences, break of structure (BOS), change of character (ChoCH) and internal swing ranges.
Institutional mitigation zones
Automatically draws bullish and bearish mitigation zones based on internal swing structure and ATR logic.
Fibonacci mitigation engine
Defines premium and discount areas (38.2%–78.6%) to identify institutional entry zones.
Anti-trap institutional filter
Blocks low-probability and retail-type entries, preventing buy traps and false momentum trades.
Institutional session timing engine
Uses real New York, London and Tokyo session timing to define high-probability trading windows.
Candlestick power confirmation
Validates entries using institutional candlestick behavior such as engulfing patterns, strong impulse candles and reversal structures.
Pro setup engine
Final pro buy and pro sell signals are only released when all layers are aligned.
How to use
• Use on XAUUSD
• Main execution timeframe: 1 minute
• Trade only during London and New York sessions
• Follow pro buy and pro sell labels
• Avoid trades when the system shows blocked conditions
Descripción en español
CRR Nemesis es un sistema institucional de decisión por capas diseñado para el scalping e intradía en XAUUSD.
No es un mashup de indicadores, sino un motor de permisos de entrada que filtra condiciones mediante estructura Smart Money, zonas de mitigación institucional, Fibonacci, sesiones reales y confirmación por velas.
Nemesis bloquea operaciones de baja probabilidad y libera setups pro solo cuando todas las capas institucionales están alineadas.
Single Candle Order Block (ICT) [Kodexius]Single Candle Order Block (ICT) is a chart-focused implementation of the ICT style Single Candle Order Block (SCOB) concept. It detects a strict 3 candle displacement pattern and projects the originating “order block candle” as a live zone that extends forward in time until price mitigates it.
The script is designed for practical trading workflows:
- It plots only the most recent active zones (user-defined limit) to keep charts readable.
- It supports optional multi-timeframe (MTF) detection, so you can project higher-timeframe SCOBs onto a lower-timeframe execution chart.
- It includes a mitigation engine (Close or Wick) to automatically invalidate and remove zones once they are decisively broken.
🔹 Features
🔸 ICT Single Candle Order Block Pattern Detection (Bull and Bear)
The indicator identifies a clean displacement sequence that implies a potential order block formed by the middle candle of a 3-candle structure.
Bullish SCOB: bearish candle at , bullish continuation at , then bullish displacement that closes above the prior candle’s high, with a sweep condition on the order block candle’s low.
Bearish SCOB: inverse structure requiring bearish displacement that closes below the prior candle’s low, with a sweep condition on the order block candle’s high.
The plotted zone boundaries are derived from the order block candle:
Top = high
Bottom = low
🔸 Multi-Timeframe Detection (Optional)
The script can compute SCOBs on a selected timeframe and display them on the current chart using request.security. This is ideal for mapping higher-timeframe order blocks onto lower-timeframe execution charts.
If the timeframe input is left empty, detection runs on the chart timeframe.
🔸 Volatility Filter (Optional)
When enabled, detections are filtered by volatility regime:
A SCOB is only displayed if ATR(14) > SMA(ATR(14), 200)
This helps reduce signals during compressed, low-range conditions where displacement patterns are often less meaningful.
🔸 Overlap Control (De-Cluttering)
Before a new zone is added, the script checks for overlap against existing zones of the same direction. If the new zone intersects an existing one, it is ignored. This reduces redundant stacking of zones in the same price area.
🔸 Mean Threshold (50%) Midline (Optional)
Each active SCOB is drawn as a semi-transparent box with:
Direction label text (Bu-SCOB / Be-SCOB)
Optional midpoint line at 50% of the zone height (Mean Threshold)
🔸 Automatic Zone Extension and Object Management
Zones extend forward on each bar to remain visible until mitigation. The script also manages object count and chart cleanliness by:
Keeping internal arrays for bull and bear zones
Removing older stored zones if internal history grows too large
Displaying only the most recent “Active SCOB Limit” zones while hiding older ones
🔸 Alerts
Alerts are provided for newly confirmed detections:
Bullish SCOB Detected
Bearish SCOB Detected
Duplicate prints are prevented by tracking the last detected zone time for each direction.
🔹 Calculations
1) Volatility Regime Check (ATR vs ATR SMA)
float myAtr = ta.atr(14)
float atrSma = ta.sma(myAtr, 200)
bool isVolatile = myAtr > atrSma
If the Volatility Filter is enabled, the script requires isVolatile to be true before creating a SCOB zone.
2) Bullish SCOB Detection Logic
bool isBull = open > close and close > open and close > open and low < low and close > high
Interpretation of the conditions:
open > close confirms the candle at is bearish.
close > open confirms the order block candle at is bullish.
close > open confirms current candle is bullish.
low < low indicates a relative sweep on the order block candle’s low.
close > high confirms displacement by closing above the order block candle’s high.
Zone bounds for a bullish SCOB come from candle :
[isBull, high , low , time , isBear, high , low , time , isVolatile]
3) Bearish SCOB Detection Logic
bool isBear = open < close and close < open and close < open and high > high and close < low
Interpretation of the conditions:
open < close confirms the candle at is bullish.
close < open confirms the order block candle at is bearish.
close < open confirms current candle is bearish.
high > high indicates a relative sweep on the order block candle’s high.
close < low confirms displacement by closing below the order block candle’s low.
Zone bounds for a bearish SCOB also come from candle :
[isBull, high , low , time , isBear, high , low , time , isVolatile]
4) Multi-Timeframe (MTF) Selection
The script runs the detection logic on the chosen timeframe and projects results onto the current chart:
=
request.security(syminfo.tickerid, i_tf, detectLogic())
It also prevents duplicate zone creation by checking the last processed detection time:
var int lastBullTime = 0
var int lastBearTime = 0
if mtf_isBull and mtf_bullTime != lastBullTime
lastBullTime := mtf_bullTime
if mtf_isBear and mtf_bearTime != lastBearTime
lastBearTime := mtf_bearTime
5) Overlap Validation
Before pushing a new zone, overlap is checked against existing zones:
if volPass and not bullArray.hasOverlap(mtf_bullTop, mtf_bullBot)
SCOB newScob = SCOB.new(top = mtf_bullTop, bottom = mtf_bullBot, barStart = mtf_bullTime, isBull = true)
bullArray.push(newScob)
if volPass and not bearArray.hasOverlap(mtf_bearTop, mtf_bearBot)
SCOB newScob = SCOB.new(top = mtf_bearTop, bottom = mtf_bearBot, barStart = mtf_bearTime, isBull = false)
bearArray.push(newScob)
6) Mitigation Logic (Close vs Wick)
Mitigation is evaluated every bar. Bullish zones mitigate below the bottom; bearish zones mitigate above the top:
method isMitigated(SCOB this, string style, float currentClose, float currentHigh, float currentLow) =>
bool mitigated = false
if this.isBull
float price = style == "Close" ? currentClose : currentLow
mitigated := (price < this.bottom)
else
float price = style == "Close" ? currentClose : currentHigh
mitigated := (price > this.top)
mitigated
Time Exhaustion Counter PRO (Confirmed Exit / Clean)🔹 Short Description (Very Short)
Time-based exhaustion indicator that confirms exits using pivots and ATR filtering. Designed to avoid premature exits and reduce market noise.
🔹 Release Notes (Version 1.0)
Version 1.0 – Initial Release
Time-based exhaustion counting from confirmed pivots
Confirmed exit logic (target bars + opposite pivot)
Automatic presets by timeframe (crypto-friendly)
ATR-based pivot filtering to reduce noise
Clean chart design with optional debug tools
ATR-Normalized VWMA DeviationThis indicator measures how far price deviates from the Volume-Weighted Moving Average ( VWMA ), normalized by market volatility ( ATR ). It identifies significant price reversal points by combining price structure and volatility-adjusted deviation behavior.
The core idea is to use VWMA as a dynamic trend anchor, then measure how far price travels away from it relative to recent volatility . This helps highlight when price has stretched too far and may be due for a reversal or pullback.
How it works:
VWMA deviation is calculated as the difference between price and the VWMA.
That deviation is divided by ATR (Average True Range) to normalize for current volatility.
The script tracks the highest and lowest normalized deviations over the chosen lookback period.
It also tracks price structure (highest/lowest highs/lows) over the same period.
A reversal signal is generated when a historical extreme in deviation aligns with a price structure extreme, and a confirmed reversal candle forms.
You get visual signals and color highlights where these conditions occur.
Settings explained:
Lookback period defines how many bars the script uses to find recent extremes.
ATR length controls how volatility is measured.
VWMA length controls how the volume-weighted moving average is calculated.
Signal filters help refine entries based on price vs deviation behavior.
Display options let you customize how signals and levels appear on the chart.
This indicator is especially useful for spotting potential turning points where price has moved far from VWMA relative to volatility, suggesting possible exhaustion or overextension.
Tips for use:
Combine with broader trend context (higher timeframe support/resistance).
Use with risk management rules (position sizing, stops) — signals are guides, not guaranteed entries.
Adjust lookback and ATR settings based on your trading timeframe and asset volatility.
SVP + candle + Max volume [midst]
SVP + DALY CANDLE + MAX VOLUME
A comprehensive trading indicator that combines Session Volume Profile (SVP), Higher Timeframe (HTF) Candles, and Intrabar Max Volume Price Detection into one powerful tool. Perfect for traders who want to understand price action, volume distribution, and key levels all in one place.
KEY FEATURES
Session Volume Profile
• Real-time volume distribution across price levels for the current session
• Point of Control (POC) - identifies the price with the highest traded volume
• Value Area High (VAH) & Low (VAL) - shows where 70% of the volume occurred (customizable percentage)
• Color-coded volume bars - distinguish between up volume (bullish) and down volume (bearish)
• Value area highlighting - clearly see the most important price zones
Higher Timeframe Candle Display
• Visual daily (or custom timeframe) candle overlaid on your current chart
• OHLC labels - see Open, High, Low, and Close prices clearly marked
• Fully customizable colors - separate colors for bullish/bearish bodies, borders, and wicks
• Adjustable positioning - move the candle and labels to your preferred location
Max Volume Price Detection
• Identifies the exact price level with maximum volume within each bar
• Uses Lower Timeframe (LTF) data for precise volume analysis (Premium+ required)
• Simple mode fallback - works on all TradingView plans
• Previous max volume marker - displays previous bar's max volume as a reference dot
• Real-time calculation - updates as each bar forms
ATR Table
• Dynamic ATR-based stop levels - automatically calculates potential stop-loss levels
• Multiple smoothing methods - RMA, SMA, EMA, WMA
• Customizable multiplier - adjust for your risk tolerance
• Clean table display - shows ATR value, high stop, and low stop
PERFECT FOR
Day traders analyzing intrabar volume distribution
Swing traders wanting HTF context on lower timeframes
Volume profile traders looking for key support/resistance levels
Price action traders seeking high-probability entry zones
HOW TO USE
Volume Profile Analysis
POC often acts as a magnet for price. VAH/VAL are key support/resistance levels. High volume nodes indicate strong price acceptance, while low volume nodes suggest potential breakout zones.
HTF Candle Context
See daily range while trading on 5m-1h charts. Daily open often acts as pivot point. Daily high/low are key levels to watch.
Max Volume Price
Black line shows where most volume traded in each bar. Previous max volume (dot) helps identify institutional activity. Clusters of max volume create strong support/resistance. Can possibly indicate a Wick bounce
ATR Stops
Use ATR-based levels for logical stop placement. Adjust multiplier based on market volatility.
SETTINGS & CUSTOMIZATION
Positioning
Control the global offset to move both candle and profile together. Fine-tune with individual offsets for candle and profile spacing.
Volume Profile
Adjustable number of rows (50-500) for granular or simplified view. Customizable width and placement (left/right). Value Area percentage control. Full color customization for all volume components.
HTF Candle
Any timeframe selection (default: Daily). Full color customization for bull/bear candles. Adjustable candle width. Toggle OHLC labels on/off. Control label distance and line widths.
Max Volume Price
Choose between Simple (all plans) or LTF mode (Premium+). Auto or manual LTF resolution. Custom color and line width. Toggle current and previous markers independently.
TECHNICAL NOTES
Maximum 5000 bars lookback for volume calculations
Works on all timeframes
LTF max volume requires TradingView Premium or higher
Optimized for performance with efficient array operations
For best results, use on liquid instruments with reliable volume data
Most effective on intraday charts (5min-1hour) for day trading and scalping strategies
For Entertainment and information only
Created by midst
Supply & Demand Zones (Volume-Based)📌 Supply & Demand Zones (Volume-Based) — Indicator Description
Overview
This indicator visually highlights potential supply and demand price zones using historical candle structure combined with relative volume behavior.The zones are intended to help users observe areas of increased market activity where price has previously reacted. This tool is designed for visual analysis only.
How the Zones Are Identified
Demand zones are highlighted when price shows a strong bullish reaction following a bearish candle.Supply zones are highlighted when price shows a strong bearish reaction following a bullish candle.Relative volume is used as context, not as a predictive input, to classify zones into higher or lower activity levels.Zones automatically invalidate when price structurally breaks them.
About the Percentage Display
The percentage shown on a zone represents normalized relative volume strength at the time the zone was formed.This value is not a probability, not a success rate, and not a performance metric.It should not be interpreted as a prediction or trading signal.Percentages are displayed only for active zones and are removed once a zone is invalidated.
How This Indicator Is Intended to Be Used
As a visual reference tool for identifying historical supply and demand areas.As a contextual overlay alongside other forms of technical analysis.To observe how price behaves when revisiting previously active zones.This indicator does not suggest trade direction, entry timing, or exit levels.
Important Notes & Limitations
All zones are derived from historical price and volume data.Market conditions change, and historical zones may lose relevance over time.No trading decisions should be made based solely on this indicator.Users are encouraged to apply their own analysis and risk management.
Disclaimer
This indicator is provided for educational and informational purposes only.It does not constitute trading, investment, or financial advice.The author assumes no responsibility for decisions made using this tool.
TradeFly CVDTradeFly CVD is a clean visualization of TradingView’s native Cumulative Volume Delta, combining CVD candles with a smoothed CVD line for improved trend and slope readability.
The indicator is designed to highlight volume participation, absorption, and divergence relative to price, using TradingView’s built-in volume delta methodology.
Best used as a context and confirmation tool alongside price structure, key levels, and session analysis — not as a standalone trading system.
*Note* - If you do not see the CVD when switching timeframes go into the settings and select the focus toggle. That will bring the CVD back into focus and then you can expand the zoom level to adjust the size displayed on the main chart.
Kalman Hull Kijun [BackQuant]Kalman Hull Kijun
A trend baseline that merges three ideas into one clean overlay, Kalman filtering for noise control, Hull-style responsiveness, and a Kijun-like Donchian midline for structure and bias.
Context and lineage
This indicator sits in the same family as two related scripts:
Kalman Price Filter
This is the foundational building block. It introduces the Kalman filter concept, a state-estimation algorithm designed to infer an underlying “true” signal from noisy measurements, originally used in aerospace guidance and later adopted across robotics, economics, and markets.
Kalman Hull Supertrend
This is the original script made, which people loved. So it inspired me to create this one.
Kalman Hull Kijun uses the same core philosophy as the Supertrend variant, but instead of building a Supertrend band system, it produces a single structural baseline that behaves like a Kijun-style reference line.
What this indicator is trying to solve
Most trend baselines sit on a bad trade-off curve:
If you smooth hard, the line reacts late and misses turns.
If you react fast, the line whipsaws and tracks noise.
Kalman Hull Kijun is designed to land closer to the middle:
Cleaner than typical fast moving averages in chop.
More responsive than slow averages in directional phases.
More “structure aware” than pure averages because the baseline is range-derived (Kijun-like) after filtering.
Core idea in plain language
The plotted line is a Kijun-like baseline, but it is not built from raw candles directly.
High level flow:
Start with a chosen price stream (source input).
Reduce measurement noise using Kalman-style state estimation.
Add Hull-style responsiveness so the filtered stream stays usable for trend work.
Build a Kijun-like baseline by taking a Donchian midpoint of that filtered stream over the base period.
So the output is a single baseline that is intended to be:
Less jittery than a simple fast MA.
Less laggy than a slow MA.
More “range anchored” than standard smoothing lines.
How to read it
1) Trend and bias (the primary use)
Price above the baseline, bullish bias.
Price below the baseline, bearish bias.
Clean flips across the baseline are regime changes, especially when followed by a hold or retest.
2) Retests and dynamic structure
Treat the baseline like dynamic S/R rather than a signal generator:
In uptrends, pullbacks that respect the baseline can act as continuation context.
In downtrends, reclaim failures around the baseline can act as continuation context.
Repeated back-and-forth around the line usually means compression or chop, not clean trend.
3) Extension vs compression (using the fill)
The fill is meant to communicate “distance” and “pressure” visually:
Large separation between price and baseline suggests expansion.
Price compressing into the baseline suggests rebalancing and decision points.
Inputs and what they change
Kijun Base Period
Controls the structural memory of the baseline.
Higher values track broader swings and reduce flips.
Lower values track tighter swings and react faster.
Kalman Price Source
Defines what data the filter is estimating.
Close is usually the cleanest default.
HL2 often “feels” smoother as an average price.
High/Low sources can become more reactive and less stable depending on the market.
Measurement Noise
Think of this as the main smoothness knob:
Higher values generally produce a calmer filtered stream.
Lower values generally produce a faster, more reactive stream.
Process Noise
Think of this as adaptability:
Higher values adapt faster to changing conditions but can get twitchy.
Lower values adapt slower but stay stable.
Plotting and UI (what you see on chart)
1) Adaptive line coloring
Baseline turns bullish color when price is above it.
Baseline turns bearish color when price is below it.
This makes the state readable without extra panels.
2) Gradient “energy” fill
Bull fill appears between price and baseline when above.
Bear fill appears between price and baseline when below.
The goal is clarity on separation and control, not decoration.
3) Rim effect
A subtle band around price that only appears on the active side.
Helps highlight directional control without hiding candles.
4) Candle painting (optional)
Candles can be colored to match the current bias.
Useful for scanning many charts quickly.
Disable if you prefer raw candles.
Alerts
Long state alert when price is above the baseline.
Short state alert when price is below the baseline.
Best used as a bias or regime notification, not a standalone entry trigger.
Where it fits in a workflow
This is a context layer, it pairs well with:
Market structure tools, BOS/MSB, OBs, FVGs.
Momentum triggers that need a regime filter.
Mean reversion tools that need “do not fade trends” context.
Limitations
No baseline eliminates chop whipsaws, tuning only manages the trade-off.
Settings should not be copy pasted across assets without checking behavior.
This does not forecast, it estimates and smooths state, then expresses it as a structural baseline.
Disclaimer
Educational and informational only, not financial advice.
Not a complete trading system.
If you use it in any trading workflow, do proper backtesting, forward testing, and risk management before any live execution.
Megvie Scalping C - Pullback EMA20/50 (3-5m)/@version=5
indicator("Megvie Scalping C - Pullback EMA20/50 (3-5m)", overlay=true, max_labels_count=500, max_lines_count=500)
// === INPUTS ===
ema_fast_len = input.int(20, "EMA fast (pullback)")
ema_slow_len = input.int(50, "EMA slow (trend)")
rsi_len = input.int(14, "RSI length")
rsi_min = input.int(40, "RSI min for entry")
atr_len = input.int(14, "ATR length (for SL/TP)")
use_atr_for_sl = input.bool(true, "Use ATR for SL size")
atr_sl_mult = input.float(1.0, "SL = ATR * multiplier", step=0.1)
rr = input.float(1.8, "Risk:Reward (TP = SL * RR)", step=0.1)
max_signals_repeat = input.int(3, "Min bars between signals", minval=1)
// === INDICATORS ===
ema_fast = ta.ema(close, ema_fast_len)
ema_slow = ta.ema(close, ema_slow_len)
rsi = ta.rsi(close, rsi_len)
atr = ta.atr(atr_len)
plot(ema_fast, color=color.new(color.green, 0), title="EMA 20")
plot(ema_slow, color=color.new(color.red, 0), title="EMA 50")
// === TREND FILTER ===
trend_bull = ema_fast > ema_slow
trend_bear = ema_fast < ema_slow
// === PULLBACK CONDITION ===
// Consider a pullback when price traded at/under EMA20 within the last 3 bars and now shows a bullish/bearish confirmation
pullback_bull = ta.lowest(low, 3) <= ema_fast and close > ema_fast
pullback_bear = ta.highest(high, 3) >= ema_fast and close < ema_fast
// === CONFIRMATION CANDLE ===
// Bullish confirmation: current close > open AND close > high (strong close)
// Bearish confirmation: current close < open AND close < low
bullish_candle = close > open and close > high
bearish_candle = close < open and close < low
// === ENTRY SIGNALS (Version C logic) ===
buySignal = trend_bull and pullback_bull and rsi >= rsi_min and bullish_candle
sellSignal = trend_bear and pullback_bear and rsi <= (100 - rsi_min) and bearish_candle
// Prevent firing signals too often
var int lastSignalBar = na
ok_to_fire = na(lastSignalBar) ? true : (bar_index - lastSignalBar) > max_signals_repeat
buyFire = buySignal and ok_to_fire
sellFire = sellSignal and ok_to_fire
if buyFire
lastSignalBar := bar_index
if sellFire
lastSignalBar := bar_index
// === SL / TP CALCULATION ===
var float sl_price = na
var float tp_price = na
var line sl_line = na
var line tp_line = na
var label sig_label = na
if buyFire
if use_atr_for_sl
sl_price := close - atr * atr_sl_mult
else
sl_price := ta.lowest(low, 3) - syminfo.mintick * 5
tp_price := close + (close - sl_price) * rr
// draw lines and label
line.delete(sl_line )
line.delete(tp_line )
label.delete(sig_label )
sl_line := line.new(bar_index, sl_price, bar_index + 50, sl_price, color=color.new(color.red, 0), width=1, extend=extend.right)
tp_line := line.new(bar_index, tp_price, bar_index + 50, tp_price, color=color.new(color.green, 0), width=1, extend=extend.right)
sig_label := label.new(bar_index, low, "BUY SL:" + str.tostring(sl_price, format.mintick) + " TP:" + str.tostring(tp_price, format.mintick), style=label.style_label_up, color=color.new(color.green,0), textcolor=color.white, size=size.small)
if sellFire
if use_atr_for_sl
sl_price := close + atr * atr_sl_mult
else
sl_price := ta.highest(high, 3) + syminfo.mintick * 5
tp_price := close - (sl_price - close) * rr
// draw lines and label
line.delete(sl_line )
line.delete(tp_line )
label.delete(sig_label )
sl_line := line.new(bar_index, sl_price, bar_index + 50, sl_price, color=color.new(color.red, 0), width=1, extend=extend.right)
tp_line := line.new(bar_index, tp_price, bar_index + 50, tp_price, color=color.new(color.green, 0), width=1, extend=extend.right)
sig_label := label.new(bar_index, high, "SELL SL:" + str.tostring(sl_price, format.mintick) + " TP:" + str.tostring(tp_price, format.mintick), style=label.style_label_down, color=color.new(color.red,0), textcolor=color.white, size=size.small)
// === PLOT SIGNAL ARROWS ===
plotshape(buyFire, title="Buy Signal", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small, text="BUY")
plotshape(sellFire, title="Sell Signal", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small, text="SELL")
// === ALERTS ===
alertcondition(buyFire, title="BUY Signal", message="Megvie C: BUY signal. SL: {{plot_0}} TP: {{plot_1}}")
alertcondition(sellFire, title="SELL Signal", message="Megvie C: SELL signal. SL: {{plot_0}} TP: {{plot_1}}")
alertcondition(ta.cross(close, tp_price), title="TP Hit", message="Megvie C: TP reached")
alertcondition(ta.cross(close, sl_price), title="SL Hit", message="Megvie C: SL reached")
// === NOTES ===
// - Optimized for 3-5 minute charts.
// - Test in paper trading before using real capital.
// - Adjust ATR multiplier and RR to match your risk management.
Interest Zones ScannerThis indicator automatically scans a user-defined price range (on current or higher timeframe) to detect and plot the strongest horizontal support/resistance zones based on validated price reactions. It intelligently identifies levels where price has repeatedly bounced without breaking for a specified number of bars, prioritizing high-probability reaction areas.
How It Works (Technical Methodology)
Range Calculation
The script determines the high/low range using a configurable method:
"Lookback Bars": User-defined number of bars (default 400) on the target timeframe.
"Fixed Start Date": Bars since a specified date (default dynamic).
Data is fetched via request.security() from a selectable timeframe (default current chart TF) for multi-timeframe alignment.
Auto Mode Scanning
When enabled:
Scans the entire range in small percentage steps (default 1.0%, adjustable down to 0.5%).
For each potential level, creates a thin volatility-adjusted zone (height % of price, default 0.07%).
Counts "valid hits": Instances where price touches the zone and holds (no break) for user-defined bars (default 10).
Break detection: Configurable "Close" (strict) or "Wick" (sensitive).
Assumes support/resistance direction based on close relative to zone center.
Level Selection and Filtering
Ranks candidates by hit count (highest first).
Applies minimum distance filter (% apart, default 8%) to avoid clustering.
Limits to user-defined max zones (default 9) for clean display.
Sorts final zones from low to high price.
Manual Mode Alternative
When auto disabled: Directly uses user-input percentages (e.g., classic Fibo levels like 23.6, 50, 61.8) applied to the range – no validation/scoring.
Zone Construction
Horizontal boxes centered on validated levels, with dynamic height (% of price).
Colored by position: Supply (above close, default light gray), Demand (below close, default cyan).
Optional full extension (both sides) or right-only.
Labeled with percentage from range low.
Dashboard and Visuals
Table (positionable) shows:
% Level, Exact Price, Hit Count (green if >3).
Header with validation details and lookback info.
Vertical line marks range start for reference.
How to Use
This scanner excels at finding statistically validated horizontal zones where price has shown respect – ideal for support/resistance, mean reversion, or breakout setups.
Auto Mode: Best for discovering hidden/non-obvious levels. Higher hit counts = stronger zones (expect reactions/retests).
Validation Bars: Increase (e.g., 20+) for stricter, higher-quality zones in trending markets; lower for more sensitive detection.
Min Distance: Higher % for fewer, separated zones; lower for denser grids.
Multi-Timeframe: Set target TF higher (e.g., Daily) for major structural levels on lower charts.
Supply Zones (Above Price): Potential resistance – shorts or take-profits.
Demand Zones (Below Price): Potential support – longs or stops below.
Confluence: Combine with volume, order blocks, or fibo for entries. Watch for multiple hits + confluence.
Manual Mode: Quick plotting of custom % (e.g., fibo retracements/extensions).
Fine-tune scan step smaller for precision (slower on large lookbacks) or larger for speed.
Disclaimer
This indicator is a technical analysis tool and should be used in conjunction with other forms of analysis. Past performance does not guarantee future results. Always use proper risk management.
Volatility Regimes | GainzAlgo📊 OVERVIEW
This is a comprehensive ATR-based trading system designed for professional traders who need advanced volatility analysis, precise trade management, and intelligent market-regime detection.
The indicator combines multiple proven volatility concepts into one powerful, highly customizable tool.
⚙️ CORE FEATURES
1️⃣ ATR BANDS (Dynamic Support & Resistance)
- Three levels of ATR-based bands plotted around price
- Band 1 (1× ATR): Closest support/resistance, primary TP target
- Band 2 (2× ATR): Secondary TP target, stronger S/R zone
- Band 3 (3× ATR): Extended TP target, major S/R level
- Bands adapt to volatility in real time
- Dotted lines mark TP points on the latest candle
2️⃣ VOLATILITY REGIME DETECTION (Market Phase Analysis)
Automatically classifies the market into four distinct volatility regimes:
🟢 COMPRESSION
ATR < 70% of baseline
Low-volatility consolidation, market is coiling
Best for: Preparing breakouts, tightening stops
🟠 EXPANSION
ATR 115–140% of baseline
Volatility breakout, early trend formation
Best for: Breakout entries, momentum trades
🔴 HIGH VOLATILITY
ATR > 140% of baseline
Strong sustained trend, maximum participation
Best for: Trend following, trailing stops
🟣 EXHAUSTION
Declining ATR after high volatility
Trend maturity, potential pause or reversal
Best for: Profit taking, reducing exposure
Additional details:
- Uses ATR Ratio (Current ATR / Long-term Baseline)
- Non-repainting logic with historical confirmation
- Background shading + regime labels for instant clarity
- Diamond markers highlight regime changes
3️⃣ DYNAMIC STOP-LOSS SYSTEM
- Automatically calculates optimal stop distance using ATR
- Adapts to current market volatility
- Separate logic for bullish and bearish trades
- Default 2× ATR multiplier (adjustable 0.5× – 5×)
- Visual cross markers display stop levels
- Tighter stops in low volatility, wider in high volatility
4️⃣ MULTIPLE TAKE-PROFIT LEVELS (TP1 / TP2 / TP3)
- Three progressive profit targets for scaling out
- TP1 (1.5× ATR): First partial profit
- TP2 (2.5× ATR): Secondary scale-out
- TP3 (4.0× ATR): Final target or runner
- Dashed lines with labels on the current bar
- Automatically aligns with trend direction
- Fully customizable multipliers
5️⃣ SUPPORT & RESISTANCE LEVELS
- Dynamic S/R detection using price extremes
- ATR-weighted significance filtering
- Adjustable lookback period (10–100 bars)
- Circle markers for visual clarity
- Updates in real time as new highs/lows form
6️⃣ RISK MANAGEMENT CALCULATOR
- Real-time position-size calculation
- Based on account size, risk percentage, and ATR stop distance
- Formula: Position Size = Risk Amount ÷ Stop Distance
- Example: $10,000 account, 1% risk, $50 stop = 200 shares
- Displays position size and dollar risk directly on chart
- Ensures consistent risk across all trades
7️⃣ ATR PERCENTILE RANKING
- Shows where current ATR ranks historically (0–100%)
- Above 80%: Extremely high volatility
- 20–80%: Normal volatility
- Below 20%: Extremely low volatility
- Adjustable lookback (50–500 bars)
- Alerts trigger at above 90% and below 10% extremes
- Adds context to all regime-based decisions
8️⃣ VOLATILITY CONTRACTION PATTERN
- Detects tight consolidation (volatility squeeze)
- Requires consecutive bars of low ATR
- Default: 7 bars below 50% of average ATR
- Yellow triangle alert when pattern completes
- Often precedes strong breakout moves
- Works on all timeframes
9️⃣ TREND DETECTION SIGNALS
- Up and down arrows on trend change with rising ATR
- Combines price direction with volatility confirmation
- Smoothing filters reduce false signals
- Green arrow for bullish, red arrow for bearish
🔟 VOLATILITY BREAKOUT SIGNALS
- Circle markers when ATR exceeds threshold
- Default threshold: 1.5× ATR average
- Indicates surge in market activity
- Can signal the start of new trends
🧠 RECOMMENDED SETTINGS BY TRADING STYLE
Day Trading (1m–15m)
ATR Length: 14
Regime Baseline: 30
SL Multiplier: 1.5–2.0
TP: 1.5 / 2.5 / 4.0
Risk: 0.5–1%
Swing Trading (1H–4H)
ATR Length: 14
Regime Baseline: 50
SL Multiplier: 2.0–2.5
TP: 2.0 / 3.5 / 6.0
Risk: 1–2%
Position Trading (Daily)
ATR Length: 14–21
Regime Baseline: 100
SL Multiplier: 2.5–3.0
TP: 3.0 / 5.0 / 8.0
Risk: 2–3%
Scalping (15s–5m)
ATR Length: 10
Regime Baseline: 20
SL Multiplier: 1.0–1.5
TP: 1.0 / 1.5 / 2.5
Risk: 0.5–1%
🧭 HOW TO USE
1. Identify the current volatility regime
2. Wait for entry confirmation (breakouts, trend arrows, contraction patterns)
3. Set stop loss using dynamic ATR-based levels
4. Scale out at TP1, TP2, TP3 or use ATR bands
5. Use the risk calculator for consistent position sizing
6. Monitor regime changes and manage exposure accordingly
🚨 ALERT SYSTEM
Alerts included for volatility breakouts, trend changes, regime transitions, ATR band crosses, contraction pattern completion, and ATR percentile extremes.
All alerts are fully configurable in TradingView.
🎨 VISUAL GUIDE
Background colors: Volatility regimes
Solid lines: ATR bands
Dotted lines: Latest TP points
Dashed lines: Take-profit levels
Cross markers: Stop-loss levels
Circles: Support, resistance, and breakouts
Arrows: Trend direction
Diamonds: Regime changes
Triangles: Contraction alerts
Labels: Regime info, ATR percentile, position size
🛠️ CUSTOMIZATION
- Toggle any feature on or off
- Adjust all thresholds and multipliers
- Customize colors
- Configure alerts
- Set account size and risk parameters
⚠️ IMPORTANT NOTES
- This indicator provides analytical tools, not trading signals
- Always apply proper risk management
- Backtest before live use
- ATR adapts to volatility, not direction
If you find this indicator useful, please leave a rating and comment ⭐
Diagonal Interest Zones ScannerThis indicator automatically scans and plots diagonal (slanted) interest zones – dynamic trend-parallel channels that identify statistically validated support/resistance levels within a trending price structure. It detects the strongest "bounce" zones where price has repeatedly respected slanted lines without breaking for a specified hold period, ideal for trending markets.
How It Works (Technical Methodology)
Trend Channel Detection
The script calculates a linear trend slope from a user-defined anchor point (start of lookback or fixed date) to the current close.
Range is determined by finding the maximum deviation above/below this trend line over the lookback period.
This creates a "channel envelope" capturing the full price oscillation around the trend.
Data can be sourced from current or higher timeframe for structural alignment.
Stable Update Mechanism
To prevent flickering on live bars:
Full recalculation (scanning + slope) occurs only after user-defined "Update Frequency" bars close (default 50).
All calculated values (slope, channel bottom, levels, scores) are "snapshotted" and frozen until next confirmed update.
Drawing uses these stable snapshots, ensuring zones remain fixed during real-time price movement.
Auto Mode Scanning
When enabled:
Scans the channel height in percentage steps (default 1.0%).
Each candidate creates a thin diagonal zone (thickness % of price, default 0.04%) parallel to the trend.
Counts valid "hits": Price touches zone and holds (no break) for user-defined bars (default 10).
Break source: "Close" (strict) or "Wick" (sensitive).
Direction assumed by close relative to zone center (support/resistance).
Level Selection and Filtering
Ranks by hit count, applies minimum distance (% of channel height) to avoid overlap.
Limits to max zones (default 9), sorted low to high.
Manual mode alternative: Directly uses input percentages (e.g., 0, 50, 100 for channel bottom/mid/top).
Diagonal Zone Construction
Zones are drawn as filled diagonal bands using two parallel lines (top/bottom) with linefill.
Thickness is volatility-adjusted (% of current price).
Optional extension far into future or limited projection.
Colors: Supply (above price, default light gray), Demand (below price, default cyan) – updates live but positions stay stable.
Dashboard and Visuals
Table shows current price at each zone (stable during bar), % level, hit count (green if high).
Update countdown displayed for transparency.
How to Use
Perfect for trending markets – identifies dynamic, parallel support/resistance zones that move with price structure.
High hit counts: Strong diagonal zones – expect bounces or acceleration on retest.
Update Frequency: Higher values (100+) for very stable long-term channels; lower for adaptive intraday.
Validation Bars: Increase for stricter zones (fewer false positives).
Multi-Timeframe: Use higher TF input for major trend channels on lower charts.
Supply Zones (Diagonal above price): Dynamic resistance – potential shorts or profit targets.
Demand Zones (Diagonal below price): Dynamic support – potential longs or trailing stops.
Manual Mode: Quick plotting of fixed % (e.g., channel median, quartiles).
Confluence: Combine with horizontal levels, volume, or order flow for entries.
Zones remain visually stable (no repainting during bar) thanks to snapshot logic – reliable for live trading decisions.
Disclaimer
This indicator is a technical analysis tool and should be used in conjunction with other forms of analysis. Past performance does not guarantee future results. Always use proper risk management.
Ultimate MACD [captainua]Ultimate MACD - Comprehensive MACD Trading System
Overview
This indicator combines traditional MACD calculations with advanced features including divergence detection, volume analysis, histogram analysis tools, regression forecasting, strong top/bottom detection, and multi-timeframe confirmation to provide a comprehensive MACD-based trading system. The script calculates MACD using configurable moving average types (EMA, SMA, RMA, WMA) and applies various smoothing methods to reduce noise while maintaining responsiveness. The combination of these features creates a multi-layered confirmation system that reduces false signals by requiring alignment across multiple indicators and timeframes.
Core Calculations
MACD Calculation:
The script calculates MACD using the standard formula: MACD Line = Fast MA - Slow MA, Signal Line = Moving Average of MACD Line, Histogram = MACD Line - Signal Line. The default parameters are Fast=12, Slow=26, Signal=9, matching the traditional MACD settings. The script supports four moving average types:
- EMA (Exponential Moving Average): Standard and most responsive, default choice
- SMA (Simple Moving Average): Equal weight to all periods
- RMA (Wilder's Moving Average): Smoother, less responsive
- WMA (Weighted Moving Average): Recent prices weighted more heavily
The price source can be configured as Close (standard), Open, High, Low, HL2, HLC3, or OHLC4. Alternative sources provide different sensitivity characteristics for various trading strategies.
Configuration Presets:
The script includes trading style presets that automatically configure MACD parameters:
- Scalping: Fast/Responsive settings (8,18,6 with minimal smoothing)
- Day Trading: Balanced settings (10,22,7 with minimal smoothing)
- Swing Trading: Standard settings (12,26,9 with moderate smoothing)
- Position Trading: Smooth/Conservative settings (15,35,12 with higher smoothing)
- Custom: Full manual control over all parameters
Histogram Smoothing:
The histogram can be smoothed using EMA to reduce noise and filter minor fluctuations. Smoothing length of 1 = raw histogram (no smoothing), higher values (3-5) = smoother histogram. Increased smoothing reduces noise but may delay signals slightly.
Percentage Mode:
MACD values can be converted to percentage of price (MACD/Close*100) for cross-instrument comparison. This is useful when comparing MACD signals across instruments with different price levels (e.g., BTC vs ETH). The percentage mode normalizes MACD values, making them comparable regardless of instrument price.
MACD Scale Factor:
A scale factor multiplier (default 1.0) allows adjusting MACD display size for better visibility. Use 0.3-0.5 if MACD appears too compressed, or 2.0-3.0 if too small.
Dynamic Overbought/Oversold Levels:
Overbought and oversold levels are calculated dynamically based on MACD's mean and standard deviation over a lookback period. The formula: OB = MACD Mean + (StdDev × OB Multiplier), OS = MACD Mean - (StdDev × OS Multiplier). This adapts to current market conditions, widening in volatile markets and narrowing in calm markets. The lookback period (default 20) controls how quickly the levels adapt: longer periods (30-50) = more stable levels, shorter (10-15) = more responsive.
OB/OS Background Coloring:
Optional background coloring can highlight the entire panel when MACD enters overbought or oversold territory, providing prominent visual indication of extreme conditions. The background colors are drawn on top of the main background to ensure visibility.
Divergence Detection
Regular Divergence:
The script uses the MACD line (not histogram) for divergence detection, which provides more reliable signals. Bullish divergence: Price makes a lower low while MACD line makes a higher low. Bearish divergence: Price makes a higher high while MACD line makes a lower high. Divergences often precede reversals and are powerful reversal signals.
Pivot-Based Divergence:
The divergence detection uses actual pivot points (pivotlow/pivothigh) instead of simple lowest/highest comparisons. This provides more accurate divergence detection by identifying significant pivot lows/highs in both price and MACD line. The pivot-based method compares two recent pivot points: for bullish divergence, price makes a lower low while MACD makes a higher low at the pivot points. This method reduces false divergences by requiring actual pivot points rather than just any low/high within a period.
The pivot lookback parameters (left and right) control how many bars on each side of a pivot are required for confirmation. Higher values = more conservative pivot detection.
Hidden Divergence:
Continuation patterns that signal trend continuation rather than reversal. Bullish hidden divergence: Price makes a higher low but MACD makes a lower low. Bearish hidden divergence: Price makes a lower high but MACD makes a higher high. These patterns indicate the trend is likely to continue in the current direction.
Zero-Line Filter:
The "Don't Touch Zero Line" option ensures divergences occur in proper context: for bullish divergence, MACD must stay below zero; for bearish divergence, MACD must stay above zero. This filters out divergences that occur in neutral zones.
Range Filtering:
Minimum and maximum lookback ranges control the time window between pivots to consider for divergence. This helps filter out divergences that are too close together (noise) or too far apart (less relevant).
Volume Confirmation System
Volume threshold filtering requires current volume to exceed the volume SMA multiplied by the threshold factor. The formula: Volume Confirmed = Volume > (Volume SMA × Threshold). If the threshold is set to 1.0 or lower, volume confirmation is effectively disabled (always returns true). This allows you to use the indicator without volume filtering if desired. Volume confirmation significantly increases divergence and signal reliability.
Volume Climax and Dry-Up Detection:
The script can mark bars with extremely high volume (volume climax) or extremely low volume (volume dry-up). Volume climax indicates potential reversal points or strong momentum continuation. Volume dry-up indicates low participation and may produce unreliable signals. These markers use standard deviation multipliers to identify extreme volume conditions.
Zero-Line Cross Detection
MACD zero-line crosses indicate momentum shifts: above zero = bullish momentum, below zero = bearish momentum. The script includes alert conditions for zero-line crosses with cooldown protection to prevent alert spam. Zero-line crosses can provide early warning signals before MACD crosses the signal line.
Histogram Analysis Tools
Histogram Moving Average:
A moving average applied to the histogram itself helps identify histogram trend direction and acts as a signal line for histogram movements. Supports EMA, SMA, RMA, and WMA types. Useful for identifying when histogram momentum is strengthening or weakening.
Histogram Bollinger Bands:
Bollinger Bands are applied to the MACD histogram instead of price. The calculation: Basis = SMA(Histogram, Period), StdDev = stdev(Histogram, Period), Upper = Basis + (StdDev × Deviation Multiplier), Lower = Basis - (StdDev × Deviation Multiplier). This creates dynamic zones around the histogram that adapt to histogram volatility. When the histogram touches or exceeds the bands, it indicates extreme conditions relative to recent histogram behavior.
Stochastic MACD (StochMACD):
Stochastic MACD applies the Stochastic oscillator formula to the MACD histogram instead of price. This normalizes the histogram to a 0-100 scale, making it easier to identify overbought/oversold conditions on the histogram itself. The calculation: %K = ((Histogram - Lowest Histogram) / (Highest Histogram - Lowest Histogram)) × 100. %K is smoothed, and %D is calculated as the moving average of smoothed %K. Standard thresholds are 80 (overbought) and 20 (oversold).
Regression Forecasting
The script includes advanced regression forecasting that predicts future MACD values using mathematical models. This helps anticipate potential MACD movements and provides forward-looking context for trading decisions.
Regression Types:
- Linear: Simple trend line (y = mx + b) - fastest, works well for steady trends
- Polynomial: Quadratic curve (y = ax² + bx + c) - captures curvature in MACD movement
- Exponential Smoothing: Weighted average with more weight on recent values - responsive to recent changes
- Moving Average: Uses difference between short and long MA to estimate trend - stable and smooth
Forecast Horizon:
Number of bars to forecast ahead (default 5, max 50 for linear/MA, max 20 for polynomial due to performance). Longer horizons predict further ahead but may be less accurate.
Confidence Bands:
Optional upper/lower bands around forecast show prediction uncertainty based on forecast error (standard deviation of prediction vs actual). Wider bands = higher uncertainty. The confidence level multiplier (default 1.5) controls band width.
Forecast Display:
Forecast appears as dotted lines extending forward from current bar, with optional confidence bands. All forecast values respect percentage mode and scale factor settings.
Strong Top/Bottom Signals
The script detects strong recovery from extreme MACD levels, generating "sBottom" and "sTop" signals. These identify significant reversal potential when MACD recovers substantially from overbought/oversold extremes.
Strong Bottom (sBottom):
Triggered when:
1. MACD was at or near its lowest point in the bottom period (default 10 bars)
2. MACD was in or near the oversold zone
3. MACD has recovered by at least the threshold amount (default 0.5) from the lowest point
4. Recovery persists for confirmation bars (default 2 consecutive bars)
5. MACD has moved out of the oversold zone
6. Volume is above average
7. All enabled filters pass
8. Minimum bars have passed since last signal (reset period, default 5 bars)
Strong Top (sTop):
Triggered when:
1. MACD was at or near its highest point in the top period (default 7 bars)
2. MACD was in or near the overbought zone
3. MACD has declined by at least the threshold amount (default 0.5) from the highest point
4. Decline persists for confirmation bars (default 2 consecutive bars)
5. MACD has moved out of the overbought zone
6. Volume is above average
7. All enabled filters pass
8. Minimum bars have passed since last signal (reset period, default 5 bars)
Label Placement:
sTop/sBottom labels appear on the historical bar where the actual extreme occurred (not on current bar), showing the exact MACD value at that extreme. Labels respect the unified distance checking system to prevent overlaps with Buy/Sell Strength labels.
Signal Strength Calculation
The script calculates a composite signal strength score (0-100) based on multiple factors:
- MACD distance from signal line (0-50 points): Larger separation indicates stronger signal
- Volume confirmation (0-15 points): Volume above average adds points
- Secondary timeframe alignment (0-15 points): Higher timeframe agreement adds points
- Distance from zero line (0-20 points): Closer to zero can indicate stronger reversal potential
Higher scores (70+) indicate stronger, more reliable signals. The signal strength is displayed in the statistics table and can be used as a filter to only accept signals above a threshold.
Smart Label Placement System
The script includes an advanced label placement system that tracks MACD extremes and places Buy/Sell Strength labels at optimal locations:
Label Placement Algorithm:
- Labels appear on the current bar at confirmation (not on historical extreme bars), ensuring they're visible when the signal is confirmed
- The system tracks pending signals when MACD enters OB/OS zones or crosses the signal line
- During tracking, the system continuously searches for the true extreme (lowest MACD for buys, highest MACD for sells) within a configurable historical lookback period
- Labels are only finalized when: (1) MACD exits the OB/OS zone, (2) sufficient bars have passed (2x minimum distance), (3) MACD has recovered/declined by a configurable percentage from the extreme (default 15%), and (4) tracking has stopped (no better extreme found)
Label Spacing and Overlap Prevention:
- Minimum Bars Between Labels: Base distance requirement (default 5 bars)
- Label Spacing Multiplier: Scales the base distance (default 1.5x) for better distribution. Higher values = more spacing between labels
- Effective distance = Base Distance × Spacing Multiplier (e.g., 5 × 1.5 = 7.5 bars minimum)
- Unified distance checking prevents overlaps between all label types (Buy Strength, Sell Strength, sTop, sBottom)
Strength-Based Filtering:
- Label Strength Minimum (%): Only labels with strength at or above this threshold are displayed (default 75%)
- When multiple potential labels are close together, the system automatically compares strengths and keeps only the strongest one
- This ensures only the most significant signals are displayed, reducing chart clutter
Zero Line Polarity Enforcement:
- Enforce Zero Line Polarity (default enabled): Ensures labels follow traditional MACD interpretation
- Buy Strength labels only appear when the tracked extreme MACD value was below zero (negative territory)
- Sell Strength labels only appear when the tracked extreme MACD value was above zero (positive territory)
- This prevents counter-intuitive labels (e.g., Buy labels above zero line) and aligns with standard MACD trading principles
Recovery/Decline Confirmation:
- Recovery/Decline Confirm (%): Percent move away from the extreme required before finalizing (default 15%)
- For Buy labels: MACD must recover by at least this percentage from the tracked bottom
- For Sell labels: MACD must decline by at least this percentage from the tracked top
- Higher values = more confirmation required, fewer but more reliable labels
Historical Lookback:
- Historical Lookback for Label Placement: Number of bars to search for true extremes (default 20)
- The system searches within this period to find the actual lowest/highest MACD value
- Higher values analyze more history but may be slower; lower values are faster but may miss some extremes
Cross Quality Score
The script calculates a MACD cross quality score (0-100) that rates crossover quality based on:
- Cross angle (0-50 points): Steeper crosses = stronger signals
- Volume confirmation (0-25 points): Volume above average adds points
- Distance from zero line (0-25 points): Crosses near zero line are stronger
This score helps identify high-quality crossovers and can be used as a filter to only accept signals meeting minimum quality threshold.
Filtering System
Histogram Filter:
Requires histogram to be above zero for buy signals, below zero for sell signals. Ensures momentum alignment before generating signals.
Signal Strength Filter:
Requires minimum signal strength score for signals. Higher threshold = only strongest signals pass. This combines multiple confirmation factors into a single filter.
Cross Quality Filter:
Requires minimum cross quality score for signals. Rates crossover quality based on angle, volume, momentum, and distance from zero. Only signals meeting minimum quality threshold will be generated.
All filters use the pattern: filterResult = not filterEnabled OR conditionMet. This means if a filter is disabled, it always passes (returns true). Filters can be combined, and all must pass for a signal to fire.
Multi-Timeframe Analysis
The script can display MACD from a secondary (higher) timeframe and use it for confirmation. When secondary timeframe confirmation is enabled, signals require the higher timeframe MACD to align (bullish/bearish) with the signal direction. This ensures signals align with the larger trend context, reducing counter-trend trades.
Secondary Timeframe MACD:
The secondary timeframe MACD uses the same calculation parameters (fast, slow, signal, MA type) as the main MACD but from a higher timeframe. This provides context for the current timeframe's MACD position relative to the larger trend. The secondary MACD lines are displayed on the chart when enabled.
Noise Filtering
Noise filtering hides small histogram movements below a threshold. This helps focus on significant moves and reduces chart clutter. When enabled, only histogram movements above the threshold are displayed. Typical threshold values are 0.1-0.5 for most instruments, depending on the instrument's price range and volatility.
Signal Debounce
Signal debounce prevents duplicate MACD cross signals within a short time period. Useful when MACD crosses back and forth quickly, creating multiple signals. Debounce ensures only one signal per period, reducing signal spam during choppy markets. This is separate from alert cooldown, which applies to all alert types.
Background Color Modes
The script offers three background color modes:
- Dynamic: Full MACD heatmap based on OB/OS conditions, confidence, and momentum. Provides rich visual feedback.
- Monotone: Soft neutral background but still allows overlays (OB/OS zones). Keeps the chart clean without overpowering candles.
- Off: No MACD background (only overlays and plots). Maximum chart cleanliness.
When OB/OS background colors are enabled, they are drawn on top of the main background to ensure visibility.
Statistics Table
A real-time statistics table displays current MACD values, signal strength, distance from zero line, secondary timeframe alignment, volume confirmation status, and all active filter statuses. The table dynamically adjusts to show only enabled features, keeping it clean and relevant. The table position can be configured (Top Left, Top Right, Bottom Left, Bottom Right).
Performance Statistics Table
An optional performance statistics table shows comprehensive filter diagnostics:
- Total buy/sell signals (raw crossover count before filters)
- Filtered buy/sell signals (signals that passed all filters)
- Overall pass rates (percentage of signals that passed filters)
- Rejected signals count
- Filter-by-filter rejection diagnostics showing which filters rejected how many signals
This table helps optimize filter settings by showing which filters are most restrictive and how they impact signal frequency. The diagnostics format shows rejections as "X B / Y S" (X buy signals rejected, Y sell signals rejected) or "Disabled" if the filter is not active.
Alert System
The script includes separate alert conditions for each signal type:
- MACD Cross: MACD line crosses above/below Signal line (with or without secondary confirmation)
- Zero-Line Cross: MACD crosses above/below zero
- Divergence: Regular and hidden divergence detections
- Secondary Timeframe: Higher timeframe MACD crosses
- Histogram MA Cross: Histogram crosses above/below its moving average
- Histogram Zero Cross: Histogram crosses above/below zero
- StochMACD: StochMACD overbought/oversold entries and %K/%D crosses
- Histogram BB: Histogram touches/breaks Bollinger Bands
- Volume Events: Volume climax and dry-up detections
- OB/OS: MACD entry/exit from overbought/oversold zones
- Strong Top/Bottom: sTop and sBottom signal detections
Each alert type has its own cooldown system to prevent alert spam. The cooldown requires a minimum number of bars between alerts of the same type, reducing duplicate alerts during volatile periods. Alert types can be filtered to only evaluate specific alert types (All, MACD Cross, Zero Line, Divergence, Secondary Timeframe, Histogram MA, Histogram Zero, StochMACD, Histogram BB, Volume Events, OB/OS, Strong Top/Bottom).
How Components Work Together
MACD crossovers provide the primary signal when the MACD line crosses the Signal line. Zero-line crosses indicate momentum shifts and can provide early warning signals. Divergences identify potential reversals before they occur.
Volume confirmation ensures signals occur with sufficient market participation, filtering out low-volume false breakouts. Histogram analysis tools (MA, Bollinger Bands, StochMACD) provide additional context for signal reliability and identify significant histogram zones.
Signal strength combines multiple confirmation factors into a single score, making it easy to filter for only the strongest signals. Cross quality score rates crossover quality to identify high-quality setups. Multi-timeframe confirmation ensures signals align with higher timeframe trends, reducing counter-trend trades.
Usage Instructions
Getting Started:
The default configuration shows MACD(12,26,9) with standard EMA calculations. Start with default settings and observe behavior, then customize settings to match your trading style. You can use configuration presets for quick setup based on your trading style.
Customizing MACD Parameters:
Adjust Fast Length (default 12), Slow Length (default 26), and Signal Length (default 9) based on your trading timeframe. Shorter periods (8,17,7) for faster signals, longer (15,30,12) for smoother signals. You can change the moving average type: EMA for responsiveness, RMA for smoothness, WMA for recent price emphasis.
Price Source Selection:
Choose Close (standard), or alternative sources (HL2, HLC3, OHLC4) for different sensitivity. HL2 uses the midpoint of the high-low range, HLC3 and OHLC4 incorporate more price information.
Histogram Smoothing:
Set smoothing to 1 for raw histogram (no smoothing), or increase (3-5) for smoother histogram that reduces noise. Higher smoothing reduces false signals but may delay signals slightly.
Percentage Mode:
Enable percentage mode when comparing MACD across instruments with different price levels. This normalizes MACD values, making them directly comparable.
Dynamic OB/OS Levels:
The dynamic thresholds automatically adapt to volatility. Adjust the multipliers (default 1.5) to fine-tune sensitivity: higher values (2.0-3.0) = more extreme thresholds (fewer signals), lower (1.0-1.5) = more frequent signals. Adjust the lookback period to control how quickly levels adapt. Enable OB/OS background colors for visual indication of extreme conditions.
Volume Confirmation:
Set volume threshold to 1.0 (default, effectively disabled) or higher (1.2-1.5) for standard confirmation. Higher values require more volume for confirmation. Set to 0.1 to completely disable volume filtering.
Filters:
Enable filters gradually to find your preferred balance. Start with histogram filter for basic momentum alignment, then add signal strength filter (threshold 50+) for moderate signals, then cross quality filter (threshold 50+) for high-quality crossovers. Combine filters for highest-quality signals but expect fewer signals.
Divergence:
Enable divergence detection and adjust pivot lookback parameters. Pivot-based divergence provides more accurate detection using actual pivot points. Hidden divergence is useful for trend-following strategies. Adjust range parameters to filter divergences by time window.
Zero-Line Crosses:
Zero-line cross alerts are automatically available when alerts are enabled. These provide early warning signals for momentum shifts.
Histogram Analysis Tools:
Enable Histogram Moving Average to see histogram trend direction. Enable Histogram Bollinger Bands to identify extreme histogram zones. Enable Stochastic MACD to normalize histogram to 0-100 scale for overbought/oversold identification.
Multi-Timeframe:
Enable secondary timeframe MACD to see higher timeframe context. Enable secondary confirmation to require higher timeframe alignment for signals.
Signal Strength:
Signal strength is automatically calculated and displayed in the statistics table. Use signal strength filter to only accept signals above a threshold (e.g., 50 for moderate, 70+ for strong signals only).
Smart Label Placement:
Configure label placement settings to control label appearance and quality:
- Label Strength Minimum (%): Set threshold (default 75%) to show only strong signals. Higher = fewer, stronger labels
- Label Spacing Multiplier: Adjust spacing (default 1.5x) for better distribution. Higher = more spacing between labels
- Recovery/Decline Confirm (%): Set confirmation requirement (default 15%). Higher = more confirmation, fewer labels
- Enforce Zero Line Polarity: Enable (default) to ensure Buy labels only appear when tracked extreme was below zero, Sell labels only when above zero
- Historical Lookback: Adjust search period (default 20 bars) for finding true extremes. Higher = more history analyzed
Cross Quality:
Cross quality score is automatically calculated for crossovers. Use cross quality filter to only accept high-quality crossovers (threshold 50+ for moderate, 70+ for high quality).
Alerts:
Set up alerts for your preferred signal types. Enable alert cooldown (default enabled, 5 bars) to prevent alert spam. Use alert type filter to only evaluate specific alert types (All, MACD Cross, Zero Line, Divergence, Secondary Timeframe, Histogram MA, Histogram Zero, StochMACD, Histogram BB, Volume Events, OB/OS, Strong Top/Bottom). Each signal type has its own alert condition, so you can be selective about which signals trigger alerts.
Visual Elements and Signal Markers
The script uses various visual markers to indicate signals and conditions:
- MACD Line: Green when above signal (bullish), red when below (bearish) if dynamic colors enabled. Optional black outline for enhanced visibility
- Signal Line: Orange line with optional black outline for enhanced visibility
- Histogram: Color-coded based on direction and momentum (green for bullish rising, lime for bullish falling, red for bearish falling, orange for bearish rising)
- Zero Line: Horizontal reference line at MACD = 0
- Fill to Zero: Green/red semi-transparent fill between MACD line and zero line showing bullish/bearish territory
- Fill Between OB/OS: Blue semi-transparent fill between overbought/oversold thresholds highlighting neutral zone
- OB/OS Background Colors: Background coloring when MACD enters overbought/oversold zones
- Background Colors: Dynamic or monotone backgrounds indicating MACD state, or custom chart background
- Divergence Labels: "🐂" for bullish, "🐻" for bearish, "H Bull" for hidden bullish, "H Bear" for hidden bearish
- Divergence Lines: Colored lines connecting pivot points when divergences are detected
- Volume Climax Markers: ⚡ symbol for extremely high volume
- Volume Dry-Up Markers: 💧 symbol for extremely low volume
- Buy/Sell Strength Labels: Show signal strength percentage (e.g., "Buy Strength: 75%")
- Strong Top/Bottom Labels: "sTop" and "sBottom" for extreme level recoveries
- Secondary MACD Lines: Purple lines showing higher timeframe MACD
- Histogram MA: Orange line showing histogram moving average
- Histogram BB: Blue bands around histogram showing extreme zones
- StochMACD Lines: %K and %D lines with overbought/oversold thresholds
- Regression Forecast: Dotted blue lines extending forward with optional confidence bands
Signal Priority and Interpretation
Signals are generated independently and can occur simultaneously. Higher-priority signals generally indicate stronger setups:
1. MACD Cross with Multiple Filters - Highest priority: Requires MACD crossover plus all enabled filters (histogram, signal strength, cross quality) and secondary timeframe confirmation if enabled. These are the most reliable signals.
2. Zero-Line Cross - High priority: Indicates momentum shift. Can provide early warning signals before MACD crosses the signal line.
3. Divergence Signals - Medium-High priority: Pivot-based divergence is more reliable than simple divergence. Hidden divergence indicates continuation rather than reversal.
4. MACD Cross with Basic Filters - Medium priority: MACD crosses signal line with basic histogram filter. Less reliable alone but useful when combined with other confirmations.
Best practice: Wait for multiple confirmations. For example, a MACD crossover combined with divergence, volume confirmation, and secondary timeframe alignment provides the strongest setup.
Chart Requirements
For proper script functionality and compliance with TradingView requirements, ensure your chart displays:
- Symbol name: The trading pair or instrument name should be visible
- Timeframe: The chart timeframe should be clearly displayed
- Script name: "Ultimate MACD " should be visible in the indicator title
These elements help traders understand what they're viewing and ensure proper script identification. The script automatically includes this information in the indicator title and chart labels.
Performance Considerations
The script is optimized for performance:
- Calculations use efficient Pine Script functions (ta.ema, ta.sma, etc.) which are optimized by TradingView
- Conditional execution: Features only calculate when enabled
- Label management: Old labels are automatically deleted to prevent accumulation
- Array management: Divergence label arrays are limited to prevent memory accumulation
The script should perform well on all timeframes. On very long historical data with many enabled features, performance may be slightly slower, but it remains usable.
Known Limitations and Considerations
- Dynamic OB/OS levels can vary significantly based on recent MACD volatility. In very volatile markets, levels may be wider; in calm markets, they may be narrower.
- Volume confirmation requires sufficient historical volume data. On new instruments or very short timeframes, volume calculations may be less reliable.
- Higher timeframe MACD uses request.security() which may have slight delays on some data feeds.
- Stochastic MACD requires the histogram to have sufficient history. Very short periods on new charts may produce less reliable StochMACD values initially.
- Divergence detection requires sufficient historical data to identify pivot points. Very short lookback periods may produce false positives.
Practical Use Cases
The indicator can be configured for different trading styles and timeframes:
Swing Trading:
Use MACD(12,26,9) with secondary timeframe confirmation. Enable divergence detection. Use signal strength filter (threshold 50+) and cross quality filter (threshold 50+) for higher-quality signals. Enable histogram analysis tools for additional context.
Day Trading:
Use MACD(8,17,7) or use "Day Trading" preset with minimal histogram smoothing for faster signals. Enable zero-line cross alerts for early signals. Use volume confirmation with threshold 1.2-1.5. Enable histogram MA for momentum tracking.
Trend Following:
Use MACD(12,26,9) or longer periods (15,30,12) for smoother signals. Enable secondary timeframe confirmation for trend alignment. Hidden divergence signals are useful for trend continuation entries. Use cross quality filter to identify high-quality crossovers.
Reversal Trading:
Focus on divergence detection (pivot-based for accuracy) combined with zero-line crosses. Enable volume confirmation. Use histogram Bollinger Bands to identify extreme histogram zones. Enable StochMACD for overbought/oversold identification.
Multi-Timeframe Analysis:
Enable secondary timeframe MACD to see context from larger timeframes. For example, use daily MACD on hourly charts to understand the larger trend context. Enable secondary confirmation to require higher timeframe alignment for signals.
Practical Tips and Best Practices
Getting Started:
Start with default settings and observe MACD behavior. The default configuration (MACD 12,26,9 with EMA) is balanced and works well across different markets. After observing behavior, customize settings to match your trading style. Consider using configuration presets for quick setup.
Reducing Repainting:
All signals are based on confirmed bars, minimizing repainting. The script uses confirmed bar data for all calculations to ensure backtesting accuracy.
Signal Quality:
MACD crosses with multiple filters provide the highest-quality signals because they require alignment across multiple indicators. These signals have lower frequency but higher reliability. Use signal strength scores to identify the strongest signals (70+). Use cross quality scores to identify high-quality crossovers (70+).
Filter Combinations:
Start with histogram filter for basic momentum alignment, then add signal strength filter for moderate signals, then cross quality filter for high-quality crossovers. Combining all filters significantly reduces false signals but also reduces signal frequency. Find your balance based on your risk tolerance.
Volume Filtering:
Set volume threshold to 1.0 (default, effectively disabled) or lower to effectively disable volume filtering if you trade instruments with unreliable volume data or want to test without volume confirmation. Standard confirmation uses 1.2-1.5 threshold.
MACD Period Selection:
Standard MACD(12,26,9) provides balanced signals suitable for most trading. Shorter periods (8,17,7) for faster signals, longer (15,30,12) for smoother signals. Adjust based on your timeframe and trading style. Consider using configuration presets for optimized settings.
Moving Average Type:
EMA provides balanced responsiveness with smoothness. RMA is smoother and less responsive. WMA gives more weight to recent prices. SMA gives equal weight to all periods. Choose based on your preference for responsiveness vs. smoothness.
Divergence:
Pivot-based divergence is more reliable than simple divergence because it uses actual pivot points. Hidden divergence indicates continuation rather than reversal, useful for trend-following strategies. Adjust pivot lookback parameters to control sensitivity.
Dynamic Thresholds:
Dynamic OB/OS thresholds automatically adapt to volatility. In volatile markets, thresholds widen; in calm markets, they narrow. Adjust the multipliers to fine-tune sensitivity. Enable OB/OS background colors for visual indication.
Zero-Line Crosses:
Zero-line crosses indicate momentum shifts and can provide early warning signals before MACD crosses the signal line. Enable alerts for zero-line crosses to catch these early signals.
Alert Management:
Enable alert cooldown (default enabled, 5 bars) to prevent alert spam. Use alert type filter to only evaluate specific alert types. Signal debounce (default enabled, 3 bars) prevents duplicate MACD cross signals during choppy markets.
Technical Specifications
- Pine Script Version: v6
- Indicator Type: Non-overlay (displays in separate panel below price chart)
- Repainting Behavior: Minimal - all signals are based on confirmed bars, ensuring accurate backtesting results
- Performance: Optimized with conditional execution. Features only calculate when enabled.
- Compatibility: Works on all timeframes (1 minute to 1 month) and all instruments (stocks, forex, crypto, futures, etc.)
- Edge Case Handling: All calculations include safety checks for division by zero, NA values, and boundary conditions. Alert cooldowns and signal debounce handle edge cases where conditions never occurred or values are NA.
Technical Notes
- All MACD values respect percentage mode conversion when enabled
- Volume confirmation uses cached volume SMA for performance
- Label arrays (divergence) are automatically limited to prevent memory accumulation
- Background coloring: OB/OS backgrounds are drawn on top of main background to ensure visibility
- All calculations are optimized with conditional execution - features only calculate when enabled (performance optimization)
- Signal strength calculation combines multiple factors into a single score for easy filtering
- Cross quality calculation rates crossover quality based on angle, volume, and distance from zero
- Secondary timeframe MACD uses request.security() for higher timeframe data access
- Histogram analysis features (Bollinger Bands, MA, StochMACD) provide additional context beyond basic MACD signals
- Statistics table dynamically adjusts to show only enabled features, keeping it clean and relevant
- Divergence detection uses MACD line (not histogram) for more reliable signals
- Configuration presets automatically optimize MACD parameters for different trading styles
- Smart label placement: Labels appear on current bar at confirmation, using strength from tracked extreme point
- Label spacing uses effective distance (base distance × spacing multiplier) for better distribution
- Zero line polarity enforcement ensures Buy labels only appear when tracked extreme MACD < 0, Sell labels only when tracked extreme MACD > 0
- Label finalization requires MACD exit from OB/OS zone, sufficient bars passed, and recovery/decline percentage confirmation
- Strength-based filtering automatically compares and keeps only the strongest label when multiple signals are close together
- Enhanced visualization: Line outlines drawn behind main lines for superior visibility (black default, configurable)
- Enhanced visualization: Fill between MACD and zero line provides instant visual feedback (green above, red below)
- Enhanced visualization: Fill between OB/OS thresholds highlights neutral zone when dynamic levels are active
- Custom chart background overrides background mode when enabled, allowing theme-consistent indicator panels
Smart Money Fluid [JOAT]
Smart Money Fluid — Accumulation and Distribution Flow Analysis
Smart Money Fluid tracks institutional-style accumulation and distribution patterns using a sophisticated combination of Money Flow Index, Chaikin Money Flow, and VWAP-relative price analysis. It aims to reveal whether larger participants may be accumulating (buying) or distributing (selling)—information that can precede significant price moves.
What Makes This Indicator Unique
Unlike single money flow indicators, Smart Money Fluid:
Combines three different money flow methodologies into one composite signal
Detects divergences between price and money flow automatically
Identifies high-volume conditions that add conviction to signals
Provides both the composite signal and individual component values
Features a momentum histogram showing flow acceleration
What This Indicator Does
Combines multiple money flow indicators into a composite signal (0-100 scale)
Identifies accumulation zones (potential institutional buying) and distribution zones (potential selling)
Detects divergences between price and money flow
Highlights high-volume conditions for stronger signals
Tracks momentum direction within the flow
Provides comprehensive dashboard with all component values
Composite Calculation Explained
The Smart Money Flow composite combines three proven money flow methodologies:
// Component 1: Money Flow Index (MFI) - 40% weight
// Measures buying/selling pressure using price and volume
float mfi = 100 - (100 / (1 + mfRatio))
// Component 2: Chaikin Money Flow (CMF) - 30% weight
// Measures accumulation/distribution based on close position within range
float cmf = sum(mfVolume, length) / sum(volume, length) * 100
// Component 3: VWAP Price Strength - 30% weight
// Measures price position relative to volume-weighted average price
float priceVsVWAP = (close - vwap) / vwap * 100
// Final Composite (scaled to 0-100)
float rawSMF = (mfi * 0.4 + (cmf + 50) * 0.3 + (50 + priceVsVWAP * 5) * 0.3)
float smf = ta.ema(rawSMF, smoothLength)
State Classification
Accumulating (Green Zone) — SMF above accumulation threshold (default: 60). Suggests institutional buying may be occurring.
Distributing (Red Zone) — SMF below distribution threshold (default: 40). Suggests institutional selling may be occurring.
Neutral (Gray Zone) — SMF between thresholds. No clear accumulation or distribution detected.
Divergence Detection
The indicator automatically detects divergences using pivot analysis:
Bullish Divergence — Price makes a lower low while SMF makes a higher low. This suggests selling pressure is weakening despite lower prices—potential reversal signal.
Bearish Divergence — Price makes a higher high while SMF makes a lower high. This suggests buying pressure is weakening despite higher prices—potential reversal signal.
Divergences are marked with "DIV" labels on the chart.
Visual Features
SMF Line with Glow — Main composite line with gradient coloring and glow effect
Signal Line — Slower EMA of SMF for crossover signals
Flow Momentum Histogram — Shows the difference between SMF and signal line with four-color coding:
- Bright green: Positive and accelerating
- Faded green: Positive but decelerating
- Bright red: Negative and accelerating
- Faded red: Negative but decelerating
Zone Backgrounds — Green tint in accumulation zone, red tint in distribution zone
Reference Lines — Dashed lines at accumulation/distribution thresholds, dotted line at 50
Strong Signal Markers — Triangles appear when accumulation/distribution occurs with high volume
Divergence Labels — "DIV" markers when divergences are detected
Color Scheme
Accumulation Color — Default: #00E676 (bright green)
Distribution Color — Default: #FF5252 (red)
Neutral Color — Default: #9E9E9E (gray)
Gradient Coloring — SMF line transitions smoothly between colors based on value
Dashboard Information
The on-chart table (top-right corner) displays:
Current SMF value with state coloring
State classification (ACCUMULATING, DISTRIBUTING, or NEUTRAL)
Flow momentum direction (Up/Down with magnitude)
MFI component value
CMF component value with directional coloring
Volume status (High or Normal)
Active divergence detection (Bullish, Bearish, or None)
Inputs Overview
Calculation Settings:
Money Flow Length — Period for flow calculations (default: 14, range: 5-50)
Smoothing Length — EMA smoothing period (default: 5, range: 1-20)
Divergence Lookback — Bars for pivot detection in divergence analysis (default: 5, range: 2-20)
Sensitivity:
Accumulation Threshold — Level above which accumulation is detected (default: 60, range: 50-90)
Distribution Threshold — Level below which distribution is detected (default: 40, range: 10-50)
High Volume Multiplier — Multiple of average volume for "high volume" classification (default: 1.5x, range: 1.0-3.0)
Visual Settings:
Accumulation/Distribution/Neutral Colors — Customizable color scheme
Show Flow Histogram — Toggle momentum histogram
Show Divergences — Toggle divergence detection and labels
Show Dashboard — Toggle the information table
Show Zone Background — Toggle colored backgrounds in accumulation/distribution zones
Alerts:
Await Bar Confirmation — Wait for bar close before triggering (recommended)
How to Use It
For Trend Confirmation:
Accumulation during uptrends confirms buying pressure
Distribution during downtrends confirms selling pressure
Divergence between price trend and SMF warns of potential reversal
For Reversal Detection:
Bullish divergence at price lows suggests potential bottom
Bearish divergence at price highs suggests potential top
Strong signals (triangles) with high volume add conviction
For Entry Timing:
Enter longs when SMF crosses into accumulation zone
Enter shorts when SMF crosses into distribution zone
Wait for high volume confirmation for stronger signals
Use divergences as early warning for position management
Alerts Available
SMF Accumulation Started — SMF entered accumulation zone
SMF Distribution Started — SMF entered distribution zone
SMF Strong Accumulation — Accumulation with high volume
SMF Strong Distribution — Distribution with high volume
SMF Bullish Divergence — Bullish divergence detected
SMF Bearish Divergence — Bearish divergence detected
Best Practices
High volume during accumulation/distribution adds significant conviction
Divergences are early warnings—don't trade them alone
Use in conjunction with price action and support/resistance
Works best on liquid markets with reliable volume data
This indicator is provided for educational purposes. It does not constitute financial advice. Past performance does not guarantee future results. Always conduct your own analysis and use proper risk management before making trading decisions.
— Made with passion by officialjackofalltrades
Box Theory [Interactive Zones] PyraTimeThis script combines Nicholas Darvas’s "Box Theory" with modern Supply and Demand (Premium/Discount) concepts. It automatically identifies the most recent Swing High and Swing Low to delineate the current trading range.
The purpose of this tool is to visualize market structure and help traders identify when price is relatively expensive (Premium) or cheap (Discount) within a defined range.
Visual Guide: What You Are Seeing
The Box: Represents the active trading range defined by the most recent significant Swing High and Swing Low.
Red Zone (Premium): The top 25% of the range. Mathematically, prices here are considered "expensive" relative to the current structure.
Green Zone (Discount): The bottom 25% of the range. Prices here are considered "cheap" relative to the current structure.
Grey Zone (Equilibrium): The middle 50% of the range. This is the area of fair value where price often consolidates.
Dashed Line (EQ): The exact 50% midpoint of the range.
Tutorial: How to Trade Using This Indicator
Method 1: Mean Reversion (Range Trading) This method applies when the market is moving sideways.
Identify Structure: Wait for a box to form.
Wait for Extremes: Do not trade when price is in the middle (Grey/White area). Wait for price to enter the Red or Green zones.
Entry Trigger:
Shorts: When price enters the Red Zone, look for a rejection (wicks leaving the zone) or a lower timeframe breakdown. Target the EQ (Midline) as your first take profit.
Longs: When price enters the Green Zone, look for support formation. Target the EQ (Midline) as your first take profit.
Method 2: Trend Continuation (Breakouts) This method applies when the market is trending strongly.
Breakout: Monitor the alerts. A close outside the box indicates a potential shift in market structure.
Retest: After a breakout up, the old "Red Zone" (Resistance) often flips to become new Support. Wait for price to pull back to the top of the old box before entering.
Configuration Guide (Settings)
Pivot Left/Right Bars (Sensitivity):
Default (20/20): Best for Swing Trading. It filters out market noise and only draws boxes based on major structural points.
Lower (5/5): Best for Scalping. It will create smaller, more frequent boxes but increases the risk of false signals.
Zone Percentage:
Default (25%): Standard deviation for Supply/Demand zones.
Alternative (15%): Use this for "sniping" entries at the absolute extremes of the range.
Multi-Timeframe (MTF):
Enable "Use Higher Timeframe" to see Daily or Weekly ranges while trading on lower timeframes (like the 15m or 1H). This helps keep your intraday trades aligned with the major trend.
Technical Note on "Lag" This indicator uses Pivots to draw the box. A pivot is only confirmed after a certain number of bars have passed (the "Pivot Right Bars" setting).
Example: If "Pivot Right Bars" is set to 20, the box will update 20 bars after the actual high or low occurred. This is necessary to confirm that the point was indeed a Swing High/Low. Do not treat the box lines as predictive; they are reactive to confirmed structure.
Big Trades / Intrabar Volume Clusters by HKDescription:
This indicator brings professional Order Flow and Footprint capabilities to your chart. It detects and visualizes high-volume trade clusters inside the candle, allowing you to see exactly at which price level big market participants were active.
Unlike standard volume bars, this tool uses Intrabar Data to map significant buying and selling pressure precisely within the candle body.
ℹ️ IMPORTANT: Resolution Setting (Read First) To ensure this indicator works immediately for all users (including Free/Basic accounts), the default resolution is set to "1 Minute".
Basic/Free Users: Please keep the setting at "1" (Second-based intervals often require a paid plan).
Premium Users: For the best precision and the exact look shown in the screenshots, we highly recommend changing the Resolution setting to "5S" (5 Seconds)!
🚀 Key Features
Intrabar Precision: Leverages request.security_lower_tf to look inside the candle structure.
Noise Filtering: Only displays clusters that exceed your defined Minimum Volume threshold, filtering out retail noise.
Smart Coloring:
Green: Buying pressure (Close >= Open on the lower timeframe).
Red: Selling pressure (Close < Open on the lower timeframe).
🆕 Independent Sizing: A unique feature: You can control the Font Size and Circle Size independently.
This allows for small, non-intrusive circles with large, readable text.
⚙️ Settings
Resolution: Default is 1 (Minute). Premium users should switch to 5S for true order flow precision.
Minimum Volume: The most important filter. Determines how large a trade cluster must be to appear (e.g., 150+ for ETH, higher for BTC).
Visuals: Customize Buy/Sell colors, Circle Size, and Text Size separately.
⚠️ Visual Tip (If text is hidden)
If the bubbles or numbers appear behind the candles or disappear when clicking away:
Right-click on any of the indicator bubbles.
Select Visual Order -> Bring to Front.
This ensures the Big Trades data always floats on top of your price bars.






















