TrigosFx: Smart Money Structure & PatternsTitle: TrigosFx: Smart Money Structure & Patterns
Description: This indicator is a comprehensive professional toolkit designed to automate Market Structure mapping and Advanced Pattern Recognition. It filters out market noise to help you identify high-probability setups aligned with institutional trends.
By combining "Swing" Fractals with dynamic Geometry and a Multi-Timeframe Dashboard, TrigosFx allows you to trade with the confluence of Price Action and Smart Money concepts.
💎 Key Features
1. Smart Geometric Patterns (Auto-Detection) The script independently detects multiple price structures simultaneously without conflict:
Channels (Purple): Identifies parallel institutional flows (Ascending/Descending).
Triangles & Wedges (Blue): Detects compression and potential explosive breakouts.
Rectangles (Orange): Highlights accumulation and distribution ranges.
Double Tops (M) & Double Bottoms (W): Classic reversal patterns at key levels.
2. Institutional Swing Points (Fractals)
Uses a "Swing" logic (default 30-bar lookback) to mark significant Structural Highs and Lows, filtering out minor internal noise to show real Support & Resistance.
3. Multi-Timeframe (MTF) Dashboard
An on-screen panel that monitors the Trend Structure (Bullish/Bearish) of higher timeframes (Default: H1, H4).
Strategy: Use this as a "Traffic Light". Only execute trades when the pattern breakout aligns with the higher timeframe trend colors.
4. "Smart TP" Probability Filter
Intelligent Targets: Automatically calculates Take Profit levels based on pattern size.
Trend Filter: If enabled, the TP label ONLY appears if the setup is aligned with the H1 Trend. Counter-trend setups are kept clean to discourage risky trades.
5. Auto-Cleanup System
Keeps your charts pristine. Old or invalidated patterns are automatically deleted after a set period (default: 50 candles), ensuring you focus only on live price action.
⚙️ How to Use
Analyze the Dashboard: Check the table (top-right). Is the HTF Structure (H1/H4) Bullish or Bearish?
Wait for Geometry: Let the script identify a clear structure (e.g., a Blue Triangle or Purple Channel).
Confirm the Breakout:
LONG Setup: Price breaks UP + Dashboard is GREEN.
SHORT Setup: Price breaks DOWN + Dashboard is RED.
Execution: If the "TP" label appears, the probability is high.
🎨 Customization
Fully Customizable: Adjust colors, line thickness, and dashboard position to fit your style.
Sensitivity Control: You can tweak the lookback periods to detect faster or slower patterns.
Disclaimer: This tool is for educational purposes and market analysis. Always manage your risk properly.
廣量指標
EMA20-EMA50 Separation Impulse**EMA20–EMA50 Separation Impulse Indicator**
This indicator is a **trend phase classifier**, not a signal generator.
It evaluates the **structural quality of a trend** by measuring the separation between the EMA20 and EMA50, **normalized by ATR**. By using volatility-adjusted distance instead of raw price or percentage, it provides a robust and comparable measure across different instruments and timeframes.
### Key characteristics
* **Discrete states**, not a continuous oscillator
* **Independent from price scale** (displayed in a lower panel)
* **Contextual indicator**, not a timing tool
* **Fully backtestable without ambiguity**
### Logic
The indicator computes:
```
|EMA20 − EMA50| / ATR
```
Based on this normalized separation, each bar is classified into one of three market phases:
* **Green (State 1)**
Ordered trend. EMA structure is compact and stable.
The EMA-based pullback setup has a statistical edge.
* **Blue (State 2)**
Extended trend. Separation is increasing.
Edge is reduced. Trades require more selectivity or reduced position size.
* **Red (State 3)**
Overextended trend. EMAs are widely separated.
Pullbacks to EMA20 lose effectiveness. The setup has no edge.
### How to integrate it into an EMA-based system
This indicator should be used strictly as a **context filter**, not as an entry or exit trigger.
Typical integration rules:
* Allow long entries **only when State = 1 (Green)**
* Reduce position size or require stronger confirmation when State = 2 (Blue)
* Disable EMA pullback entries entirely when State = 3 (Red)
Used correctly, the indicator helps distinguish **when an EMA trend-following system is operating in its optimal environment**, and when market conditions degrade its expectancy.
It answers the question:
> *“Is this still a healthy trend for EMA pullback trading?”*
—not *“Should I buy or sell now?”*
BuyLow SellHigh Bands | ProjectSyndicate________________________________________
📊 BuyLow SellHigh (BLSH) Bands
Comprehensive Trading Guide – by ProjectSyndicate
________________________________________
🔰 1. Introduction
The BuyLow SellHigh (BLSH) Bands indicator is a powerful technical analysis tool designed for the TradingView platform. Works with any symbol. Gold/FX/indices/oil/crypto/stocks.
It provides traders with a clear, visual representation of:
• 📈 Overbought conditions
• 📉 Oversold conditions
This makes it easier to identify high-probability entry and exit points.
The indicator is built on:
• Dynamic price channels
• Fibonacci-based zones
• Color-coded market structure
💡 While the BLSH Bands can be used on Forex, Crypto, and Futures, this guide focuses on Gold (XAUUSD) using:
• M5
• M15
• M30 timeframes
________________________________________
🧠 2. Core Concepts
The BLSH Bands structure is created using two key components:
________________________________________
📐 Dynamic Price Bands
• Upper and lower bands are calculated using the highest high and lowest low
• Based on a user-defined lookback period (fiboPeriod)
• Reflects recent volatility and price range
This creates a self-adjusting channel that adapts to market conditions.
________________________________________
🧮 Fibonacci Zones
The space between the bands is divided into six Fibonacci-based zones:
• 0.786
• 0.618
• 0.500
• 0.382
• 0.214
⚠️ These are not traditional retracements — they are used to grade price extremity within the channel.
________________________________________
🎨 Color-Coded Zones Overview
Zone (Fib Level) Color Market Condition Interpretation
1.000 – 0.786 🔴 Red Extreme Overbought High reversal / pullback probability
0.786 – 0.618 🟠 Orange Overbought Selling pressure building
0.618 – 0.500 🟡 Yellow Mildly Overbought Bullish momentum weakening
0.500 – 0.382 🟢 Aqua Mildly Oversold Bearish momentum weakening
0.382 – 0.214 🔵 Deep Sky Blue Oversold Strong buying interest
0.214 – 0.000 🔷 Blue Extreme Oversold High bounce / reversal probability
🖤 Solid black separator lines ensure clean visual separation between zones for precise price location.
________________________________________
🪙 3. Trading Strategies for XAUUSD (Gold)
Gold’s volatility and respect for technical levels make it ideal for BLSH Bands strategies.
________________________________________
⚡ M5 Timeframe – Scalping Strategy
Designed for fast mean-reversion trades from extreme zones.
🟢 BUY Setup
• Price enters Extreme Oversold (Blue) zone
• Bullish confirmation candle appears:
o Hammer
o Bullish engulfing
• Enter BUY
🔴 SELL Setup
• Price enters Extreme Overbought (Red) zone
• Bearish confirmation candle appears:
o Shooting star
o Bearish engulfing
• Enter SELL
🎯 Take Profit:
• Median band (between Yellow & Aqua)
🛑 Stop Loss:
• Just outside the outer band
________________________________________
📆 M15 Timeframe – Day Trading Strategy
Balanced timeframe for higher-probability reversals.
🟢 BUY Setup
• Price enters Oversold (Blue / Deep Sky Blue)
• Strong bullish reversal candle closes back inside bands
• Enter BUY after close
🔴 SELL Setup
• Price enters Overbought (Red / Orange)
• Bearish reversal candle closes back inside bands
• Enter SELL after close
🎯 Take Profit (Multi-Target):
1. Median band
2. Opposite extreme band
🛑 Stop Loss:
• Beyond high/low of confirmation candle
________________________________________
🔄 M30 Timeframe – Swing Trading Strategy
Used for identifying major swing points.
🔍 Trend Filter
• Use 100 or 200 EMA
• Trade only in trend direction
🟢 Uptrend
• Buy pullbacks into Oversold zones
🔴 Downtrend
• Sell rallies into Overbought zones
📉 Confirmation:
• Band rejection
• RSI or MACD divergence
🎯 Take Profit:
• Previous structure levels
• Opposite band extreme
🛑 Stop Loss:
• Below / above recent swing high or low
________________________________________
🚨 4. Alerts System
Alerts are disabled by default to keep charts clean.
✅ How to Enable
• Open indicator settings
• Check “Enable Alerts”
________________________________________
🔔 Available Alerts
🔴 Overbought Alert
• Trigger: Price crosses above 0.786
• Message:
🔴 SELL SIGNAL: Price entered Overbought Zone – Consider selling or taking profits
🟢 Oversold Alert
• Trigger: Price crosses below 0.214
• Message:
🟢 BUY SIGNAL: Price entered Oversold Zone – Consider buying or entering long
________________________________________
⏱ Alert Spacing Logic
• Default: 20/50 bars
• Prevents repeated alerts in choppy markets
• Filters for higher-quality signals
________________________________________
⚙️ 5. Customization Settings
Adjust the indicator in the Settings panel:
🔧 Core Inputs
• fiboPeriod → Band sensitivity
• extremes → Price source (High/Low or Close)
🔔 Alert Controls
• Enable / disable alerts
• Separate control for overbought & oversold
• Alert spacing (bars)
________________________________________
⭐ How You Can Support ProjectSyndicate (3 Steps)
1. ✅ Click “Add to Favorites” to save this script to your TradingView Favorites
2. 🔎 Check out our other scripts to complete your SMC toolkit
3. 👤 Follow ProjectSyndicate for the latest updates, upgrades, and new releases
________________________________________
⚠️ 6. Disclaimer
Trading involves significant risk and may not be suitable for all traders.
This indicator is a decision-support tool, not a standalone trading system.
Always apply:
• Proper risk management
• Additional confirmations
• Sound trading discipline
📉 Past performance does not guarantee future results.
eob Area - Body Closes Prev Extreme + Opposite ColorEob indicator identifies eob zone to trade
this eob zones used for trade scalping points
quick scalp and exit
kk s9target 1 is rs 10 and stoploss 15points but always hit target if you have any doubts call : 9963782970, or email : kkraju5@gmail.com , 9966755535
www.youtube.com
Gold 2-Week Futures LevelsYou may change the color at bottom of script and i used 1h to mark out my levels, you may change it to fit your time frame.
MACD 12-26-9 with Slope, Convergence & Divergence1. Core Indicator: MACD (12-26-9)
The script uses the standard MACD:
Fast EMA: 12
Slow EMA: 26
Signal EMA: 9
It plots:
MACD Line → short-term vs long-term momentum
Signal Line → smoothed MACD
Histogram → distance between MACD and Signal
2. Histogram Slope (Momentum Acceleration)
What it is
The slope measures how fast the MACD histogram is changing.
histSlope = hist - hist
What it tells you
Positive slope → momentum accelerating
Negative slope → momentum slowing
Slope flip → early momentum shift (often before MACD cross)
Why it matters
MACD crosses are lagging.
Histogram slope gives early warning of momentum changes.
3. Convergence & Divergence (MACD vs Signal)
How it’s calculated
The script measures the distance between the MACD and Signal lines:
distance = abs(macdLine - signalLine)
Convergence → distance is shrinking
Divergence → distance is expanding
Interpretation
Convergence = compression / energy building
Divergence = expansion / trend strength or exhaustion
This is not price divergence, but internal momentum structure.
4. MACD Perimeter Threshold (Momentum Filter)
What it is
Horizontal bands above and below zero that define a “noise zone”.
Inside perimeter → weak / choppy momentum
Outside perimeter → strong momentum
Why it’s useful
Filters low-quality MACD crosses
Identifies compression → expansion
Helps spot trend exhaustion when momentum fades outside the band
5. Visual Encoding (What you see)
Histogram colors
Bright green / red → strong acceleration
Dull green / maroon → weakening momentum
Gray → indecision
MACD line color
Yellow → converging (compression)
Orange → diverging (expansion)
Blue → neutral
Markers
Up triangle → bullish convergence
Down triangle → bearish divergence
6. How traders use this indicator
Trend continuation
MACD above zero
Histogram positive
Slope rising
Divergence expanding
➡ Strong trend continuation
Pullback entries
Trend intact
Histogram pulls back toward zero
Slope turns up again
➡ High-probability re-entry
Breakout anticipation
Long convergence
Histogram flattening
Sudden slope expansion
➡ Breakout likely
Exhaustion warning
Large divergence
Histogram slope weakens
Momentum fails to expand
➡ Trend may stall or reverse
7. Best use cases
Works best as a momentum confirmation tool
Combine with:
Market structure
Support / resistance
Moving averages
Volume or Force Index
Value Area PRO (TPO/Volume Session VAH/VAL/POC) 📌 AP Capital Value Area PRO (TPO / Volume)
AP Capital Value Area PRO is a session-based value area indicator designed for Gold (XAUUSD), NASDAQ (NAS100), and other CFD instruments.
It focuses on where the market has accepted price during the current session and highlights high-probability interaction zones used by professional traders.
Unlike rolling lookback volume profiles, this indicator builds a true session value area and provides actionable signals around VAH, VAL, and POC.
🔹 Core Features
Session-Anchored Value Area
Value Area is built only during the selected session
Resets cleanly at session start
Levels develop during the session and can be extended forward
No repainting or shifting due to lookback changes
TPO or Volume Mode
TPO (Time-at-Price) mode – ideal for CFDs and tick-volume data
Volume mode – uses broker volume if preferred
Same logic, different weighting method
Fixed Price Bin Size
Uses a fixed bin size (e.g. 0.10 for Gold, 0.25–0.50 for NAS100)
Produces cleaner, more realistic VAH/VAL levels
Avoids distorted profiles caused by dynamic bin scaling
VAH / VAL / POC Levels
VAH (Value Area High)
VAL (Value Area Low)
POC (Point of Control) (optional)
Lines can be extended to act as forward reference levels
🔹 Trading Signals & Alerts
Value Re-Entry
Identifies false breakouts where price:
Trades outside value
Then closes back inside
Often seen before strong mean-reversion or continuation moves.
Acceptance
Detects initiative activity using:
Multiple consecutive closes outside value
Filters out weak single-candle breaks
Rejection
Flags strong rejection candles:
Large candle body
Wick outside value
Close back inside the value area
These conditions are especially effective on Gold intraday.
🔹 Optional Profile Histogram
Right-side volume/TPO histogram
Buy/sell imbalance visualization
Fully optional to reduce chart clutter and improve performance
🔹 Best Use Cases
Recommended markets
XAUUSD (Gold)
NAS100 / US100
Other index or metal CFDs
Recommended timeframes
5m, 15m, 30m
Suggested settings
Mode: TPO
Value Area: 70%
Bin size:
Gold: 0.10
NAS100: 0.25 or 0.50
🔹 How Traders Use It
Trade rejections at VAH / VAL
Look for acceptance to confirm trend days
Use re-entries to fade failed breakouts
Combine with trend filters, EMA structure, or session context
⚠️ Disclaimer
This indicator is provided for educational and analytical purposes only and does not constitute financial advice. Always manage risk appropriately.
Relative Strength SpreadSPY vs IWM Relative Strength Spread Indicator
The SPY vs IWM Relative Strength Spread indicator measures leadership between large-cap and small-cap equities by comparing the percent performance of SPY (S&P 500) against IWM (Russell 2000) over a user-defined lookback period.
The indicator plots a zero-centered histogram in a separate pane, making relative strength shifts immediately visible.
How It Works
The indicator calculates the percent change of SPY and IWM over the same lookback window.
It then subtracts IWM’s percent change from SPY’s percent change.
The result is plotted as a histogram pinned to the 0% line.
This design removes long-term drift and ensures that:
Positive values indicate SPY is outperforming IWM
Negative values indicate IWM is outperforming SPY
How to Read the Histogram
Above Zero (Green Bars)
Large-cap stocks are leading → typically associated with risk-on stability and institutional flow into SPY-weighted names.
Below Zero (Red Bars)
Small-cap stocks are leading → often signals risk appetite expansion and speculative participation.
Crosses of the Zero Line
Mark potential leadership transitions between large caps and small caps.
Why This Indicator Is Useful
Identifies market regime shifts (risk-on vs risk-off behavior)
Confirms or filters trend strength in equities
Helps time rotations between large-cap and small-cap exposure
Works consistently across all timeframes
Because the calculation is based on percent change, the histogram remains normalized and comparable regardless of price level or timeframe.
Best Use Cases
As a market internals / breadth confirmation tool
As a bias filter for SPY, IWM, or index futures
To spot early leadership changes before price trends fully develop
The Order Flow Key LevelsThe Order Flow Key Levels — Liquidity-Based Support & Resistance
The Order Flow Key Levels is a closed-source indicator that plots participation-based key levels directly on the chart as clean, horizontal lines. The goal is to help traders quickly identify key levels formed by high participation, using the interaction between price movement and executed volume.
What you see on the chart
The indicator draws horizontal key level lines at prices where meaningful trading activity has occurred and where price has historically shown a reaction. These lines are intended to be used as context—areas where price may pause, reject, or accept and continue.
How it works (high level)
At a conceptual level, the tool evaluates:
Executed volume concentration at specific price levels
Repeated interaction at those levels over time (participation “revisits”)
Price response to participation, distinguishing between acceptance vs rejection behavior
Key levels are formed from completed execution data and are designed to be non-repainting, meaning once a level is confirmed and plotted, it remains stable rather than shifting retroactively. The indicator does not predict future price direction; it provides structure and confirmation based on participation.
How traders use it
Treat the plotted lines as high liquidity zones
Look for acceptance above/below a level as directional confirmation
Use levels for entries, exits, and trade management, including defining invalidation areas beyond a level
Monitor market structure as price transitions between levels (break, hold, retest, rejection)
The Order Flow Key Levels is built for futures, crypto, CFDs, and other high-liquidity markets, where executed volume-based participation can provide meaningful context.
While the indicator uses established price and volume concepts, it applies a proprietary methodology for identifying and filtering participation-based key levels, helping reduce noise compared to traditional support/resistance tools.
Smart Scalper Pro Template + VWAP
📌 Author
Garry Evans
Independent system developer focused on:
Risk-first automation
Market structure & liquidity behavior
Discipline, consistency, and capital preservation
“The edge isn’t the market — it’s the man who survives it.”
⚙️ Risk Management & Position Sizing
The script is built around capital protection, not signal frequency.
Risk logic includes:
Fixed or dynamic risk per trade
Market-adaptive position sizing
Session-based trade limits
Daily trade caps and auto-lockout protection
Volatility-aware sizing (futures & crypto)
⚠️ Profit is pursued only after risk is controlled.
📊 Track Record
Backtested across multiple market environments
Forward-tested and actively used by the author
Real-account trades are logged where platform rules allow
Results vary by market, timeframe, and user-defined risk settings.
🌍 Supported Markets
Designed to work across all liquid markets, including:
Stocks
Crypto (spot & futures)
Options (signal-based framework)
Futures (indices, metals, crypto futures)
The system adapts to volatility and structure — it is not market-specific.
⚖️ Leverage
Leverage is not required
If used, leverage is fully user-controlled
Risk logic scales exposure conservatively
No martingale.
No revenge sizing.
No over-exposure logic.
🧪 Backtesting
✔ Yes
Strategy logic has been backtested
Filters reduce chop, noise, and forced trades
Focus on drawdown control over curve-fitting
🛠 Support
✔ Yes
Direct author support
Ongoing improvements and updates
Feature refinement based on real usage and feedback
👥 Community
✔ Yes
Private user access
High-quality feedback environment
No public signal spam or hype-driven chat rooms
⏳ Trial Period
✔ Yes
Limited trial access available
Designed for evaluation only
Trial users do not receive full feature access
🚫 Who This Script Is NOT For
This system is not for:
Traders looking for guaranteed profits
Users expecting copy-paste “signal calls”
Over-leveraged gamblers
Those unwilling to follow risk rules
Anyone seeking overnight results
This is a discipline and automation tool, not a shortcut.
🧠 Final Positioning
This is not a signal service.
This is a risk-controlled execution framework designed to:
Enforce discipline
Reduce emotional trading
Protect capital during bad market conditions
Scale responsibly during favorable ones
Smart Scalper Pro Template + VWAP + FVG Invite-Only Trading Script
Private Access • Risk-First • Discipline-Driven
🔐 Access Tiers
Lifetime Access — $999
(Limited to 25 total seats)
One-time payment
Full script access
All future updates included
Priority support & early feature access
Locked pricing — never increases
Once lifetime seats are filled, this tier is permanently closed.
Level 2 Access — $199
Advanced Risk & Confirmation Module
Higher-confidence trade filters
Enhanced risk controls & lockout logic
Advanced session and volatility filters
Designed for experienced, disciplined traders
Reduces over-trading and low-quality setups
Level 2 is feature-based, not cosmetic — it adds stricter trade qualification.
Subscription Access — $99 / month
Core strategy framework
Risk-managed trade logic
Ongoing updates while subscribed
Ideal for evaluation or short-term usage
Subscription does not include Level 2 advanced filters.
📌 Author
Garry Evans
Independent system developer focused on:
Risk-first automation
Market structure & liquidity behavior
Discipline, consistency, and capital preservation
“The edge isn’t the market — it’s the man who survives it.”
⚙️ Risk Management & Position Sizing
The script is built around capital protection, not signal frequency.
Risk logic includes:
Fixed or dynamic risk per trade
Market-adaptive position sizing
Session-based trade limits
Daily trade caps and auto-lockout protection
Volatility-aware sizing (futures & crypto)
⚠️ Profit is pursued only after risk is controlled.
📊 Track Record
Backtested across multiple market environments
Forward-tested and actively used by the author
Real-account trades are logged where platform rules allow
Results vary by market, timeframe, and user-defined risk settings.
🌍 Supported Markets
Designed to work across all liquid markets, including:
Stocks
Crypto (spot & futures)
Options (signal-based framework)
Futures (indices, metals, crypto futures)
The system adapts to volatility and structure — it is not market-specific.
⚖️ Leverage
Leverage is not required
If used, leverage is fully user-controlled
Risk logic scales exposure conservatively
No martingale.
No revenge sizing.
No over-exposure logic.
🧪 Backtesting
✔ Yes
Strategy logic has been backtested
Filters reduce chop, noise, and forced trades
Focus on drawdown control over curve-fitting
🛠 Support
✔ Yes
Direct author support
Ongoing improvements and updates
Feature refinement based on real usage and feedback
👥 Community
✔ Yes
Private user access
High-quality feedback environment
No public signal spam or hype-driven chat rooms
⏳ Trial Period
✔ Yes
Limited trial access available
Designed for evaluation only
Trial users do not receive full feature access
🚫 Who This Script Is NOT For
This system is not for:
Traders looking for guaranteed profits
Users expecting copy-paste “signal calls”
Over-leveraged gamblers
Those unwilling to follow risk rules
Anyone seeking overnight results
This is a discipline and automation tool, not a shortcut.
🧠 Final Positioning
This is not a signal service.
This is a risk-controlled execution framework designed to:
Enforce discipline
Reduce emotional trading
Protect capital during bad market conditions
Scale responsibly during favorable ones
BK AK-Momentum Pivot Wolf🐺 BK AK–Momentum Pivot Wolf — Momentum / Pivots / Confluence 🐺
🙏 All glory to Gd.
Built with standards and discipline passed down by my mentor — thank you for the lens and the insistence on structure over noise.
Update / Record
A previous version of this publication was hidden due to insufficient description. This republish is a complete, self-contained explanation of what the script does, how it works, and how to use it.
✨ What this script does
Pivot Wolf is a TSI-based momentum oscillator system that focuses on extremes → pivots → confirmation, then adds confluence layers (VWAP, MTF alignment, SNR, volume, regime) to reduce chop and low-quality signals.
It’s built to help you:
Identify momentum extremes using dynamic or static bands
Detect pivot points in the oscillator at those extremes
Mark divergences (regular + hidden) between price and oscillator
Confirm/grade signals using a scoring system (or legacy hard filters)
Visualize context via VWAP gating, MTF alignment, and regime state
Project post-pivot expectation zones via T1/T2 targets
Optionally enable historical learning that only applies overrides when validation is strong
🧠 How it works (high level)
1) Momentum engine (TSI blend)
Computes Fast and Slow TSI.
Optionally blends them using volatility weighting (ATR% normalized over a lookback) to adapt responsiveness.
Smooths momentum with a Signal EMA for cross/shift confirmation.
2) Bands define “extremes”
Dynamic mode uses StdDev (or robust MAD) over a lookback to size bands.
Static mode uses a fixed ± level.
Extremes are simply “momentum beyond the band,” with optional tolerance/smoothing.
3) Pivot detection (the main signals)
Uses oscillator pivot highs/lows.
A “strong” pivot is when a pivot forms outside the band (oversold/overbought).
Marker styling, sizes, and tooltips are configurable.
4) Divergence logic
Tracks the last two oscillator pivots and compares them to the last two price pivots:
Bullish divergence: price makes a lower low while oscillator makes a higher low
Bearish divergence: price makes a higher high while oscillator makes a lower high
Includes hidden divergences and optional “require extreme” filtering.
5) Confluence + scoring (0–100)
Instead of only hard rules, Pivot Wolf can compute bull/bear scores using:
VWAP position and/or slope gating
MTF direction alignment across selected timeframes
Signal-to-noise ratio filter (momentum vs signal noise)
Volume confirmation and regime adjustments
Acceleration / deceleration behavior
Structure + consolidation penalties
Signals can be shown as strong or weak (optional), based on your thresholds.
6) Targets / projections
After confirmed pivots, it projects expectation zones using recent run behavior:
T1 = 0.618 projection
T2 = 1.000 projection
Targets can display continuously or only when momentum approaches.
7) Optional historical learning
If enabled, it records pivot outcomes after N bars and runs a train/validation check before applying any learned overrides. If validation fails, it stays on manual settings.
🧭 How to use (simple workflow)
🧩 Check MTF dashboard for alignment (avoid fighting the stack).
🧱 Let momentum reach band extremes (OB/OS).
🔻🔺 Take pivot signals more seriously when score is strong + VWAP gate agrees.
💎 Use divergence as added weight, not as the trigger.
🎯 Manage around T1/T2 as structured expectation zones.
👁️🗨️ King Solomon Lens
“Solomon didn’t predict. He judged. He built tests that made truth show itself. Pivot Wolf is that: pivots as boundary stones, momentum as witness, acceleration as the confession. No hammer in the Temple — rules are cut before entry. When it’s quiet, it’s saving you. When it speaks, it’s a ruling.”
This is not financial advice. This is structure. If you wanted a fortune teller, you’ll hate this script. If you wanted a system that makes the market prove itself before you strike—welcome to the Wolf.
🙏 All glory to G-d—the source of all wisdom and every true edge. 🙏
Chip Distribution Pro// This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// Enhanced Position Cost Distribution - Auto-adaptive with improved visualization
// Works with ETFs, commodities, forex, crypto, stocks - any instrument
// @version=5
indicator('Chip Distribution Pro', overlay = true, max_lines_count = 500, max_bars_back = 500)
//#region Inputs
string GRP_GENERAL = "General Settings"
int LOOKBACK = input.int(1000, 'Lookback Bars', maxval = 20000, minval = 500, step = 250, group = GRP_GENERAL)
int CHART_X_OFFSET = input.int(100, 'Chart Offset', step = 10, group = GRP_GENERAL)
int LABEL_X_OFFSET = CHART_X_OFFSET + 4
int CHART_MAX_WIDTH = input.int(80, 'Max Width', maxval = 500, minval = 10, step = 10, group = GRP_GENERAL)
int NUM_BUCKETS = input.int(400, 'Price Buckets', maxval = 500, minval = 50, step = 50, group = GRP_GENERAL)
string GRP_AUTO = "Auto-Tuning"
bool AUTO_TUNE = input.bool(true, 'Enable Auto-Tuning', group = GRP_AUTO,
tooltip = 'Automatically adjusts turnover rate based on volatility and volume characteristics')
float MANUAL_DECAY = input.float(0.1, 'Manual Turnover Rate', minval = 0.01, maxval = 0.5, step = 0.01, group = GRP_AUTO,
tooltip = 'Only used when Auto-Tuning is disabled')
int VOLATILITY_PERIOD = input.int(20, 'Volatility Period', minval = 5, maxval = 100, group = GRP_AUTO)
string GRP_VISUAL = "Visualization"
string COLOR_SCHEME = input.string("Rainbow", "Color Scheme", options = , group = GRP_VISUAL)
color PROFIT_COLOR_LIGHT = input.color(#26a69a, 'Profit Light', group = GRP_VISUAL)
color PROFIT_COLOR_DARK = input.color(#004d40, 'Profit Dark', group = GRP_VISUAL)
color LOSS_COLOR_LIGHT = input.color(#ef5350, 'Loss Light', group = GRP_VISUAL)
color LOSS_COLOR_DARK = input.color(#b71c1c, 'Loss Dark', group = GRP_VISUAL)
color CURRENT_PRICE_COLOR = input.color(color.yellow, 'Current Price', group = GRP_VISUAL)
color AVG_PRICE_COLOR = input.color(#2196F3, 'Average Cost', group = GRP_VISUAL)
color PEAK_COLOR = input.color(#FF9800, 'Peak Concentration', group = GRP_VISUAL)
color STATS_COLOR = input.color(#434651, 'Stats Background', group = GRP_VISUAL)
string GRP_LEVELS = "Key Levels"
bool SHOW_SUPPORT_RESISTANCE = input.bool(true, 'Show Support/Resistance Zones', group = GRP_LEVELS)
bool SHOW_PEAK = input.bool(true, 'Show Peak Concentration', group = GRP_LEVELS)
float SR_THRESHOLD = input.float(0.7, 'S/R Detection Threshold', minval = 0.3, maxval = 0.95, step = 0.05, group = GRP_LEVELS,
tooltip = 'Minimum concentration (relative to peak) to mark as support/resistance')
string GRP_SIGNALS = "Signals Panel"
bool SHOW_SIGNALS = input.bool(true, 'Show Signal Panel', group = GRP_SIGNALS)
bool SHOW_KEY_LEVELS = input.bool(true, 'Show Key Price Levels', group = GRP_SIGNALS)
bool SHOW_TREND_ARROW = input.bool(true, 'Show Trend Arrow', group = GRP_SIGNALS)
bool SHOW_PRESSURE_BAR = input.bool(true, 'Show Pressure Bar', group = GRP_SIGNALS)
// Colors for key levels
color SUPPORT_COLOR = input.color(#00E676, 'Support Level', group = GRP_LEVELS)
color RESISTANCE_COLOR = input.color(#FF5252, 'Resistance Level', group = GRP_LEVELS)
color BREAKOUT_COLOR = input.color(#FFD600, 'Breakout Level', group = GRP_LEVELS)
//#endregion
//#region Candle Type
type Candle
int idx
float hi
float lo
float vol
float relativeVol
float atrPct
//#endregion
//#region PCD Type
type PCD
array candles
float minPrice
float maxPrice
float priceStep
array lines
label currentPriceLabel
label avgPriceLabel
label peakLabel
label statsLabel
label signalLabel
array srZones
float calculatedTurnover
// New visualization elements
line supportLine
line resistanceLine
line avgCostLine
label trendArrow
box pressureBar
box pressureFill
label pressureLabel
// Create a new price label
newPriceLabel(color bg, color txtColor) =>
label.new(0, 0, '', style = label.style_label_left, color = bg, textcolor = txtColor, size = size.small)
// Create a new PCD instance
newPCD() =>
array lns = array.new(NUM_BUCKETS)
for i = 0 to NUM_BUCKETS - 1
array.set(lns, i, line.new(0, 0, 0, 0))
PCD.new(
candles = array.new(0),
lines = lns,
currentPriceLabel = newPriceLabel(color.new(#00BCD4, 0), color.white),
avgPriceLabel = newPriceLabel(AVG_PRICE_COLOR, color.white),
peakLabel = newPriceLabel(PEAK_COLOR, color.white),
statsLabel = label.new(0, 0, '', style = label.style_label_up, size = size.small,
textalign = text.align_left, color = color.new(STATS_COLOR, 20), textcolor = color.white),
signalLabel = label.new(0, 0, '', style = label.style_label_left, size = size.small,
textalign = text.align_left, color = color.new(#1a1a2e, 20), textcolor = color.white),
srZones = array.new(0),
calculatedTurnover = 0.1,
minPrice = na,
maxPrice = na,
priceStep = na,
supportLine = line.new(0, 0, 0, 0, color = SUPPORT_COLOR, width = 2, style = line.style_dashed),
resistanceLine = line.new(0, 0, 0, 0, color = RESISTANCE_COLOR, width = 2, style = line.style_dashed),
avgCostLine = line.new(0, 0, 0, 0, color = AVG_PRICE_COLOR, width = 2, style = line.style_dotted),
trendArrow = label.new(0, 0, '', style = label.style_label_center, size = size.large, textcolor = color.white),
pressureBar = box.new(0, 0, 0, 0, bgcolor = color.new(#424242, 50), border_color = color.gray),
pressureFill = box.new(0, 0, 0, 0, bgcolor = color.green, border_color = na),
pressureLabel = label.new(0, 0, '', style = label.style_label_right, size = size.tiny, color = color.new(#000000, 100), textcolor = color.white))
// Auto-calculate turnover rate based on instrument characteristics
calcAdaptiveTurnover(float atrPct, float volRatio) =>
float safeAtrPct = na(atrPct) or atrPct <= 0 ? 0.02 : atrPct
float safeVolRatio = na(volRatio) or volRatio <= 0 ? 1.0 : volRatio
float volBasedTurnover = math.max(0.03, math.min(0.3, safeAtrPct * 3))
float volAdjustment = math.max(0.5, math.min(2.0, safeVolRatio))
float turnover = volBasedTurnover * volAdjustment
math.max(0.02, math.min(0.4, turnover))
// Store candle method
method storeCandle(PCD this, int barIdx, float hiPrice, float loPrice, float volVal, float avgVol, float atrPct) =>
if not na(hiPrice) and not na(loPrice) and not na(volVal) and volVal > 0
float safeAvgVol = na(avgVol) or avgVol <= 0 ? volVal : avgVol
float relVol = volVal / safeAvgVol
float safeAtrPct = na(atrPct) ? 0.02 : atrPct
bool modified = false
int candleSize = array.size(this.candles)
if candleSize > 0
Candle c = array.get(this.candles, candleSize - 1)
if c.idx == barIdx
c.hi := hiPrice
c.lo := loPrice
c.vol := volVal
c.relativeVol := relVol
c.atrPct := safeAtrPct
modified := true
if not modified
Candle c = Candle.new(barIdx, hiPrice, loPrice, volVal, relVol, safeAtrPct)
array.push(this.candles, c)
this.minPrice := na(this.minPrice) ? loPrice : math.min(this.minPrice, loPrice)
this.maxPrice := na(this.maxPrice) ? hiPrice : math.max(this.maxPrice, hiPrice)
float priceRange = this.maxPrice - this.minPrice
this.priceStep := priceRange > 0 ? priceRange / NUM_BUCKETS : 0.0001
// Get bucket index for price
method getBucketIndex(PCD this, float price) =>
if na(this.priceStep) or this.priceStep <= 0 or na(this.minPrice)
0
else
int idx = int(math.floor((price - this.minPrice) / this.priceStep))
math.max(0, math.min(idx, NUM_BUCKETS - 1))
// Get price for bucket index
method getBucketedPrice(PCD this, int bucketIdx) =>
int safeIndex = math.max(0, math.min(bucketIdx, NUM_BUCKETS - 1))
float safeStep = na(this.priceStep) or this.priceStep <= 0 ? 0.0001 : this.priceStep
float safeMin = na(this.minPrice) ? 0.0 : this.minPrice
(safeIndex + 0.5) * safeStep + safeMin
// Get rainbow color based on position (0.0 = bottom/red, 1.0 = top/violet)
getRainbowColor(float position, float intensityRatio) =>
float pos = math.max(0.0, math.min(1.0, position))
int transparency = int(math.round((1.0 - intensityRatio) * 50))
// Rainbow spectrum: red -> orange -> yellow -> green -> cyan -> blue -> violet
if pos < 0.166
color.new(color.from_gradient(pos, 0.0, 0.166, #FF0000, #FF7F00), transparency)
else if pos < 0.333
color.new(color.from_gradient(pos, 0.166, 0.333, #FF7F00, #FFFF00), transparency)
else if pos < 0.5
color.new(color.from_gradient(pos, 0.333, 0.5, #FFFF00, #00FF00), transparency)
else if pos < 0.666
color.new(color.from_gradient(pos, 0.5, 0.666, #00FF00, #00FFFF), transparency)
else if pos < 0.833
color.new(color.from_gradient(pos, 0.666, 0.833, #00FFFF, #0000FF), transparency)
else
color.new(color.from_gradient(pos, 0.833, 1.0, #0000FF, #8B00FF), transparency)
// Get color based on scheme and intensity
getColor(bool isProfitable, float intensity, float maxIntensity, int bucketIdx) =>
float safeMax = maxIntensity > 0 ? maxIntensity : 1.0
float ratio = math.max(0.0, math.min(1.0, intensity / safeMax))
float positionRatio = bucketIdx / math.max(1.0, NUM_BUCKETS - 1.0)
if COLOR_SCHEME == "Rainbow"
getRainbowColor(positionRatio, ratio)
else if COLOR_SCHEME == "Gradient"
if isProfitable
color.from_gradient(ratio, 0.0, 1.0, PROFIT_COLOR_DARK, PROFIT_COLOR_LIGHT)
else
color.from_gradient(ratio, 0.0, 1.0, LOSS_COLOR_DARK, LOSS_COLOR_LIGHT)
else if COLOR_SCHEME == "Heatmap"
color.from_gradient(ratio, 0.0, 1.0, #1a237e, #f44336)
else
if isProfitable
color.new(#5d606b, int(math.round((1.0 - ratio) * 70)))
else
color.new(#e91e63, int(math.round((1.0 - ratio) * 70)))
// Update method
method update(PCD this) =>
int candleCount = array.size(this.candles)
if candleCount > 0 and not na(this.priceStep) and this.priceStep > 0
// Create distribution array
array dist = array.new_float(NUM_BUCKETS, 0.0)
// Process each candle
for candleIdx = 0 to candleCount - 1
Candle candle = array.get(this.candles, candleIdx)
bool isFirstCandle = candleIdx == 0
float turnover = AUTO_TUNE ? calcAdaptiveTurnover(candle.atrPct, candle.relativeVol) : MANUAL_DECAY * candle.relativeVol
turnover := math.min(turnover, 0.95)
this.calculatedTurnover := turnover
int startIdx = this.getBucketIndex(candle.lo)
int endIdx = this.getBucketIndex(candle.hi)
int buckets = math.max(1, endIdx - startIdx + 1)
if isFirstCandle
float initialWeight = 1.0 / buckets
for i = startIdx to endIdx
array.set(dist, i, initialWeight)
else
float decayedAmount = 0.0
for i = 0 to NUM_BUCKETS - 1
float oldVal = array.get(dist, i)
float newVal = oldVal * (1.0 - turnover)
array.set(dist, i, newVal)
decayedAmount += oldVal - newVal
float addPerBucket = decayedAmount / buckets
for i = startIdx to endIdx
array.set(dist, i, array.get(dist, i) + addPerBucket)
// Normalize distribution
float totalWeight = 0.0
for i = 0 to NUM_BUCKETS - 1
totalWeight += array.get(dist, i)
if totalWeight > 0
for i = 0 to NUM_BUCKETS - 1
array.set(dist, i, array.get(dist, i) / totalWeight)
// Find peak
float maxWeight = array.max(dist)
if na(maxWeight) or maxWeight <= 0
maxWeight := 0.001
int peakIndex = array.indexof(dist, maxWeight)
if peakIndex < 0
peakIndex := 0
float peakPrice = this.getBucketedPrice(peakIndex)
// Find support/resistance zones
array srIndices = array.new(0)
if SHOW_SUPPORT_RESISTANCE
bool inZone = false
int zoneStart = 0
for i = 0 to NUM_BUCKETS - 1
bool isHighConcentration = array.get(dist, i) >= maxWeight * SR_THRESHOLD
if isHighConcentration and not inZone
inZone := true
zoneStart := i
else if not isHighConcentration and inZone
inZone := false
array.push(srIndices, int(math.floor((zoneStart + i) / 2)))
if inZone
array.push(srIndices, int(math.floor((zoneStart + NUM_BUCKETS - 1) / 2)))
// Clear old SR zones
int srZoneSize = array.size(this.srZones)
if srZoneSize > 0
for i = 0 to srZoneSize - 1
box b = array.get(this.srZones, i)
box.set_lefttop(b, 0, 0)
box.set_rightbottom(b, 0, 0)
// Draw the distribution
float lowestDisplayedPrice = na
float highestDisplayedPrice = na
for i = 0 to NUM_BUCKETS - 1
float weight = array.get(dist, i)
float price = (i + 0.5) * this.priceStep + this.minPrice
int width = int(math.round(weight / maxWeight * CHART_MAX_WIDTH))
line ln = array.get(this.lines, i)
if width > 0
if na(lowestDisplayedPrice)
lowestDisplayedPrice := price
highestDisplayedPrice := price
int x1 = bar_index + CHART_X_OFFSET
int x2 = x1 - width
bool isProfitable = price < close
color c = getColor(isProfitable, weight, maxWeight, i)
line.set_xy1(ln, x1, price)
line.set_xy2(ln, x2, price)
line.set_color(ln, c)
else
line.set_xy1(ln, 0, 0)
line.set_xy2(ln, 0, 0)
// Draw S/R zones
if SHOW_SUPPORT_RESISTANCE
int srCount = array.size(srIndices)
int leftBar = math.max(0, bar_index - LOOKBACK)
if srCount > 0
for i = 0 to srCount - 1
int idx = array.get(srIndices, i)
float zonePrice = this.getBucketedPrice(idx)
float zoneHalfHeight = this.priceStep * 3
box b = na
if i < array.size(this.srZones)
b := array.get(this.srZones, i)
box.set_lefttop(b, leftBar, zonePrice + zoneHalfHeight)
box.set_rightbottom(b, bar_index, zonePrice - zoneHalfHeight)
else
b := box.new(leftBar, zonePrice + zoneHalfHeight, bar_index, zonePrice - zoneHalfHeight, bgcolor = color.new(PEAK_COLOR, 85), border_color = color.new(PEAK_COLOR, 60))
array.push(this.srZones, b)
// Calculate cumulative distribution
array cumdist = array.copy(dist)
for i = 1 to NUM_BUCKETS - 1
array.set(cumdist, i, array.get(cumdist, i - 1) + array.get(cumdist, i))
// Highlight current price
int closeIndex = this.getBucketIndex(close)
if closeIndex >= 0 and closeIndex < NUM_BUCKETS
line.set_color(array.get(this.lines, closeIndex), CURRENT_PRICE_COLOR)
// Calculate stats
float totalShares = array.get(cumdist, NUM_BUCKETS - 1)
int profitIndex = math.min(closeIndex + 1, NUM_BUCKETS - 1)
float profitRatio = totalShares > 0 ? array.get(cumdist, profitIndex) / totalShares : 0.0
// Calculate average price
float avg = 0.0
for i = 0 to NUM_BUCKETS - 1
float weight = array.get(dist, i)
float price = this.getBucketedPrice(i)
avg += price * weight
int avgIndex = this.getBucketIndex(avg)
if avgIndex >= 0 and avgIndex < NUM_BUCKETS
line.set_color(array.get(this.lines, avgIndex), AVG_PRICE_COLOR)
// Peak concentration - highlight line
if SHOW_PEAK and peakIndex >= 0 and peakIndex < NUM_BUCKETS
line.set_color(array.get(this.lines, peakIndex), PEAK_COLOR)
// Smart label positioning - avoid overlaps
float priceRange = na(highestDisplayedPrice) or na(lowestDisplayedPrice) ? close * 0.01 : (highestDisplayedPrice - lowestDisplayedPrice)
float minLabelSpacing = priceRange * 0.025
// Sort prices and assign staggered X offsets
float currentY = close
float avgY = avg
float peakY = peakPrice
// Adjust avg label if too close to current
if math.abs(avgY - currentY) < minLabelSpacing
avgY := currentY > avgY ? avgY - minLabelSpacing : avgY + minLabelSpacing
// Adjust peak label if too close to current or avg
if SHOW_PEAK
if math.abs(peakY - currentY) < minLabelSpacing
peakY := currentY > peakY ? peakY - minLabelSpacing : peakY + minLabelSpacing
if math.abs(peakY - avgY) < minLabelSpacing
peakY := avgY > peakY ? peakY - minLabelSpacing : peakY + minLabelSpacing
// Position price labels - compact format, right side of distribution
label.set_text(this.currentPriceLabel, str.format('{0,number,#.##}', close))
label.set_xy(this.currentPriceLabel, bar_index + LABEL_X_OFFSET + 2, close)
label.set_style(this.currentPriceLabel, label.style_label_left)
label.set_size(this.currentPriceLabel, size.tiny)
label.set_text(this.avgPriceLabel, str.format('{0,number,#.##} AVG', avg))
label.set_xy(this.avgPriceLabel, bar_index + LABEL_X_OFFSET + 2, avgY)
label.set_style(this.avgPriceLabel, label.style_label_left)
label.set_size(this.avgPriceLabel, size.tiny)
if SHOW_PEAK
label.set_text(this.peakLabel, str.format('{0,number,#.##} PEAK', peakPrice))
label.set_xy(this.peakLabel, bar_index + LABEL_X_OFFSET + 2, peakY)
label.set_style(this.peakLabel, label.style_label_left)
label.set_size(this.peakLabel, size.tiny)
// Calculate ranges safely
float safeTotalShares = totalShares > 0 ? totalShares : 1.0
int idx05 = array.binary_search_leftmost(cumdist, safeTotalShares * 0.05)
int idx95 = array.binary_search_leftmost(cumdist, safeTotalShares * 0.95)
int idx15 = array.binary_search_leftmost(cumdist, safeTotalShares * 0.15)
int idx85 = array.binary_search_leftmost(cumdist, safeTotalShares * 0.85)
float ninetyPctLow = this.getBucketedPrice(idx05)
float ninetyPctHigh = this.getBucketedPrice(idx95)
float seventyPctLow = this.getBucketedPrice(idx15)
float seventyPctHigh = this.getBucketedPrice(idx85)
float rangeDenom = ninetyPctHigh - ninetyPctLow
float rangeOverlap = rangeDenom != 0 ? (seventyPctHigh - seventyPctLow) / rangeDenom : 0.0
// Calculate chip concentration
float concentration = rangeOverlap * 100
string concentrationDesc = concentration < 50 ? "High" : concentration < 70 ? "Medium" : "Dispersed"
// Pressure analysis
float safeAvg = avg > 0 ? avg : close
float priceVsAvg = ((close - safeAvg) / safeAvg) * 100
string pressure = priceVsAvg > 5 ? "Strong Bullish" : priceVsAvg > 1 ? "Bullish" :
priceVsAvg < -5 ? "Strong Bearish" : priceVsAvg < -1 ? "Bearish" : "Neutral"
// Price vs Peak
float safePeak = peakPrice > 0 ? peakPrice : close
float priceVsPeak = ((close - safePeak) / safePeak) * 100
string peakRelation = close > peakPrice ? "Above Peak" : close < peakPrice ? "Below Peak" : "At Peak"
// Stats panel - positioned at bottom, compact
float displayedRange = na(highestDisplayedPrice) or na(lowestDisplayedPrice) ? close * 0.02 : highestDisplayedPrice - lowestDisplayedPrice
label.set_text(this.statsLabel, str.format(
'90%: {0,number,#.##} - {1,number,#.##} | 70%: {2,number,#.##} - {3,number,#.##}',
ninetyPctLow, ninetyPctHigh, seventyPctLow, seventyPctHigh))
if not na(lowestDisplayedPrice) and displayedRange > 0
label.set_y(this.statsLabel, lowestDisplayedPrice - displayedRange * 0.05)
label.set_style(this.statsLabel, label.style_label_up)
label.set_x(this.statsLabel, bar_index + CHART_X_OFFSET - 30)
label.set_size(this.statsLabel, size.tiny)
// Signal panel - hidden (info moved to trend arrow and pressure bar)
label.set_text(this.signalLabel, "")
label.set_xy(this.signalLabel, bar_index, close)
// === NEW PROFESSIONAL VISUALIZATIONS ===
// 1. Key Level Lines - Support, Resistance, and Average Cost extending across chart
if SHOW_KEY_LEVELS
int chartLeft = math.max(0, bar_index - LOOKBACK)
int chartRight = bar_index + CHART_X_OFFSET - 5
// Average cost line (horizontal dotted blue line)
line.set_xy1(this.avgCostLine, chartLeft, avg)
line.set_xy2(this.avgCostLine, chartRight, avg)
line.set_color(this.avgCostLine, AVG_PRICE_COLOR)
// Find strongest support (highest concentration below current price)
float strongestSupport = na
float strongestSupportWeight = 0.0
float strongestResistance = na
float strongestResistanceWeight = 0.0
for i = 0 to NUM_BUCKETS - 1
float bucketPrice = this.getBucketedPrice(i)
float bucketWeight = array.get(dist, i)
if bucketPrice < close and bucketWeight > strongestSupportWeight
strongestSupport := bucketPrice
strongestSupportWeight := bucketWeight
if bucketPrice > close and bucketWeight > strongestResistanceWeight
strongestResistance := bucketPrice
strongestResistanceWeight := bucketWeight
// Support line (green dashed)
if not na(strongestSupport)
line.set_xy1(this.supportLine, chartLeft, strongestSupport)
line.set_xy2(this.supportLine, chartRight, strongestSupport)
line.set_color(this.supportLine, SUPPORT_COLOR)
else
line.set_xy1(this.supportLine, bar_index, close)
line.set_xy2(this.supportLine, bar_index, close)
line.set_color(this.supportLine, color.new(SUPPORT_COLOR, 100))
// Resistance line (red dashed)
if not na(strongestResistance)
line.set_xy1(this.resistanceLine, chartLeft, strongestResistance)
line.set_xy2(this.resistanceLine, chartRight, strongestResistance)
line.set_color(this.resistanceLine, RESISTANCE_COLOR)
else
line.set_xy1(this.resistanceLine, bar_index, close)
line.set_xy2(this.resistanceLine, bar_index, close)
line.set_color(this.resistanceLine, color.new(RESISTANCE_COLOR, 100))
// 2. Trend Direction Arrow
if SHOW_TREND_ARROW
string trendSymbol = priceVsAvg > 5 ? "▲▲" : priceVsAvg > 1 ? "▲" :
priceVsAvg < -5 ? "▼▼" : priceVsAvg < -1 ? "▼" : "◆"
color trendColor = priceVsAvg > 5 ? color.new(#00E676, 0) : priceVsAvg > 1 ? color.new(#4CAF50, 0) :
priceVsAvg < -5 ? color.new(#FF1744, 0) : priceVsAvg < -1 ? color.new(#EF5350, 0) : color.new(#9E9E9E, 0)
string trendText = trendSymbol + " " + pressure
label.set_text(this.trendArrow, trendText)
float arrowY = na(highestDisplayedPrice) ? close : highestDisplayedPrice + displayedRange * 0.12
label.set_xy(this.trendArrow, bar_index + CHART_X_OFFSET - 40, arrowY)
label.set_color(this.trendArrow, color.new(trendColor, 70))
label.set_textcolor(this.trendArrow, trendColor)
label.set_size(this.trendArrow, size.large)
// 3. Pressure Bar (Profit/Loss ratio visualization)
if SHOW_PRESSURE_BAR
float barWidth = 8.0
float barHeight = displayedRange * 0.25
float barX = bar_index + CHART_X_OFFSET + 5
float barTop = na(highestDisplayedPrice) ? close + barHeight/2 : highestDisplayedPrice - displayedRange * 0.02
float barBottom = barTop - barHeight
// Background bar
box.set_lefttop(this.pressureBar, int(barX), barTop)
box.set_rightbottom(this.pressureBar, int(barX + barWidth), barBottom)
box.set_bgcolor(this.pressureBar, color.new(#424242, 60))
// Fill based on profit ratio (green from bottom)
float fillHeight = barHeight * profitRatio
float fillTop = barBottom + fillHeight
color fillColor = profitRatio > 0.7 ? color.new(#00E676, 30) :
profitRatio > 0.5 ? color.new(#4CAF50, 30) :
profitRatio > 0.3 ? color.new(#FFC107, 30) : color.new(#FF5252, 30)
box.set_lefttop(this.pressureFill, int(barX), fillTop)
box.set_rightbottom(this.pressureFill, int(barX + barWidth), barBottom)
box.set_bgcolor(this.pressureFill, fillColor)
// Pressure label
string pressureText = str.format('{0,number,#}%', profitRatio * 100)
label.set_text(this.pressureLabel, pressureText)
label.set_xy(this.pressureLabel, int(barX - 1), barTop + displayedRange * 0.01)
label.set_textcolor(this.pressureLabel, fillColor)
//#endregion
//#region Main
= request.security(syminfo.tickerid, 'D', , lookahead = barmerge.lookahead_off)
float atrPercent = dailyClose > 0 ? dailyATR / dailyClose : 0.02
if timeframe.in_seconds(timeframe.period) <= timeframe.in_seconds('D')
var PCD pcd = newPCD()
if last_bar_index - bar_index < LOOKBACK
pcd.storeCandle(dailyBarIdx, dailyHigh, dailyLow, dailyVolume, avgVolume, atrPercent)
if barstate.islast
pcd.update()
//#endregion
Neeson bitcoin Dynamic ATR Trailing SystemNeeson bitcoin Dynamic ATR Trailing System: A Comprehensive Guide to Volatility-Adaptive Trend Following
Introduction
The Dynamic ATR Trailing System (DATR-TS) represents a sophisticated approach to trend following that transcends conventional moving average or breakout-based methodologies. Unlike standard trend-following systems that rely on price pattern recognition or fixed parameter oscillators, this system operates on the principle of volatility-adjusted position management—a nuanced approach that dynamically adapts to changing market conditions rather than imposing rigid rules on market behavior.
Originality and Innovation
Distinct Methodological Approach
What sets DATR-TS apart from hundreds of existing trend-following systems is its dual-layered conditional execution framework. While most trend-following systems fall into one of three broad categories—moving average crossovers, channel breakouts, or momentum oscillators—this system belongs to the more specialized category of volatility-normalized trailing stop systems.
Key Original Contributions:
Volatility-Threshold Signal Filtering: Most trend systems generate signals continuously, leading to overtrading during low-volatility periods. DATR-TS implements a proprietary volatility filter that requires minimum market movement before generating signals, effectively separating high-probatility trend opportunities from market noise.
Self-Contained Position State Management: Unlike traditional systems that require external position tracking, DATR-TS maintains an internal position state that prevents contradictory signals and creates a closed-loop decision framework.
Dynamic Risk Parameter Adjustment: The system doesn't use fixed percentage stops or rigid ATR multiples. Instead, it implements a responsive adjustment mechanism that widens stops during high volatility and tightens them during low volatility, creating an optimal balance between risk protection and opportunity capture.
Trader-Centric Visualization Philosophy: Beyond mere signal generation, the system provides a comprehensive visual feedback system designed to align with human cognitive patterns, reducing emotional decision-making through consistent color coding and information hierarchy.
Technical Implementation and Functionality
Core Operational Mechanism
DATR-TS implements a volatility-adjusted trend persistence model that operates on the principle that trending markets exhibit characteristic volatility signatures. The system specifically targets medium-term directional movements (typically lasting 5-20 days) rather than short-term scalping opportunities or long-term position trades.
The Four-Pillar Architecture:
Volatility Measurement and Normalization
Calculates Average True Range (ATR) over a user-defined period
Converts absolute volatility to percentage terms relative to price
Compares current volatility against user-defined thresholds to filter suboptimal conditions
Dynamic Trailing Stop Algorithm
Establishes an initial stop distance based on current volatility
Implements a four-state adjustment mechanism that responds to price action
Maintains stop position during trend continuation while allowing for trend reversal detection
Conditional Signal Generation
Generates entry signals only when price action meets both directional and volatility criteria
Produces exit signals based on trailing stop penetration
Incorporates position state awareness to prevent conflicting signals
Comprehensive Feedback System
Provides multi-layer visual information including dynamic stop lines, signal labels, and color-coded price action
Displays real-time metrics through an integrated dashboard
Offers configurable visualization options for different trading styles
Specific Trend-Following Methodology
DATR-TS employs a volatility-normalized trailing stop breakout approach, which differs significantly from common trend identification methods:
Not a moving average crossover system (like MACD or traditional MA crosses)
Not a channel breakout system (like Bollinger Band or Donchian Channel breaks)
Not a momentum oscillator system (like RSI or Stochastic trend following)
Not a price pattern recognition system (like head-and-shoulders or triangle breaks)
Instead, it belongs to the more specialized category of volatility-adjusted stop-and-reverse systems that:
Wait for market volatility to reach actionable levels
Establish positions when price confirms directional bias through stop penetration
Manage risk dynamically based on evolving market conditions
Exit positions when the trend exhausts itself through stop violation
Practical Application and Usage
Market Environment Optimization
Ideal Conditions:
Trending markets with sustained directional movement
Medium volatility environments (neither excessively calm nor chaotic)
Timeframes: 4-hour to daily charts for optimal signal quality
Instruments: Forex majors, commodity futures, equity indices
Suboptimal Conditions:
Ranging or consolidating markets
Extreme volatility events or news-driven spikes
Very short timeframes (below 1-hour)
Illiquid or highly manipulated instruments
Parameter Configuration Strategy
Core Parameter Philosophy:
ATR Length (Default: 21 periods)
Controls the system's memory of volatility
Shorter lengths increase sensitivity but may cause overtrading
Longer lengths provide smoother signals but may lag during volatility shifts
ATR Multiplier (Default: 6.3x)
Determines the initial risk buffer
Lower values (4-5x) create tighter stops for conservative trading
Higher values (6-8x) allow for larger trends but increase drawdown risk
Volatility Threshold (Default: 1.5%)
Filters out low-quality trading environments
Adjust based on market characteristics (higher for volatile markets)
Acts as a quality control mechanism for signals
Trading Workflow and Execution
Signal Interpretation and Action:
Entry Protocol:
Wait for BLUE "BUY" signal label appearance
Confirm volatility conditions meet threshold requirements
Enter long position at market or next reasonable opportunity
Set initial stop at displayed dynamic stop level
Position Management:
Monitor dynamic stop line for position adjustment
Allow profits to run while stop protects capital
No manual adjustment required—system manages stop automatically
Exit Protocol:
Exit on ORANGE "SELL" signal label appearance
Alternative exit if price hits dynamic stop level
System will generate new entry signal if conditions warrant re-entry
Risk Management Integration:
Position sizing based on distance to dynamic stop
Volatility filter prevents trades during unfavorable conditions
Clear visual feedback on current risk exposure
Built-in protection against overtrading
Philosophical Foundation and Market Theory
Core Trading Principles
DATR-TS embodies several foundational market principles:
Volatility Defines Opportunity
Markets don't trend continuously—they alternate between trending and ranging phases
Volatility provides the energy for trends to develop and sustain
By measuring and filtering volatility, we can focus on high-probability trend phases
Risk Should Be Proportional
Fixed percentage stops ignore market context
Dynamic stops that adjust with volatility provide more appropriate risk management
Position sizing should reflect current market conditions, not arbitrary rules
Simplicity Through Sophistication
Complex systems often fail in real-world conditions
A simple core algorithm with intelligent filtering outperforms complex multi-indicator approaches
Clear visual feedback reduces cognitive load and emotional interference
Trends Persist Until Proven Otherwise
Markets exhibit momentum characteristics
Once a trend establishes itself, it tends to continue
The trailing stop methodology captures this persistence while providing exit mechanisms
Mathematical and Statistical Foundation
The system operates on several statistical market observations:
Volatility Clustering Phenomenon
High volatility periods tend to follow high volatility periods
Low volatility periods tend to follow low volatility periods
By filtering for adequate volatility, we increase the probability of capturing meaningful trends
Trend Magnitude Distribution
Most trends are small to medium in magnitude
Very large trends are rare but account for disproportionate returns
The dynamic stop methodology allows capture of varying trend magnitudes
Autocorrelation in Price Movements
Price movements exhibit short-term positive autocorrelation during trends
This persistence allows trailing stops to capture continued movement
The system leverages this characteristic without requiring explicit autocorrelation calculation
Performance Characteristics and Expectations
Typical System Behavior
Signal Frequency:
Low to moderate signal generation (prevents overtrading)
Signals concentrated during trending market phases
Extended periods without signals during ranging conditions
Risk-Reward Profile:
Win rate typically 40-60% in trending conditions
Average win larger than average loss
Risk-reward ratios of 1:2 to 1:3 achievable
Drawdown Patterns:
Controlled through volatility adjustment
Larger drawdowns during extended ranging periods
Recovery typically follows when trending conditions resume
Comparison with Alternative Approaches
Versus Moving Average Systems:
Less prone to whipsaws during ranging markets
Better adaptation to changing volatility conditions
Clearer exit signals through stop levels
Versus Channel Breakout Systems:
More responsive to emerging trends
Lower false breakout probability
Dynamic risk adjustment rather than fixed parameters
Versus Momentum Oscillator Systems:
Better trend persistence capture
Less susceptible to overbought/oversold false signals
Clearer position management rules
Educational Value and Skill Development
Learning Opportunities
DATR-TS serves as more than just a trading tool—it provides educational value through:
Market Condition Awareness
Teaches traders to distinguish between trending and ranging markets
Develops understanding of volatility's role in trading opportunities
Encourages patience and selectivity in trade execution
Risk Management Discipline
Demonstrates dynamic position sizing principles
Illustrates the importance of adaptive stops
Reinforces the concept of risk-adjusted returns
Psychological Skill Development
Reduces emotional trading through clear rules
Builds patience through conditional execution
Develops discipline through systematic approach
Customization and Evolution
The system provides a foundation for further development:
Beginner Level:
Use default parameters for initial learning
Focus on signal recognition and execution discipline
Develop understanding of system behavior across market conditions
Intermediate Level:
Adjust parameters based on specific market characteristics
Combine with complementary analysis techniques
Develop personal variations based on trading style
Advanced Level:
Integrate with portfolio management systems
Develop automated execution frameworks
Create derivative systems for specialized applications
Conclusion: The Modern Trend-Following Paradigm
The Dynamic ATR Trailing System represents a significant evolution in trend-following methodology. By moving beyond simple price pattern recognition or fixed parameter oscillators, it embraces the complex reality of financial markets where volatility, trend persistence, and risk management interact dynamically.
This system doesn't claim to predict market direction or identify tops and bottoms. Instead, it provides a systematic framework for participating in trends when they emerge, managing risk appropriately as conditions change, and preserving capital during unfavorable environments.
For traders seeking a methodology that combines mathematical rigor with practical execution, adapts to changing market conditions rather than fighting against them, and provides clear, actionable information without cognitive overload, DATR-TS offers a sophisticated yet accessible approach to modern trend following.
The true value lies not in any single signal or parameter setting, but in the comprehensive philosophy of volatility-aware, risk-adjusted, conditionally-executed trend participation that the system embodies—a philosophy that aligns with how markets actually behave rather than how we might wish them to behave.
OHLC+ Pre Market + ORB + 9 21 200 EMAs + VWAPOHLC Suite - Complete Price Level & Technical Indicator Package
This all-in-one indicator provides essential price levels and technical indicators for intraday trading, combining multiple reference points in a single, customizable overlay.
Features:
📊 Previous Day's OHLC
Open, High, Low, and Close levels from the previous trading day
Helps identify key support/resistance levels and reference points
Customizable line styles (Solid/Dashed/Dotted) and colors
📈 Today's OHLC
Current day's Open, High, Low, and Close levels
Real-time updates as price action develops
Separate styling options from previous day levels
🌅 Premarket High/Low
Tracks high and low during premarket hours (4:00 AM - 9:30 AM ET)
Essential for gap trading and identifying early morning range
Displays after regular session opens
⚡ Opening Range Breakout (ORB)
Calculates high/low of first 15 minutes (9:30 AM - 9:45 AM ET)
Popular for momentum and breakout strategies
Shows range boundaries after initial period
📉 Exponential Moving Averages (EMAs)
EMA 9 (short-term trend)
EMA 21 (intermediate trend)
EMA 200 (long-term trend/major support-resistance)
Toggle each EMA independently
📊 Volume Weighted Average Price (VWAP)
Standard VWAP calculation using hlc3
Key institutional reference level
Useful for mean reversion and trend following
Customization Options:
Individual color and opacity controls for all elements
Show/hide any component independently
Adjustable line styles for different level types
Price labels with abbreviations or actual values
Clean, organized settings interface
Best For:
Day traders and swing traders
Multi-timeframe analysis
Support/resistance identification
Breakout and range trading strategies
Institutional level awareness
Settings:
All colors, transparencies, line styles, and visibility options are fully customizable through the indicator settings panel. Default configuration provides optimal visibility with distinct colors for different level types.
CVD-MACD### CVD-MACD (Research)
The CVD-MACD is a research-oriented indicator that combines Cumulative Volume Delta (CVD) with the classic MACD framework to provide insights into market momentum and potential reversals. Unlike a standard MACD based on price, this version uses CVD (the running total of buy vs. sell volume delta) as its input source, offering a volume-driven perspective on trend strength and divergences.
Key Features:
- **CVD-Based MACD Calculation**: Computes MACD using CVD instead of price, highlighting volume imbalances that may precede price moves.
- **Dual Divergence Detection**: Identifies bullish/bearish divergences on both the MACD line and histogram, with configurable pivot lookbacks and filters (e.g., momentum decay and zero-side consistency).
- **Visual Flexibility**: Toggle divergences in the indicator pane or overlaid on the main chart, with optional raw CVD line for reference.
- **Alerts**: Built-in conditions for bullish and bearish divergences to notify users of potential setups.
###This indicator is designed for research and experimentation—it's not financial advice. It performs best on liquid assets with reliable volume data (e.g., stocks, futures). I've shared this to gather community feedback: please test it thoroughly and point out any bugs, inefficiencies, or improvements! For example, if you spot issues with divergence detection on certain timeframes or symbols, let me know in the comments. Your input will help refine it.
Inspired by volume analysis techniques; open to collaborations or forks.
## User Manual for CVD-MACD (Research)
### Overview
The CVD-MACD indicator transforms traditional MACD by using Cumulative Volume Delta (CVD) as the base input. CVD accumulates the net delta between estimated buy and sell volume per bar, providing a volume-centric view of momentum. The indicator plots a MACD line, signal line, and histogram, while also detecting divergences on both the MACD line and histogram for potential reversal signals.
This manual covers setup, interpretation, and troubleshooting.
Note: This is a research tool—backtest and validate on your own data before using in live trading.
### Installation and Setup
1. **Add to Chart**: Search for "CVD-MACD (Research)" in TradingView's indicator library or paste the script into the Pine Editor and add it to your chart.
2. **Compatibility**: Works on any timeframe and symbol with volume data. Best on daily/intraday charts for stocks, forex, or futures. Avoid illiquid symbols where volume may be unreliable.
3. **Customization**: All inputs are configurable via the indicator's settings panel. Defaults are optimized for general use but can be tuned based on asset volatility.
### Input Parameters
The inputs are grouped for ease of use:
#### MACD Settings
- **Fast EMA (CVD)** (default: 12): Length of the fast EMA applied to CVD. Shorter values make it more responsive to recent volume changes.
- **Slow EMA (CVD)** (default: 26): Length of the slow EMA on CVD. Longer values smooth out noise for trend identification.
- **Signal EMA** (default: 9): Smoothing period for the signal line (EMA of the MACD line).
#### Divergence Logic (MACD Line)
- **Pivot Lookback (MACD Line)** (default: 5): Bars to look left/right for detecting pivots on the MACD line. Higher values detect larger swings but may miss smaller divergences.
- **Max Lookback Range (MACD Line)** (default: 50): Maximum bars between two pivots to consider a divergence valid. Prevents detecting outdated signals.
- **Enable Momentum Decay Filter (Histogram)** (default: false): When enabled, requires the histogram to show decaying momentum (absolute value decreasing) for MACD-line divergences to trigger.
#### Histogram Divergence
- **Pivot Lookback (Histogram)** (default: 5): Similar to above, but for histogram pivots.
- **Max Lookback Range (Histogram)** (default: 50): Max bars for histogram divergence detection.
- **Show Histogram Divergences in Indicator Pane** (default: true): Displays dashed lines and "H" labels for histogram divergences in the sub-window.
- **Show Histogram Divergences on Main Chart** (default: true): Overlays histogram divergences on the price chart with semi-transparent lines and labels.
- **Require Histogram to Stay on Same Side of Zero** (default: true): Filters divergences to only those where the histogram doesn't cross zero between pivots, ensuring consistent momentum direction.
#### Visuals (Dual View)
- **Show MACD-Line Divergences (Indicator Pane)** (default: true): Draws solid lines and "L" labels for MACD-line divergences in the sub-window.
- **Show MACD-Line Divergences (Main Chart)** (default: true): Overlays MACD-line divergences on the price chart.
- **Show Raw CVD Line** (default: false): Plots the underlying CVD as a faint gray line for reference.
### How to Interpret the Indicator
1. **Core Plots**:
- **MACD Line** (blue): Difference between fast and slow CVD EMAs. Above zero indicates building buy volume momentum; below zero shows sell dominance.
- **Signal Line** (orange): EMA of the MACD line. Crossovers can signal potential entries/exits (e.g., MACD above signal = bullish).
- **Histogram** (columns): MACD minus signal. Green shades for positive/expanding bars (bullish momentum); red for negative/contracting (bearish). Fading colors indicate weakening momentum.
- **Zero Line** (gray horizontal): Reference for bullish (above) vs. bearish (below) territory.
- **Raw CVD** (optional gray line): The cumulative buy-sell delta. Rising = net buying; falling = net selling.
2. **Divergences**:
- **Bullish (Green Lines/Labels)**: Occur when price makes lower lows, but MACD line or histogram makes higher lows. Suggests weakening downside momentum and potential reversal up. Look for "L" (MACD line) or "H" (histogram) labels.
- **Bearish (Red Lines/Labels)**: Price higher highs vs. MACD/histogram lower highs. Indicates fading upside and possible downturn.
- **Dual View**: Divergences appear in the indicator pane (sub-window) for clean analysis and overlaid on the main chart for price context. Histogram divergences use dashed lines to distinguish from MACD-line (solid).
- **Filters**: Momentum decay ensures only "hidden" or weakening divergences trigger. Zero-side filter prevents false signals from oscillating histograms.
3. **Alerts**:
- **Bullish Divergence (L or H)**: Triggers on either MACD-line or histogram bullish divergence. Message: "CVD-MACD Bullish Divergence detected on {{ticker}}".
- **Bearish Divergence (L or H)**: Similar for bearish. Use TradingView's alert setup to notify via email/SMS/webhook.
- Tip: Combine with price action (e.g., support/resistance) for confirmation.
### Usage Tips and Strategies
- **Trend Confirmation**: Use in uptrends for bullish divergences (pullback buys) or downtrends for bearish (short entries).
- **Timeframe Selection**: Higher timeframes (e.g., daily) for swing trading; lower (e.g., 15-min) for intraday. Adjust pivot lookbacks accordingly (shorter for faster charts).
- **Combination Ideas**: Pair with RSI for overbought/oversold confirmation or VWAP for intraday volume context.
- **Risk Management**: Divergences are probabilistic—not guarantees. Always use stop-losses based on recent swings.
- **Performance Notes**: Backtest on historical data via TradingView's Strategy Tester. CVD relies on accurate volume; test on exchanges like NYSE/NASDAQ.
### Known Limitations and Troubleshooting
- **Volume Dependency**: CVD estimation assumes linear buy/sell distribution based on bar position—may be less accurate on thin markets or during gaps.
- **Repainting**: Pivots and divergences can repaint as new data arrives (common in pivot-based indicators). Use on closed bars for reliability.
- **Resource Usage**: High max_bars_back (5000) ensures deep history; reduce if chart loads slowly.
- **No Signals on Low-Volume Bars**: If CVD flatlines, check symbol volume—some crypto/forex pairs have inconsistent data.
- **Community Feedback**: If you encounter bugs (e.g., false divergences on specific symbols/timeframes), missing alerts, or calculation errors, please comment below with details like symbol, timeframe, and screenshots. Suggestions for enhancements (e.g., more filters or visuals) are welcome!
If you have questions or find issues, drop a comment—let's improve this together!
MA 9 & MA 20 Crossover + EMA200 + CONFIRMED + RSI OB/OS (Alerts)Tesing this strategy. This will not work for all coins. this is short specific coins
Manual Backtest Dashboard (100 Trades)Manual Backtest Dashboard (100 Trades) is a lightweight TradingView indicator designed to help traders manually record and evaluate their trading performance directly on the chart. This tool is built specifically for discretionary traders such as SMC, price action, scalping, and intraday traders who want to analyze their win rate and overall performance without relying on the Strategy Tester.
The indicator works by allowing users to input their trade results manually through the settings panel. Each trade is recorded using simple values: 1 for a winning trade, -1 for a losing trade, and 0 for an empty or uncounted trade. The dashboard automatically calculates the total number of trades entered, the number of wins and losses, and the win rate percentage in real time. Users do not need to fill all 100 trade slots, as only trades with non-zero values are included in the calculations.
This indicator does not place trades or generate buy and sell signals. Instead, it focuses purely on performance evaluation, making it ideal for subjective backtesting, forward testing, and manual trading journals. The dashboard is clean, lightweight, and does not clutter the price chart, ensuring a smooth and distraction-free trading experience. The script is stable, efficient, and does not repaint, making it a reliable tool for traders who want to track and improve their consistency over time.
MTT Cyclical vs Defensive Z-ScoreThe MTT Cyclical vs Defensive Z-Score is a sophisticated sentiment and rotation indicator designed to measure the relative strength of "risk-on" sectors against "risk-off" havens. It calculates a ratio between two distinct baskets: Cyclicals (Consumer Discretionary, Industrials, Materials) and Defensives/Commodities (Consumer Staples, Health Care, Utilities, and the DBC Commodity Index).
By applying a Z-score calculation to this ratio, the indicator identifies how many standard deviations the current market leadership is away from its mean. This transforms a simple ratio into a powerful tool for identifying market extremes and potential pivot points.
How the Indicator Works
The script follows a logical three-step process to quantify market sentiment:
Basket Comparison: It pits growth-sensitive sectors (which thrive during economic expansion) against defensive sectors and commodities (which act as anchors or inflation hedges).
Mean Reversion: It uses a Simple Moving Average (SMA) and Standard Deviation over a 20-period lookback to determine the "normal" range for this relationship.
Standardization: The resulting Z-score oscillates around a zero line. Green columns represent periods where cyclicals are outperforming their recent average, while red columns indicate defensive leadership.
How to Use It for Trading
The Z-score serves as a barometer for overextended market moves:
Identifying Extreme Optimism: When the Z-score crosses above +2.0, cyclicals are significantly overextended. This suggests the "risk-on" move may be exhausted, signaling a potential pullback or a rotation back into defensive stocks.
Identifying Extreme Fear: When the Z-score drops below -2.0, defensives and commodities are heavily favored. This often coincides with market bottoms or "washouts," suggesting that a bounce in cyclical sectors (and the broader market) may be imminent.
Trend Confirmation: Crossing the 0.0 (Mean) line acts as a momentum shifter. Moving from negative to positive suggests a fresh bullish rotation is gaining traction.






















