AG Pro Correlation Breakdown Map [AGPro Series]AG Pro Correlation Breakdown Map
Overview / What it does
AG Pro Correlation Breakdown Map is an overlay indicator designed to monitor whether a chart symbol is maintaining, weakening, breaking, or repairing its relationship with a benchmark symbol.
The default benchmark in this version is Bitcoin via BINANCE:BTCUSDT, which makes the tool especially useful for crypto traders who want to understand whether an altcoin is still moving in line with BTC or beginning to decouple from it.
This script does not attempt to answer whether correlation is simply high or low in isolation. Its purpose is more specific: it first checks whether a meaningful benchmark relationship existed, then evaluates whether that relationship is starting to deteriorate, whether the deterioration is becoming a confirmed breakdown, and whether the relationship is later stabilizing again.
The result is a regime-style map that helps users read benchmark dependency through distinct states such as coupled, strained, breaking, broken, repairing, and recoupled. This makes the script useful for contextual analysis, benchmark-relative behavior studies, and chart review workflows where users want more than a single rolling-correlation number.
Unique Edge
The main difference of this script is that it is not a generic correlation line, not a spread-trading engine, and not a simple benchmark overlay.
Its focus is the structure of relationship failure.
Instead of only plotting short-term correlation, the script combines four layers:
1. prior relationship validation,
2. short-vs-long correlation deterioration,
3. independent price behavior,
4. persistence and repair logic.
That combination is what separates a temporary wobble from a more meaningful benchmark breakdown event.
This also makes the script distinct from tools that measure correlation pressure or synchronized stress. Correlation Breakdown Map is built around the question: “A relationship existed before, but is it now failing, and if so, how cleanly?”
Methodology
The script starts by selecting a benchmark series and transforming price data into returns. Users can choose between log returns and percent returns.
A short correlation window and a long correlation window are then calculated between the chart symbol and the benchmark. The long window is used to judge whether a stable benchmark relationship has existed, while the short window is used to detect more recent deterioration.
The model then evaluates the gap between long and short correlation, along with short-correlation slope behavior. A benchmark relationship is considered more vulnerable when the short window weakens materially relative to the long window and the short-correlation slope also softens.
To avoid treating every statistical wobble as a true event, the script also checks for independent price behavior. This layer measures whether the chart symbol is beginning to move in a way that is meaningfully different from the benchmark over a configurable lookback period.
Finally, persistence and repair conditions are applied. This allows the script to separate brief instability from a more durable breakdown state, and later identify whether the relationship is beginning to normalize again.
Signals & Alerts / States
This script is primarily a state-mapping tool rather than a directional buy/sell engine.
The core states are:
Coupled
The chart symbol remains meaningfully aligned with the benchmark relationship structure.
Strained
The prior relationship still exists, but weakness is starting to appear.
Breaking
The relationship is under active deterioration and may be transitioning into a more meaningful failure.
Broken
The chart symbol is behaving as if benchmark linkage has materially weakened.
Repairing
The breakdown is no longer cleanly expanding, and the relationship may be stabilizing.
Recoupled
The benchmark relationship has improved enough to suggest that the prior structure is functioning again.
The Breakdown Score is used as a compact summary value. It is not intended to be interpreted as a trade signal on its own. It is a regime-strength readout that helps users compare the current condition of the relationship with the underlying state labels.
Key Inputs
Benchmark Symbol
Sets the comparison symbol. The default is BINANCE:BTCUSDT.
Benchmark Timeframe
Allows users to keep the benchmark on chart timeframe or compare against another timeframe.
Source
Selects Close, HLC3, or OHLC4 for the benchmark study.
Short Correlation Length / Long Correlation Length
Define the fast and slow windows used to evaluate current deterioration versus prior relationship structure.
Stable Relationship Threshold
Controls how strong the historical relationship must be before the script treats later weakness as a true breakdown candidate.
Breakdown Threshold / Repair Threshold
Control how strict the transition logic is for deterioration and recovery.
Min Long/Short Correlation Gap
Requires a meaningful difference between longer-term and shorter-term correlation before escalation.
Independent Move Threshold
Defines how much benchmark-relative price independence is required before the script treats the event as more than a statistical fluctuation.
Breakdown Confirmation Bars / Repair Confirmation Bars
Control persistence and confirmation sensitivity.
Visual Settings
Users can customize theme, visual intensity, panel font size, panel position, event visibility, trail visibility, and chart context density.
Limitations & Transparency
Correlation is a descriptive relationship metric, not a causal model.
A relationship breakdown does not automatically imply immediate continuation, reversal, trend acceleration, or trade opportunity. It only means the chart symbol is no longer behaving as consistently relative to the selected benchmark under the current settings.
Different assets, timeframes, and volatility regimes can produce different correlation behavior. A benchmark relationship that looks stable on one timeframe may be much less stable on another.
Short lookbacks can react faster but may create more noise. Longer lookbacks can be more stable but slower to react.
This script should be interpreted in the context of market structure, volatility, liquidity, and the chosen benchmark. It is a framework for reading relationship quality, not a guarantee engine.
Risk Disclosure
This indicator is for analytical and educational use.
It does not provide financial advice, does not predict future price direction, and should not be used in isolation for trading decisions. Users should perform their own analysis, validate settings on the markets they follow, and apply appropriate risk management. Indicator

Swing-Level Z-Score Oscillator▶️Overview
The Swing-Level Z-Score Oscillator is an innovative indicator that bridges the gap between classic market structure and statistical probability. Instead of relying on traditional moving averages as a baseline, this oscillator evaluates price extremes relative to recent structural pivot levels (Swing Highs and Swing Lows).
By transforming these structural deviations into a standardized Z-Score, it provides a highly intuitive, context-aware perspective on Overbought (OB) and Oversold (OS) conditions.
▶️How It Works (The Logic)
Traditional oscillators often lag or provide false signals during strong trends. This script tackles that issue through a unique three-step process:
Dynamic Baseline : The algorithm constantly scans for recent Pivot Highs and Pivot Lows. It takes the average of the last N pivots to establish a dynamic "horizontal zone" of recent historical interest. This acts as our expected mean.
Error & Volatility: It measures the distance (error) between the current Close price and this expected mean. To understand the significance of this distance, it calculates the rolling standard deviation of these errors.
Z-Score Normalization: Finally, it divides the current error by the standard deviation. The result is a clean Z-Score that tells you exactly how many standard deviations the current price has stretched away from recent structural levels.
▶️Key Features
Actionable Market Context: Because the baseline is built on actual price pivots rather than arbitrary averages, the oscillator respects current market structure (support/resistance).
Intelligent Gradient UI: The indicator features a dynamic color-coding system.
The histogram and signal line smoothly fade based on the intensity of the momentum.
Vivid Extreme Alerts: When the Z-Score stretches beyond the critical ±2.0 Sigma threshold, the histogram flashes vivid Cyan (Overbought) or Neon Pink (Oversold), immediately catching your attention.
Plug-and-Play Presets: Don't want to mess with settings? Use the "Operating Mode" dropdown to quickly switch between Short-term, Standard, and Long-term presets tailored to different trading styles. Fully customizable options are also available.
▶️How to Trade with It
Mean Reversion (Fade the Extremes): When the histogram hits the vivid ±2.0 zones, the price is statistically overextended relative to recent swing levels. Look for exhaustion price action (like pin bars) combined with a hook back toward the center line to trade reversions.
Pullbacks in a Trend: During a clear trend, look for the oscillator to reset back to the Center Line (0) or the ±1 Sigma lines. These often represent optimal, low-risk entry points (buy the dip/sell the rally) before the trend resumes.
Momentum Breakouts: A sudden, aggressive spike that blasts through the ±2 Sigma line can indicate a genuine structural breakout with heavy momentum, rather than a mere overextension.
▶️Settings & Customization
If you select "Custom" in the Operating Mode, you can fine-tune:
Left/Right Bars: Adjusts the sensitivity of the pivot detection. Lower numbers catch micro-swings, while higher numbers catch major structural points.
StdDev Length: The lookback period for calculating the variance of the errors.
Past Pivots Count (N): Determines how many historical pivots are used to calculate the "Expected Value" baseline.
Disclaimer: This script is for educational and analytical purposes only. Always combine oscillator readings with broader price action analysis and proper risk management. Indicator

CL OVX Implied Daily RangeThis indicator combines the CBOE OVX Implied Daily Range (Black-Scholes style) with dynamic Rays. It plots the expected daily trading range for Crude Oil (CL) based on current OVX volatility.
On top of that, it automatically draws two special horizontal rays:
Ray 1: Fires from the lowest point the upper band has reached in the selected lookback period. Ray 2: Fires from the highest point the lower band has reached in the same period.
Each ray continues extending right until the opposite ray triggers (stops when other fires, and vice versa). This creates clean, non-cluttered reference levels.
The result is a volatility-based range with intelligent horizontal support/resistance rays that adapt to the actual behavior of the implied range.
Main Use Cases
Dynamic Support & Resistance
The top rays often acts as a strong overhead resistance level once the upper band has been “pushed down.” The bottom rays frequently acts as dynamic support when the lower band has been “pushed up.”
Mean Reversion Trading
Many traders use these rays as targets or mean-reversion zones. For example, if price is near the upper band and a ray is active, it highlights a high-probability area where price may stall or reverse.
Breakout Confirmation
When price breaks and holds above the upper ray (or below the lower ray), it can signal stronger momentum because it has cleared the recent “tightest” implied range boundary.
Volatility Context
Helps you visually see when the implied range is contracting (rays appear closer together) or when it’s expanding, giving you better context for position sizing and stop placement.
Intraday / Swing Trading on CL
Very useful on 15min, 30min, 1H, and 4H charts for Crude Oil to identify high-probability bounce or rejection zones based on options-implied volatility.
Indicator

Indicator

Indicator

Indicator

Indicator

Indicator

FC Footprint , Delta Imbalance and Zero Print TrackerOverview
FC Footprint is a real-time bid/ask footprint chart rendered directly on the price pane. Each candle is broken into price rows showing traded sell volume (bid) and buy volume (ask) side by side, colored by dominance, Value Area membership, and imbalance. Interior zero-print rows — price levels where one side of the auction was completely absent — are flagged inline and tracked as persistent untested zones that extend into future price action until retested.
The indicator is designed for futures traders (NQ, ES, GC, CL) who need order flow context without leaving the chart. It runs entirely on the chart timeframe with no secondary security calls.
REQUIREMENTS
PulseWire Premium plan or higher is required to use this indicator.
The request.footprint() function is only available on Premium, Premium+, and Ultimate subscriptions. The script will not load on lower-tier plans.
Real-time footprint data requires a live data feed. Delayed feeds will produce delayed row updates on the current bar.
─────────────────────────────────────────────────────────
How It Works
Footprint Rows
Each bar is decomposed into rows of ticksPerRow ticks. For every row the indicator displays bid - ask volume, where bid = sell-side aggression and ask = buy-side aggression. Row text is color-coded:
Green — ask volume dominant (buyers in control)
Red — bid volume dominant (sellers in control)
Teal — buy imbalance (ask ≥ bid × threshold)
Pink — sell imbalance (bid ≥ ask × threshold)
Yellow — zero print (one side is completely absent)
Light blue — inside the Value Area
White — Point of Control (highest volume row)
Point of Control (POC)
The highest-volume row of each bar is marked with a horizontal line spanning the bar width, making the dominant auction price immediately visible.
Value Area
Rows falling within the configurable Value Area percentage (default 70%) are highlighted, consistent with the standard Market Profile convention.
Imbalances
Rows where one side outpaces the other by the configured threshold (default 300%, meaning 3:1 ratio) are flagged. Stacked imbalances in the same direction are a common signal of directional conviction in order flow analysis.
Zero Print Detection
A zero print occurs when either bid or ask volume on a row is exactly zero, indicating the auction passed through that price with no two-sided participation. Interior zero prints (those within the bar body, not in the wick) are the most significant and are registered as untested zones. Each zone extends as a shaded box to the right until price revisits and fills the level, at which point the box is hidden.
Delta / Total Summary
A label below each bar shows:
"Δ" — net delta (buy volume minus sell volume for the bar)
"Σ" — total traded volume for the bar
Delta color shifts green for positive, red for negative, and neutral gray when balanced.
Inputs
Core
Ticks Per Row — tick granularity of each row. Lower = more rows, finer resolution. Typical starting points: NQ/ES = 4–8, Gold = 2–4.
Value Area % — proportion of bar volume that defines the Value Area. Standard is 70%.
Imbalance Threshold % — minimum one-sided ratio to flag a row as an imbalance. Default 300 (3:1).
Bars To Show — number of recent bars rendered. Each bar consumes labels proportional to its row count; keep within PulseWire's 500-object limit.
Max Rows Per Bar — hard ceiling on rows processed per bar, preventing object overflow on exceptionally wide candles.
Zero Print Lookback — how many bars back untested zero-print boxes are drawn. Values above 300 may cause a timeout on tick-dense symbols.
Zero Print
Flag Zero On Bid / Ask — independently toggle which side triggers a zero print.
Box Extension — how many bars to the right untested zones project.
Hide Box After Retest — removes the box once price re-enters the zone on a confirmed bar.
Hide Zero in Wick — suppresses wick-area zeros, which are common and typically less actionable than body zeros.
Usage Notes
Works on any timeframe. Lower timeframes (1m, 3m, 5m) produce the most granular order flow data.
Tune Ticks Per Row to your instrument's tick size. Too few ticks creates excessive rows; too many compresses meaningful auction structure.
Zero print boxes are best used as magnet zones — unfilled auctions tend to attract price when revisited in the same session or overnight.
Imbalance stacks (three or more consecutive imbalance rows in the same direction) are a particularly strong signal.
Delta alone does not predict direction, but divergence between delta and price close (e.g., negative delta on a green close) can indicate absorption or hidden demand/supply.
Technical Notes
Built on Pine Script v6 using the native request.footprint() and volume_row type system.
All drawing objects are managed through pooled arrays and rebuilt on the last bar only, keeping runtime overhead minimal.
History is stored as a flat array with slice indexing rather than nested arrays for efficient memory use across the configured lookback.
Indicator

Indicator

Trade Strategy Calculator [WillyAlgoTrader]📊 Trade Strategy Calculator is the first comprehensive mathematical strategy calculator built entirely inside PulseWire — a 4-panel dashboard that computes position sizing, risk analysis, deposit growth projection, and Kelly Criterion optimization in real time, directly on your chart. No spreadsheets, no external tools, no switching tabs. Every number you need before entering a trade — position size, stop loss level, take-profit targets, commission impact, expected value, probability of ruin, compound growth forecast, and optimal bet sizing — calculated from your strategy parameters and displayed in a single organized view.
This tool is useful for every trader regardless of market, instrument, or timeframe — stocks, forex, crypto, futures, indices, commodities. Whether you trade scalping on 1-minute charts or swing on daily, whether you use 1x spot or 125x futures leverage — the mathematics of position sizing, risk management, and bankroll growth are universal. This calculator puts those mathematics at your fingertips.
🧩 WHY ALL FOUR PANELS WORK TOGETHER
Most traders calculate position size in isolation — they know how much to risk but don't connect it to their long-term growth trajectory. They know their win rate but don't know if it's mathematically profitable after commissions. They have a "feel" for their risk level but haven't computed what happens after 7 consecutive losses.
This calculator connects four mathematical dimensions into one coherent picture:
🎯 TRADE panel answers: "How large should this specific trade be, and what are the exact entry/SL/TP prices?"
⚠️ RISK panel answers: "What happens when things go wrong — how many losses until I hit my daily limit, my max drawdown, and what's my expected value per trade?"
📈 GROWTH panel answers: "If I trade consistently with these parameters, where will my deposit be in 30/90/365 days — and how long to reach my target?"
📐 KELLY panel answers: "Am I betting the mathematically optimal amount — or am I over-betting (risking ruin) or under-betting (leaving growth on the table)?"
A trader who only uses the TRADE panel knows their position size but not whether their strategy has positive expected value. A trader who only uses KELLY knows the optimal bet size but not the specific position for their current trade. A trader who only uses GROWTH knows the projection but not whether the underlying math is sound. All four together give you the complete picture: "Is my strategy profitable? Am I sizing correctly? What's the worst case? And where does this lead?"
🔍 WHAT MAKES IT ORIGINAL
There is no other indicator on PulseWire that combines all four of these mathematical models — position sizing, risk stress testing, compound growth simulation, and Kelly Criterion — into a single, real-time, interactive dashboard. Each panel alone would be a useful tool. Together, they create something that doesn't exist elsewhere on the platform.
🎯 PANEL 1 — TRADE (Position Sizing + Targets)
This panel calculates the exact position size for your trade based on your deposit, risk percentage, stop loss distance, leverage, and commissions.
Core formula:
positionSize = riskAmount / (slDistance% + commissionBothSides)
Where:
— riskAmount = deposit × riskPerTrade%
— slDistance% = slPercent × (1 + slippage%) — slippage is added to the stop distance for realistic sizing
— commissionBothSides = commission% × 2 (open + close)
This formula ensures that if your stop loss is hit, you lose exactly riskAmount — not more, not less — after accounting for both slippage and round-trip commission.
What you see:
— Direction (Long / Short)
— Entry Price (manual or auto from chart)
— Stop Loss price (calculated from entry ± SL%)
— 💰 Position Size in USD — the headline number
— Margin Required (if leverage > 1)
— Quantity (units/coins/shares)
— 🔴 Risk (loss) in USD and % of deposit
— 🟢 Profit at TP — in USD, % of deposit, and net R:R after commission
— TP Price level
— Commission cost in USD
— Liquidation price (for leveraged positions)
— ⚠️ Insufficient margin warning (if position exceeds deposit)
Multi Take-Profit mode:
When enabled, the position is split across 2 or 3 TP levels with configurable volume allocation:
— TP1 at R:R 1.0 with 50% of position → locks partial profit early
— TP2 at R:R 2.0 with 30% → captures the main move
— TP3 at R:R 3.0 with 20% (if 3 TPs) → runner for extended moves
Each TP shows: profit in USD, target price. The panel also computes:
— Total blended profit across all TPs
— Net R:R (blended, after commissions)
— Breakeven price after TP1 — the price where your remaining position becomes zero-loss after banking TP1 profit. This is critical: after TP1, you move your stop to this price — the trade can no longer lose money.
Example:
Deposit: $10,000. Risk: 1% ($100). SL: 2%. Commission: 0.04%.
Position = $100 / (0.02 + 0.0008) = $4,808.
If BTC at $100,000 → SL at $98,000, TP1 at $102,000.
If stopped out → you lose exactly $100 (1% of deposit).
If TP1 hit → you gain ~$96 (after commission).
⚠️ PANEL 2 — RISK (Stress Testing + Expected Value)
This panel answers: "What happens when I have a losing streak, and is my strategy mathematically profitable?"
Daily risk limit:
maxLosingDaily = floor(dailyRiskLimit% / riskPerTrade%)
Example: 3% daily limit, 1% per trade → you stop after 3 losses in a day.
Max drawdown limit:
maxLosingTotal = floor(maxDrawdown% / riskPerTrade%)
Example: 20% max DD, 1% per trade → 20 consecutive losses to hit max DD.
Stress test — losing streaks:
The panel computes what happens after 5, 7, and 10 consecutive losses:
— depositAfterN = deposit × (1 − riskPerTrade%)^N
— drawdownAfterN = (1 − (1 − riskPerTrade%)^N) × 100%
— probabilityOfN = (1 − winrate%)^N × 100%
Example: $10,000 deposit, 1% risk, 55% winrate:
— 5 losses: −4.9% DD ($9,510), probability 1.85%
— 7 losses: −6.8% DD ($9,321), probability 0.37%
— 10 losses: −9.6% DD ($9,044), probability 0.03%
This tells you: a 5-loss streak WILL happen (1.85% probability over hundreds of trades). A 10-loss streak is extremely rare (0.03%). Your risk% must be sized so that even the realistic worst case doesn't blow your account.
Expected Value (EV):
EV per trade = winrate × riskAmount × avgR:R − (1 − winrate) × riskAmount − commission
This is the single most important number in trading. If EV > 0, your strategy makes money over time. If EV < 0, no amount of position sizing saves you.
The panel shows:
— 📈 EV per trade in USD (highlighted — this is the headline metric)
— EV per 100 trades
— Break-even winrate WITH commission — the minimum winrate needed to be profitable at your R:R, accounting for commission drag
— Your actual WR and R:R for comparison
Break-even winrate formula (with commission):
beWinrate = (1 + commissionCost / riskAmount) / (avgR:R + 1)
This is more accurate than the standard 1/(R:R+1) because it accounts for commission reducing your net edge.
📈 PANEL 3 — GROWTH (Deposit Projection + Scenarios)
This is the unique deposit growth simulator — it projects where your deposit will be after N days of consistent trading, using either compound (reinvest profits) or simple (fixed risk from initial deposit) growth.
Compound growth formula:
EV per trade as % = winrate × (risk% × R:R) − (1 − winrate) × risk%
totalTrades = tradesPerDay × projectionDays
finalDeposit = deposit × (1 + evPerTrade%)^totalTrades
Simple growth formula:
finalDeposit = deposit + deposit × evPerTrade% × totalTrades
The difference is massive. Compound growth reinvests profits — each winning trade increases the base for the next trade. Simple growth always risks a fixed amount from the initial deposit.
Example — compound vs simple:
$1,000 deposit, 55% WR, 1:2 R:R, 1% risk, 3 trades/day, 30 days:
— Simple: $1,000 + $1,000 × 0.65% × 90 = $1,585
— Compound: $1,000 × (1.0065)^90 = $1,795
Over 90 days: $1,585 vs $1,795. Over 365 days the gap becomes enormous. This is why compound growth (reinvesting profits) is the key to deposit acceleration.
Three scenarios:
— 🟢 Optimistic: your winrate + 10% (what happens if you're having a great month)
— 🟡 Realistic: your actual parameters
— 🔴 Pessimistic: your winrate − 10% (what happens during a drawdown period)
This gives you a range, not a single number. If even the pessimistic scenario is positive, your strategy is robust.
Goal milestones:
— Days to 2× deposit (double your money)
— Days to 3× deposit
— Days to custom target ($5,000, $10,000, etc.)
Formula: daysToTarget = log(target / deposit) / (log(1 + evPerTrade%) × tradesPerDay)
Risk metrics:
— Max estimated drawdown: based on expected worst losing streak × risk%
— Ruin probability: the probability of losing your entire bankroll at your current risk level
Ruin probability formula:
edge = winrate × R:R − (1 − winrate)
bankrollUnits = floor(100 / risk%)
ruinProb = ((1 − winrate) / (winrate × R:R))^bankrollUnits
If edge ≤ 0, ruin probability is effectively 100%. If edge > 0, ruin probability decreases exponentially with more bankroll units (lower risk%).
Presets for quick scenarios:
— Beginner: 45% WR, 1:2 R:R, 1% risk — conservative starting point
— Moderate: 55% WR, 1:2 R:R, 2% risk — typical intermediate trader
— Aggressive: 50% WR, 1:3 R:R, 3% risk — higher risk, needs discipline
— Custom: uses your exact My Strategy values
📐 PANEL 4 — KELLY CRITERION (Optimal Bet Sizing)
The Kelly Criterion is the mathematically optimal percentage of your bankroll to risk on each bet, given your edge. It maximizes the long-term growth rate of your account.
Kelly formula:
edge = winrate × avgR:R − (1 − winrate)
kellyPercent = edge / avgR:R
If edge ≤ 0 → Kelly = 0% (no edge, don't trade). If edge > 0 → Kelly tells you the maximum you should risk.
What the panel shows:
— Your winrate and avg R:R
— Break-even winrate (with commission)
— 📐 Edge per $1 risked — your mathematical advantage. If +$0.15, every $1 risked returns $1.15 on average.
— Full Kelly % — the theoretical maximum. Most traders should NOT use this — it's too aggressive.
— Half Kelly ✦ — the recommended practical value. Reduces variance by ~75% while giving up only ~25% of growth.
— Quarter Kelly — ultra-conservative, minimal variance.
— Your current risk % — so you can compare
— Status: 🟢 Optimal (between half and full Kelly), 🟡 Conservative (below half), 🔴 Over-bet (above full Kelly), 🚨 >2× Kelly (danger zone)
Growth rate comparison:
— Growth rate at Kelly %: the compound growth rate per trade at the optimal bet size
— Growth rate at your %: your actual compound growth rate per trade
Formula: growthRate = winrate × log(1 + risk% × R:R) + (1 − winrate) × log(1 − risk%)
If your rate is close to the Kelly rate, you're near-optimal. If it's much lower, you're leaving growth on the table. If it's negative (possible when over-betting!), you're actually losing money despite having a positive edge — the over-betting destroys the compounding.
Why this matters:
A trader with a 55% WR and 1:2 R:R has an edge. Kelly says risk ~4.6%. But if that trader risks 10% per trade (2× Kelly), their actual growth rate can become negative — they go broke despite having a winning strategy. This is the most counterintuitive result in trading mathematics: over-betting a winning system turns it into a losing system . The Kelly panel prevents this.
📖 HOW TO USE — STEP BY STEP
Step 1 — Enter your strategy parameters (My Strategy section):
— Deposit: your actual account balance in USD
— Risk per Trade: how much you risk per trade (start with 1% if unsure)
— Winrate: your historical win rate (be honest — check your journal)
— Average R:R: your average reward-to-risk on winning trades
— Trades per Day: how many trades you typically take
— Leverage: 1 for spot, or your futures leverage
— Commission: your exchange fee per side (Binance Futures taker: 0.04%)
Step 2 — Set up your current trade (Trade Setup section):
— Direction: Long or Short
— Stop Loss %: how far your SL is from entry
— Risk:Reward: your target R:R for this trade
— Entry Price: manual or auto from chart
Step 3 — Read the TRADE panel:
— The 💰 Position Size number is your order size in USD
— If using leverage, check Margin Required doesn't exceed your deposit
— Note the SL and TP prices — set these in your exchange
Step 4 — Check the RISK panel:
— Is your EV per trade positive? If not, your strategy loses money long-term
— Is your winrate above the break-even? If not, improve your R:R
— Check the stress test: can your deposit survive 7 losses in a row?
— If the risk badge shows 🚨 DANGER, reduce your risk% or leverage
Step 5 — Review the GROWTH panel:
— The projected deposit shows where you'll be in 30 days
— Check the pessimistic scenario — is it still above your starting deposit?
— Note the days to 2× — this is your compound growth timeline
— If ruin probability > 5%, your risk is too high
Step 6 — Optimize with KELLY panel:
— Compare your risk% to Half Kelly — this is the recommended level
— If Status shows 🔴 Over-bet, reduce your risk%
— If Status shows 🟡 Conservative, you could increase (but don't have to)
— Check Growth Rate at Your % — is it positive? Is it close to Kelly's rate?
🎯 PRACTICAL EXAMPLES
Example 1 — Conservative Spot Trader:
Deposit $5,000, Risk 1%, WR 55%, R:R 1:2, 2 trades/day, No leverage, Commission 0.1%
— Position: ~$2,500 per trade. Risk: $50.
— EV: +$5.60 per trade. Positive — strategy is profitable.
— 30-day projection (compound): $5,000 → $5,705 (+14.1%)
— Days to double: ~98 days
— Kelly: 4.6%. Your 1% = conservative. Status: 🟡
Example 2 — Crypto Futures Scalper:
Deposit $1,000, Risk 2%, WR 50%, R:R 1:3, 5 trades/day, Leverage 10x, Commission 0.04%
— Position: ~$10,000 per trade. Margin: $1,000. Risk: $20.
— EV: +$10.40 per trade. Strong positive edge.
— 30-day projection (compound): $1,000 → $4,680 (+368%)
— Days to double: ~14 days
— Kelly: 8.3%. Your 2% = well below Kelly. Room to grow.
— ⚠️ But 7-loss streak probability: 0.78%. DD: −13.2%. Manageable.
Example 3 — Why Over-Betting Kills:
Same as Example 2, but Risk 15% (almost 2× Kelly):
— EV per trade still positive (+$78)
— BUT growth rate per trade: NEGATIVE (−0.3%)
— 30-day projection: $1,000 → $620 (−38%)
— Kelly Status: 🚨 >2× Kelly
— Despite winning 50% with 1:3 R:R, you LOSE money because over-betting destroys compounding.
⚙️ KEY SETTINGS REFERENCE
⚙️ My Strategy:
— Deposit : account balance in USD
— Risk per Trade (default 1%): % of deposit risked per trade
— Winrate (default 55%): historical win rate
— Average R:R (default 2.0): average reward-to-risk on wins
— Trades per Day (default 3): daily trade count
— Leverage (default 1): 1 = spot, >1 = futures
— Commission (default 0.04%): exchange fee per side
🎯 Trade Setup:
— Direction : Long / Short
— Stop Loss % (default 1%): SL distance from entry
— Risk:Reward (default 2.0): target R:R
— Slippage (default 0.05%): expected execution slippage
— Entry Price : Manual or Auto (chart price)
🎯 Multi Take-Profit:
— Enable Multi TP (default Off): split into 2–3 targets
— R:R for TP1/TP2/TP3 (default 1.0/2.0/3.0)
— Volume allocation (default 50%/30%/20%)
📈 Growth Projection:
— Preset : Beginner / Moderate / Aggressive / Custom
— Projection Period (default 30 days)
— Compound (default On): reinvest profits
— Target Deposit (default 0 = off): goal amount
— Max Daily Risk (default 3%): daily loss limit
— Max Drawdown (default 20%): total DD limit
🎨 Visual:
— Font Size: Tiny / Small / Normal / Large
— Auto / Dark / Light theme
⚠️ IMPORTANT NOTES
— 📊 This is a calculator, not a signal generator. It does not produce buy/sell signals. It computes the mathematical framework for your trading decisions — position sizing, risk limits, growth projections, and optimal bet sizing. The math is universal and applies to any strategy.
— 📐 All calculations are deterministic — they depend only on your input parameters, not on price data. The dashboard updates in real-time when you change any input.
— ⚖️ The growth projection assumes consistent strategy parameters over the projection period. Real trading involves varying win rates, R:R ratios, and market conditions. The three scenarios (optimistic/realistic/pessimistic) partially address this by showing a range.
— 📏 The Kelly Criterion assumes known, fixed probabilities . In practice, your winrate and R:R fluctuate. This is why Half Kelly (not Full Kelly) is recommended — it accounts for parameter uncertainty.
— 💰 Commission is calculated as round-trip (both sides) and deducted from both profit calculations and expected value. This provides realistic net returns.
— 📊 The break-even winrate calculation includes commission drag — it's higher than the simplified 1/(R:R+1) formula because commission erodes your edge.
— 🔄 The compound growth formula uses logarithmic overflow protection — if the projected growth exceeds exp(23) ≈ 10 billion ×, it displays "∞" instead of crashing.
— 🛠️ Works on any chart, any instrument, any timeframe . The calculator is price-independent — it uses your manual inputs. "Auto" entry price mode uses the current chart close for convenience.
— 🌐 Useful for all markets : stocks (set leverage = 1, commission = 0.1%), forex (adjust for pip-based SL), crypto spot (leverage = 1), crypto futures (set your leverage), indices, commodities. Indicator

Delta AVAT - Volume Deviation IndicatorDelta AVAT measures how much current bar volume deviates from its historical average across three configurable lookback periods, giving you an immediate read on whether volume is running hot, cold, or in line with recent norms.
How it works
Rather than plotting raw volume, Delta AVAT plots the difference between current volume and the simple moving average of the previous N bars - all relative to whatever timeframe your chart is set to. Switch between 1m, 15m, 1H, Daily, or any other timeframe and the lookbacks automatically adapt to that period with no reconfiguration needed.
Three simultaneous lookbacks
Lookback 1 (default 5) - short-term baseline: is this bar unusual vs the last few bars?
Lookback 2 (default 20) - intermediate baseline: monthly context
Lookback 3 (default 180) - structural baseline: long-run volume norm
All three are fully adjustable. Common alternatives: 10 / 55 / 200, or 8 / 21 / 89.
Reading the indicator
Bars above zero - current volume exceeds the lookback average (elevated activity)
Bars below zero - current volume is below average (quiet/weak participation)
Bar color - green if price closed up, red if down, gray if flat
Gold line - Lookback 1 delta
Blue line - Lookback 2 delta
Violet line - Lookback 3 delta
Dashboard table (top right)
Displays live percentage deviation of current volume vs each lookback average, color-coded green/red. Updates on every bar.
Settings
Lookback 1 / 2 / 3 - period lengths (bars on current TF)
Color bars by close-to-close - toggle between close vs prior close or close vs open for bar coloring
Show % deviation - switches the plotted values from absolute delta to percent deviation
Based on AVAT by danilogalisteu. Delta extension by alxs1234. Indicator

DafeRCMLibRolling Confidence Matrix Library (RCM)
A Structural Evidence Accumulation Engine for Pine Script Developers
What This Library Does
The Rolling Confidence Matrix (RCM) is a developer library that provides a stateful structural analysis engine for Pine Script indicators. It maintains rolling evidence buckets that accumulate and decay observations about market structure on every bar, then synthesizes those observations into confidence scores, a directional state classification, and a set of modulation outputs that downstream indicators can consume.
The library is designed to be algorithm-agnostic. It does not generate signals, draw lines, or produce visual output. It computes structural context that other indicators use to make better decisions — whether that indicator is a Supertrend, a moving average crossover, a Bollinger Band system, or a machine learning model.
The Problem This Solves
Traditional indicators are structurally blind. A Supertrend calculates band width from ATR alone. A moving average crossover fires regardless of whether the cross happens during a structural breakout or inside exhaustion chop. A Bollinger Band squeeze looks identical mathematically whether it precedes a genuine expansion or a false breakout.
These indicators lack the ability to evaluate what kind of price action is producing their signals. The RCM addresses this by maintaining a persistent, per-bar structural memory that any indicator can query.
How It Works: The Five Evidence Buckets
The RCM tracks five categories of structural evidence, accumulated separately for bull and bear sides (10 buckets total). Each bucket decays by a configurable rate every bar, accumulates when its specific conditions are detected, and is hard-capped to prevent runaway values.
Impulse — Detects directional thrust bars. Criteria: body exceeds the 10-bar average body by 15%, close position is in the upper 30% (bull) or lower 30% (bear) of the bar's range, and the bar's range exceeds the 10-bar average range by 5%. Volume confirmation adds additional evidence when the volume ratio exceeds 1.2x the 20-bar average.
Structure — Detects swing-level events. Criteria: price closes above the 5-bar highest high (swing break), price sweeps below a swing low and reclaims it on a bullish close (reclaim), or price wicks through a swing level but closes back inside (sweep absorption). Each event type contributes a different evidence weight, reflecting its structural significance.
Exhaustion — Detects reversal pressure. Criteria: a bearish-body bar with a lower wick exceeding 45% of the total range on volume above 1.2x average contributes bull exhaustion evidence (potential buying absorption). The inverse applies for bear exhaustion. This bucket represents counter-trend pressure building within the current move.
Continuation — Detects trend persistence. Criteria: the EMA(21) of HLC3 has a positive slope, price is above the anchor, and the current close exceeds the previous close. This bucket also has asymmetric decay: when price moves to the wrong side of the anchor, continuation evidence decays at 62% per bar instead of the standard rate. Anchor crosses trigger a 50% immediate reduction.
Compression — Detects range contraction. Criteria: the current bar's range is below 80% of the 10-bar average range, and the ATR(14) to SMA(ATR,30) ratio is below 0.95. Compression evidence accumulates on the side of the anchor (bull compression above, bear compression below), representing potential energy buildup before expansion.
Bucket Caps
Each bucket has a defined maximum to prevent any single evidence type from dominating the confidence calculation:
Impulse: 25
Structure: 30
Exhaustion: 20
Continuation: 20
Compression: 15
Confidence Computation
Bull and bear confidence scores are computed as weighted sums of their respective five buckets:
bullConf = bullImpulse × wImpulse + bullStructure × wStructure +
bullExhaustion × wExhaustion + bullContinuation × wContinuation +
bullCompression × wCompression
Default weights are: Impulse 1.20, Structure 1.35, Exhaustion 1.15, Continuation 1.00, Compression 0.90. Structure carries the highest default weight because swing-level events are the most structurally significant observations.
From these scores, the library derives:
Net Confidence: bullConf − bearConf
Activity: bullConf + bearConf (total evidence in the system)
Dominance: netConf / activity (how one-sided the evidence is, range −1 to +1)
Bull/Bear Pressure: each side's share of total activity (range 0 to 1)
The Three-State Engine
The state engine uses hysteresis to prevent flickering between states. Entering a state requires strong evidence; holding a state requires only moderate evidence.
Entry Conditions (Transition → Bull/Bear):
Net confidence exceeds the entry threshold (default: 12.0)
AND dominance exceeds the dominance threshold (default: 0.18)
Hold Conditions (Bull/Bear → Transition):
A state is lost when ANY of:
Net confidence drops below the hold threshold (default: 5.0)
Opposing pressure exceeds the flip pressure threshold (default: 0.58)
Erosion (peak confidence minus current) exceeds 35% of current confidence
This hysteresis design means the engine requires conviction to enter a directional state but gives the trend room to breathe once established.
Substates
When the engine is in Transition (state = 0), it internally classifies the type of transition based on which evidence buckets are dominant:
Early (substate 1): Within 3 bars of losing a directional state. Evidence is collapsing.
Contested (substate 2): Both bull and bear confidence exceed 50% of the entry threshold. Both sides have material evidence.
Rotational (substate 3): Exhaustion buckets represent more than 35% of total non-compression evidence. The market is churning.
Compression (substate 4): Compression buckets exceed 35% of total evidence while impulse is below 15%. Energy is building.
The external state remains 0 for all substates. Consumers who need granularity can query st.substate.
Damage Detection
When the engine is in a directional state, it evaluates structural compromise on every bar by accumulating a damage score from seven independent checks:
For a Bull state, damage accumulates from:
Price below the anchor (+1.5)
Bear impulse condition detected (+1.0)
Upper wick ratio exceeds 35% (+0.75)
Anchor slope is negative (+1.0)
Bear pressure exceeds 45% (+1.0)
Close and high are both lower than previous bar (+0.75)
Price crossed below the anchor this bar (+1.25)
Maximum possible damage score per bar: 7.25. When the score exceeds the damage threshold (default: 4.0), the trend is flagged as damaged.
Damage Response
When damage is detected, the engine modifies the active side's evidence buckets:
Continuation is reduced by (0.25 × damageDecayMult) — default removes ~44%
Impulse is multiplied by damageImpulseCut — default retains 88%
Structure is multiplied by 0.92
Opposing exhaustion receives +1.5
Opposing impulse receives +1.0
This creates a natural degradation cycle: damage weakens the active trend's evidence while strengthening the opposing side's, making a transition more likely without forcing it.
Integrity Score
The library computes a continuous structural integrity measure from 0.0 (broken) to 1.0 (fully intact), derived from four components:
Erosion component (max −0.30): How far current confidence has fallen from its peak
Damage component (max −0.30): Current damage score relative to threshold
Opposing pressure (max −0.20): Counter-trend pressure magnitude
Transition duration (max −0.15): How long the engine has been in transition state
External evidence modifiers can also adjust integrity by ±0.1.
Directional Permissions
Rather than a simple pass/fail gate, the library outputs four permission values:
allowLong (bool) : Structural permission to take long positions
allowShort (bool): Structural permission to take short positions
preferLong (float, 0−1): Strength of structural preference for longs
preferShort (float, 0−1): Strength of structural preference for shorts
In Bull state: longs are allowed, shorts are blocked unless the trend is damaged (allowing counter-trend fades). preferLong equals the confidence strength. In Bear state: the inverse. In Transition: both sides are allowed, preference leans toward whichever side has more evidence.
External Evidence Sockets
The library accepts additive evidence injection from external systems through the ExternalEvidence type. External evidence is applied after internal bucket computation but before state transitions, meaning it can influence confidence but cannot directly set state.
ev = rcm.ExternalEvidence.new(bullEvidence=3.0, source="dreamer")
st := rcm.inject(st, ev)
External evidence is reset to zero after each update() call. This prevents stale external data from persisting.
Modulation Outputs
The library provides purpose-built modulation functions for different indicator types:
Band Modulation (get_band_mod): Returns a float multiplier for band/envelope width. Bands tighten during high-confidence directional states and widen when damage is detected. Used by Supertrend, Bollinger Band, and PSAR-type indicators.
Score Modulation (get_score_mod): Returns an additive modifier for directional scores. When a score's direction aligns with the RCM state, it receives a confidence-proportional boost. When it opposes, it receives a penalty. Used by signal-scoring systems.
Signal Gate (get_gate): Returns a boolean indicating whether signals should be permitted. When transition blocking is enabled, all signals are suppressed during Transition state.
Full Package (get_modulation): Returns all outputs in a single RCMModulation struct including band mod, score mod, gate, permissions, integrity, state color, and regime label.
Configuration
The library ships with three preset configurations:
default_config(): Balanced settings suitable for 15m−1H timeframes
scalp_config(): Faster decay (0.75), lower thresholds, higher impulse weight — optimized for 1m−5m
swing_config(): Slower decay (0.88), higher thresholds, higher structure weight — optimized for 4H−Daily
All 16 configuration parameters can also be set individually through the RCMConfig constructor.
Developer Integration Guide
Step 1: Import and Initialize
import DskyzInvestments/DafeRCMLib/1 as rcm
var rcm.RCMState st = rcm.RCMState.new()
var rcm.RCMConfig cfg = rcm.default_config()
Both objects must be declared with var for state persistence across bars.
Step 2: Update Every Bar
st := rcm.update(st, cfg)
Call update() exactly once per bar. It handles all evidence detection, decay, confidence computation, damage detection, state transitions, substate classification, and integrity scoring.
Step 3: Query Modulation Outputs
For band-based indicators (Supertrend, BB, PSAR):
band := band * rcm.get_band_mod(st, 0.45, 1.10)
For score-based systems (signal scoring, ML models):
fusedScore = rawScore + rcm.get_score_mod(st, rawScore, 0.25)
For signal gating:
buySignal := buySignal and rcm.get_gate(st, true)
For directional permissions:
rcm.RCMPermissions perms = rcm.get_permissions(st)
if perms.allowLong and perms.preferLong > 0.3
// High structural preference for longs
Step 4: Optional — Inject External Evidence
if myDreamerScore > 2.0
ev = rcm.ExternalEvidence.new(bullEvidence=2.0, source="dreamer")
st := rcm.inject(st, ev)
// inject() must be called BEFORE update()
Step 5: Optional — Use Dashboard Helpers
rcm.conf_bar(st.bullConf, 130, 8) // Returns "████░░░░"
rcm.state_text(st) // Returns "▲ BULL"
rcm.damage_text(st) // Returns "Intact"
rcm.integrity_text(st) // Returns "87.3%"
rcm.state_color(st, bullCol, bearCol, transCol)
Step 6: Optional — Narrative Text
= rcm.narrative_regime(st, bullCol, bearCol, transCol, dimCol)
= rcm.narrative_kinetics(st, accentCol, dimCol)
= rcm.narrative_structure(st, bullCol, bearCol, transCol, dimCol)
What This Library Does Not Do
It does not generate buy/sell signals
It does not draw on the chart
It does not use request.security or access external timeframes
It does not use request.footprint (consumers can inject footprint-derived evidence through the external socket)
It does not persist data beyond the current chart's bar history
It does not adapt its own parameters automatically
The library computes structural context. What the consuming indicator does with that context is entirely the developer's decision.
Companion Demo
The DafeRCMLibDEMO indicator demonstrates every function and output of this library
using a simple EMA crossover system as the base indicator. It includes:
Modulated ATR bands showing get_band_mod() in action
Trade signals gated by get_permissions() and get_gate()
State shift and damage markers
Substate classification labels
Evidence bucket subplots for all 10 buckets
Confidence, integrity, and modulation output subplots
Full quantitative dashboard and narrative panel
— Dskyz, Trade with insight. Trade with anticipation. Library

Trend State [DAFE]Trend State
A State-Driven Confidence Trend Engine
Where Trend is Assessed as a Matter of Confidence, Not as a Binary Switch.
The Trend State engine is a systematic approach to trend analysis designed to address the fundamental limitations of traditional, binary-state indicators. Its core premise is that a market trend is not an "on/off" condition but a dynamic state that builds, sustains, and loses confidence over time. Instead of relying on a single price crossover, this engine operates like a jury, continuously gathering and weighing multiple forms of evidence to determine the true state of the market.
This results in a more nuanced, context-aware model that provides deeper insight into trend health, sustainability, and structural integrity.
The Problem with Binary-State Trend Indicators
Traditional indicators like a standard Supertrend operate on a binary, stateless model. A trend is either "up" or "down," and the switch is triggered by a single event: price closing across a calculated line. This model, while simple, suffers from critical drawbacks:
Lack of Memory: It has no concept of how strong the previous trend was. A powerful, multi-month bull run is treated with the same fragility as a weak, two-day rally. Both can be negated by a single bar's close.
Susceptibility to Whipsaws: Because the logic is binary, any volatile price action around the trendline can trigger a rapid succession of "buy" and "sell" signals, leading to over-trading in choppy or transitional markets.
No Concept of Neutrality: The market is forced into a bullish or bearish classification at all times. It lacks a "gray area" or a state of indecision, which is where many binary systems fail.
No Context of Trend Health: It cannot differentiate between a healthy, accelerating trend and one that is structurally compromised and likely to fail.
The Trend State Solution: A Multi-Pillar Confidence Model
The Trend State engine solves these issues through its proprietary architecture.
Pillar 1: The Rolling Evidence Matrix
This is the core of the engine. Instead of a single condition, the system maintains ten "evidence buckets"—five for bullish evidence and five for bearish. On every bar, new evidence is added to these buckets based on specific market behaviors. Simultaneously, the old evidence in every bucket is subject to a time-based decay , ensuring that recent events carry more weight than older ones.
The five categories of evidence collected are:
Impulse: Strong, directional thrust bars with high volume and a close near the highs/lows. Represents aggressive participation.
Structure: The breaking of recent swing highs/lows, or the reclamation of those levels after a failed break. Represents technical progress.
Exhaustion: Reversal pressure, identified through significant rejection wicks or volume divergences. Represents the failure of the opposing side.
Continuation: Quiet persistence, such as price continuing to close higher/lower while respecting the underlying price anchor. Represents sustained momentum.
Compression: A decrease in range and volatility, suggesting a buildup of energy for the next directional move.
Each category has a user-defined weight , allowing for fine-tuning of the engine's sensitivity to different market behaviors. The sum of this weighted evidence creates the final Bull and Bear Confidence Scores .
Pillar 2: The 3-State Engine (Bull / Transition / Bear)
Based on the confidence scores, the engine operates in one of three states:
Bull State (1): Bullish evidence is dominant, substantial, and actively holding above key thresholds.
Bear State (-1): Bearish evidence is dominant, substantial, and actively holding above key thresholds.
Transition State (0): Neither side has sufficient confidence, or the dominant side is losing its grip. This is the critical "gray area" where binary indicators produce whipsaws. The Trend State engine identifies this as a period of indecision or a potential turning point.
Pillar 3: The Damage Detection Layer
This is a crucial innovation that provides context on trend health. If a trend is in an active Bull or Bear state, this layer continuously scans for signs of structural compromise (e.g., price crossing below the anchor, strong opposing impulse bars, high opposing pressure). If enough "damage" accumulates, the trend is flagged as Damaged . A damaged state has critical consequences:
Accelerated Deterioration: The confidence score of the current trend decays faster.
Reduced Impulse: New evidence in favor of the damaged trend has less impact.
Increased Fragility: The thresholds required to flip the trend into a Transition state are lowered, making it easier for the compromised trend to fail.
Pillar 4: Optional Footprint Enhancement
For maximum fidelity, the engine can integrate real order flow data from footprint charts. This enhances the evidence-gathering process by confirming price action with volume. For example, a bullish impulse bar is given a significantly higher score if it is accompanied by strong, positive delta, confirming aggressive market buying.
A METHODOLOGICAL COMPARISON: Standard Supertrend vs. Trend State Engine
To understand the architectural difference, consider this side-by-side comparison:
🔧 COMPREHENSIVE INPUT SYSTEM
Core Engine
Anchor Length: The EMA period for the central price anchor, which acts as the gravitational baseline for the system.
Base Width Multiplier: The master ATR multiplier for the trail distance.
Bucket Decay: The per-bar decay rate (0.50-0.99) for all evidence buckets. A lower value gives the system a shorter memory, while a higher value allows it to "remember" evidence for longer.
Bucket Weights
Granular control to assign a weight to each of the five evidence categories ( Impulse, Structure, Exhaustion, Continuation, Compression ). This allows you to calibrate the engine's personality—for example, making it more sensitive to structural breaks than to impulse moves.
State Engine
Enter Net Threshold: The minimum net confidence score (Bull Score - Bear Score) required to shift from the Transition state into a confirmed Bull or Bear state.
Hold Net Threshold: While in an active Bull/Bear state, if the net confidence falls below this value, the trend is considered lost, and the engine returns to the Transition state.
Dominance Threshold: A ratio (Net / Total) that ensures a true trend is established, not just a slight edge in a low-activity market.
Damage Layer
Enable Damage Detection: Toggles the entire damage analysis module.
Damage Score Threshold: The cumulative damage score required to flag a trend as "Damaged."
Decay Multiplier, Impulse Retention, Threshold Ease: A suite of inputs to control exactly how a "Damaged" state affects the system's behavior, allowing for fine-tuning of its risk-off response.
🎨 ADVANCED VISUAL SYSTEM
The Trend State engine leverages the DafeVisLib library to provide a clean, professional, and highly informative visual experience.
The Main Trend Line: The line's color instantly communicates the current state: Bullish, Bearish, or Transition. Crucially, it will adopt a distinct "alert" color when the active trend is flagged as Damaged .
State Markers: Clear labels appear on the chart to mark the exact bar where the state shifts to Bull (▲), Bear (▼), or Transition (◆).
Damage Markers: An alert symbol (!) appears above/below the bar when the Damage Threshold is breached, providing an un-missable visual warning of trend deterioration.
The Cloud: The area between the trend line and the price anchor is shaded, creating a dynamic cloud that provides a clear visual representation of the trend's strength and control.
📊 GAUGE DASHBOARD & NARRATIVE PANEL
The indicator includes two advanced UI elements for at-a-glance analysis.
The Gauge Dashboard
This panel provides a complete quantitative breakdown of the engine's internal state, featuring:
State Info: Displays the current state, Footprint status, and live Delta.
Confidence Engine Gauges: Real-time gauges visualizing the raw Bull, Bear, and Net Confidence scores.
Pressure Kinetics Gauges: Displays the Dominance and Pressure ratios, showing which side is in control of the market auction.
Damage Layer Gauges: Shows the current Damage Status (Intact/Damaged) and the live scores being accumulated against the active trend.
Evidence Bucket Breakdowns: Individual gauges for all 10 evidence buckets, allowing you to see exactly what kind of evidence is driving the current market move.
The Narrative Panel
This unique panel provides a qualitative, human-readable summary of the complex quantitative data from the engine. It translates the numbers into a clear story, with simple statements describing the current Regime , Kinetics , Structure , and Order Flow .
⚖️ RESPONSIBLE USAGE
This is a Decision-Support System: The Trend State engine is designed to provide a deep, contextual understanding of trend health. It is not a black-box signal generator. Its outputs should be used to inform and enhance a pre-existing trading plan.
Context is Key: A "Bull State" confirmation is a statement about trend confidence, not a guarantee of future price movement. Always consider the broader market context.
Calibration is Recommended: The default weights and thresholds are robustly balanced, but the true power of the engine is unlocked by calibrating these settings to the specific personality of the asset and timeframe you are trading.
🔮 CONCLUSION
The Trend State engine represents a significant evolution in trend analysis. By moving away from a simple, binary model and adopting a multi-faceted, evidence-based confidence system, it offers a more robust and realistic interpretation of market dynamics. Its ability to quantify trend health through its Damage Layer and to recognize periods of indecision with its Transition State provides traders with critical context that traditional indicators simply cannot see. This is a tool for traders who wish to understand not just the direction of a trend, but its quality, sustainability, and structural integrity.
— Dskyz, Trade with insight. Trade with anticipation. (Funny how innovation suddenly shows up everywhere once you build something real. This is a Rolling Confidence Matrix , foundation level work, not copied code, not recycled concepts, and not the same thing with a new paint job.) Indicator

FLEE Customizable Strong FVGsIn simple terms:
It’s a 3-candle pattern showing inefficiency.
Here’s the visual logic (assuming a bullish FVG):
Candle 1: a bearish or minor candle.
Candle 2: a large bullish candle (impulsive move).
Candle 3: another bullish or neutral candle.
The gap appears between the high of Candle 1 and the low of Candle 3.
That area often acts as a “magnet” later — price may return to “fill” it before resuming trend direction.
For bearish FVG, it’s the opposite:
The gap forms between the low of Candle 1 and the high of Candle 3 in a strong move down.
2. How an Indicator Detects FVGs
Most FVG indicators (such as in PulseWire’s Pine Script) look for the 3-candle structure:
Bullish FVG condition:
Candle1.high < Candle3.low
Bearish FVG condition:
Candle1.low > Candle3.high
When this happens, the indicator shades or boxes that range (the gap) between those levels.
Many indicators will:
Highlight the area between the gap lines.
Delete the zone once it’s “filled” (price touches it again).
Allow customization (colors, timeframe, expiry logic, etc.)
3. Marking Strong FVG Zones
Not every FVG is equal — some are much stronger. “Strong zones” are usually defined by confluence and context.
Here’s how you can identify stronger ones:
A. Volume or Impulse Strength
Strong zones usually come after a powerful displacement candle — large body, small wicks, and maybe a volume spike.
That shows genuine institutional activity.
B. Higher Timeframe Origin
FVGs formed on H1, H4, or Daily charts carry more weight than those on M5 or M15.
C. Market Structure
Zones that align with:
Break of structure (BOS)
Order block origin are generally more reliable.
D. Unfilled Gaps
If the FVG has not been rebalanced yet, it’s still valid. Once price trades fully into that gap, it’s “filled” and loses power.
E. Multiple confluences
Combine FVG zones with:
Fibonacci retracement (e.g., gap within 50–61.8%)
Key support/resistance levels
Liquidity zones (equal highs/lows nearby) Indicator

BandsLibLibrary "BandsLib"
f_calc_survival_bands(basis, dev, shift_z, prob_pct, mr_shift)
Parameters:
basis (float) : Base price level (MA, median, etc.)
dev (float) : Standard deviation or volatility measure
shift_z (float) : Directional shift factor (e.g., vector pressure, momentum)
prob_pct (float) : Survival probability percentage (e.g., 10 = 10%)
mr_shift (float) : Mean reversion shift (optional, contrarian to shift_z)
Returns: Tuple of upper and lower survival bands
f_detect_squeeze(band_up, band_dn, price, damping)
Parameters:
band_up (float) : Upper band level
band_dn (float) : Lower band level
price (float) : Current price
damping (float) : Correlation damping factor (0-1)
Returns: Tuple of bullish/bearish squeeze signals and bandwidth percentile
f_detect_confluence(basis, fv, dev, tol_mult, min_lines)
Parameters:
basis (float) : Base price level (MA, median, etc.)
fv (float) : Fair value or equilibrium price
dev (float) : Standard deviation or volatility measure
tol_mult (float) : ATR multiplier for clustering tolerance
min_lines (int) : Minimum number of converging lines to trigger confluence Library

BasketLibLibrary "BasketLib"
f_calc_correlation_score(base_return, candidate_return, corr_len, smooth_len, is_self)
Parameters:
base_return (float) : Base asset 1-bar return
candidate_return (float) : Candidate asset 1-bar return
corr_len (int) : Correlation calculation length
smooth_len (simple int) : EMA smoothing length
is_self (bool) : Whether candidate is the base asset itself
Returns: Correlation score (0.7 * raw + 0.3 * ema), or na if invalid
f_rank_and_select(scores, n)
Parameters:
scores (array) : Array of correlation scores
n (int) : Number of assets to select (typically 4)
Returns: Array of selected indices
f_is_self_reference(candidate_symbol, base_ticker)
Parameters:
candidate_symbol (string) : Full symbol string (e.g., "BINANCE:BTCUSDT")
base_ticker (string) : Base asset ticker (e.g., "BTC")
Returns: True if candidate is the base asset
f_route_scan_idx(idx, prices)
Parameters:
idx (int) : Index (0-9)
prices (array) : Array of 10 scan candidate prices
Returns: Price at index, or na if invalid
f_get_preset_basket(preset_name)
Parameters:
preset_name (string) : Name of preset ("Basket B (Memes)", etc.)
Returns:
f_get_default_scan_symbols()
f_calc_basket_fit(score1, score2, score3, score4)
Parameters:
score1 (float) : Correlation score of asset 1
score2 (float) : Correlation score of asset 2
score3 (float) : Correlation score of asset 3
score4 (float) : Correlation score of asset 4
Returns: Basket fit percentage (0-100)
f_get_fit_label(fit_pct)
Parameters:
fit_pct (float) : Basket fit percentage (0-100)
Returns: Quality label ("Excellent", "Good", "Fair", "Poor")
f_get_fit_color(fit_pct)
Parameters:
fit_pct (float) : Basket fit percentage (0-100)
Returns: Color (lime, aqua, orange, red)
ScanCandidate
Fields:
symbol (series string)
price (series float)
return_1bar (series float)
correlation_raw (series float)
correlation_ema (series float)
score (series float)
is_self (series bool)
BasketSelection
Fields:
sym1 (series string)
sym2 (series string)
sym3 (series string)
sym4 (series string)
score1 (series float)
score2 (series float)
score3 (series float)
score4 (series float)
idx1 (series int)
idx2 (series int)
idx3 (series int)
idx4 (series int) Library

Meridian Zones [JOAT]Meridian Zones
Introduction
Meridian Zones is an advanced open-source session analysis engine built for traders who structure their trading around the Asia, London, and New York sessions. Unlike typical session indicators that clutter the chart with dozens of lines and levels, Meridian Zones takes a deliberately clean approach: session boxes, killzone backgrounds, session-colored candles, and precise liquidity sweep labels live on the chart, while all analytical depth lives in a fully-populated 15-row dashboard. The result is a chart that remains readable at any zoom level while giving you institutional-grade session intelligence at a glance.
The indicator tracks session ranges, calculates session VWAP, monitors volume distribution across sessions, detects liquidity sweeps with wick filtering and cooldown logic, flags volume spikes, grades institutional candles, and reports previous day high/low positioning — all without drawing a single horizontal line on the chart.
Why This Indicator Exists
Session-based trading is a cornerstone of institutional methodology. The Asia session establishes a range, London often breaks that range with directional intent, and New York either continues or reverses the London move. Understanding which session is dominant, where sweeps occur, and how volume distributes across sessions gives traders a significant edge.
Most session indicators fall into two traps: either they are too simple (just drawing boxes) or too cluttered (drawing session highs, lows, midpoints, opens, VWAP lines, and previous session levels all on the chart simultaneously). Meridian Zones avoids both by:
Drawing only the essential visual elements on the chart — session range boxes, killzone background shading, and labeled signals
Moving all analytical data into a comprehensive dashboard where it can be read without visual noise
Adding features that most session indicators lack entirely: session VWAP calculation, volume-weighted session dominance, institutional candle detection within sessions, and precise liquidity sweep identification with ATR-based wick filtering
Core Session Engine
Sessions are defined by UTC hour ranges (all configurable):
Asia: 00:00 - 08:00 UTC (default)
London: 08:00 - 16:00 UTC (default)
New York: 13:00 - 21:00 UTC (default)
The indicator detects session opens and closes, tracks high/low/volume/VWAP within each session, and draws range boxes when sessions close. A timeframe filter ensures the indicator only displays on charts where session analysis is meaningful (up to 4H by default).
Session overlap (London + NY) is automatically detected and reported in the dashboard, as overlap periods often produce the highest-volume, most directional moves of the day.
Session Tracking and Analytics
For each session, the indicator calculates and tracks:
Session Range: High and low of the session, displayed as a colored box
Session VWAP: Volume-weighted average price calculated from session open, updated every bar. This is the true institutional fair value for the session — not a simple midpoint
Session Momentum: The ratio of bullish candles to total candles within the session, giving a quick read on directional bias
Session Volume: Total volume accumulated during the session, used for dominance and volume leader calculations
Session Open/Close Prices: Used to determine session bias (bullish if close > open, bearish if close < open)
Liquidity Sweep Detection
One of the most valuable features is the precise liquidity sweep detector. A sweep occurs when price wicks beyond a session high or low and closes back inside — this is institutional stop hunting.
The sweep detector uses two filters to avoid false signals:
ATR Wick Filter: The wick beyond the session level must exceed a configurable ATR multiple (default 0.4x ATR). This eliminates tiny wicks that barely touch the level.
Cooldown Timer: After a sweep is detected, no new sweep can fire for a configurable number of bars (default 8). This prevents multiple labels from stacking on the same sweep event.
Sweep labels are color-coded: bullish sweeps (wicking below and closing above) in teal, bearish sweeps (wicking above and closing below) in rose.
Volume Spike Detection
When volume exceeds the session's average volume by a configurable multiplier (default 2.0x), a volume spike flag appears. Volume spikes during sessions often coincide with institutional order execution and can confirm the validity of a sweep or directional move.
Institutional Candle Labels
Candles with a body-to-range ratio exceeding the threshold (default 75%) are flagged as institutional candles. These are large-bodied, low-wick candles that indicate strong directional conviction — the kind of candles that institutions create when executing large orders.
Session-Colored Candles
When enabled, candles are tinted by the active session: gold for Asia, blue for London, rose for New York. This provides an instant visual reference for which session produced each candle, making it easy to see session transitions and overlap periods on the chart.
15-Row Dashboard
The dashboard is the analytical heart of the indicator. Every cell is populated — no empty rows. It displays:
Row 1: Active Session — Which session is currently active, or "OFF" between sessions
Row 2: Overlap Status — Whether London and NY are overlapping
Row 3-5: Session Ranges — Asia, London, and NY ranges in price with pip/point size
Row 6-8: Session Bias — Bullish/Bearish for each session based on open vs close
Row 9: Dominance — Which session has the largest range (the "dominant" session)
Row 10: Volume Leader — Which session has the highest total volume
Row 11: VWAP Position — Whether current price is above or below the active session's VWAP
Row 12: Range/ATR — Current session range as a multiple of ATR (shows how extended the session is)
Row 13: PDH/PDL — Previous Day High and Low with current price position relative to them
Row 14: Candle Quality — Current candle's body ratio and institutional grade
Row 15: Sweep Radar — Most recent sweep direction and how many bars ago it occurred
Input Parameters
Session Definitions (UTC):
Asia Start/End Hour (default 0/8)
London Start/End Hour (default 8/16)
NY Start/End Hour (default 13/21)
Features:
Show Session Boxes, Killzone Background, Session-Colored Candles, Session Open Markers
Show Liquidity Sweeps, Volume Spike Markers, Institutional Candle Labels, Dashboard
Sessions to Keep (default 3) — how many past session boxes remain on chart
Sweep Min Wick ATR multiplier (default 0.4), Sweep Cooldown bars (default 8)
Volume Spike Multiplier (default 2.0), Institutional Candle Body % (default 75%)
Timeframe Filter:
Show Up To (default 4H) — prevents the indicator from displaying on higher timeframes where session analysis is not meaningful
How to Use This Indicator
Step 1: Identify the Dominant Session
Check the dashboard for which session has the largest range and highest volume. The dominant session sets the directional tone for the day.
Step 2: Watch for Asia Range Breaks
London often breaks the Asia range. When London's first move sweeps the Asia high or low, the sweep label confirms the liquidity grab. The direction of the break often sets the trend for the day.
Step 3: Monitor Overlap Period
The London-NY overlap (typically 13:00-16:00 UTC) produces the highest volume and most decisive moves. Volume spikes during overlap are particularly significant.
Step 4: Use VWAP Position for Bias
If price is above the session VWAP, institutional flow is net bullish for that session. Below VWAP, net bearish. The dashboard shows this in real-time.
Step 5: Confirm with Institutional Candles
When a sweep occurs and is followed by an institutional candle (large body, high volume), the move has strong institutional backing.
Step 6: Reference PDH/PDL
Previous Day High and Low are key institutional levels. The dashboard shows whether price is above PDH (bullish), below PDL (bearish), or between them (range-bound).
Limitations
Session analysis is most relevant on intraday timeframes (1m to 4H). The timeframe filter prevents display on higher timeframes, but users should understand that session dynamics are inherently intraday concepts.
UTC-based session times may need adjustment for instruments that trade in different time zones or have non-standard trading hours.
Volume data quality varies by instrument. Forex volume on PulseWire is tick volume, which approximates but does not equal true institutional volume.
Session VWAP resets at each session open. It is not a continuous daily VWAP.
Sweep detection relies on wick analysis, which can produce false signals in extremely volatile or illiquid conditions.
The indicator shows session dynamics, not price predictions. A bullish session bias does not guarantee price will continue higher.
Originality Statement
This indicator is original in its clean-chart, dashboard-heavy approach to session analysis. While session boxes and killzone backgrounds exist in other indicators, this indicator is justified because:
It deliberately separates visual elements (chart) from analytical data (dashboard), solving the clutter problem that plagues most session indicators
Session VWAP calculation per session provides institutional fair value that simple midpoint calculations cannot match
The liquidity sweep detector uses dual filtering (ATR wick threshold + cooldown timer) for precision that basic "price crossed level" detection lacks
Volume-weighted session dominance and volume leader tracking provide insights into which session is driving the market — information not available in standard session indicators
Institutional candle grading within sessions identifies the specific candles where large orders were executed
The 15-row dashboard presents all session analytics simultaneously with zero empty cells, creating a true session command center
The combination of session boxes, sweep detection, volume spikes, institutional candle grading, and comprehensive analytics in a single clean-chart indicator is not available in existing public scripts
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss and is not suitable for all investors.
Session analysis reveals historical patterns in how different trading sessions behave. Past session patterns do not guarantee future session behavior. Market conditions, news events, and institutional positioning can cause sessions to behave atypically at any time.
Always use proper risk management. Never risk more than you can afford to lose. The author is not responsible for any losses incurred from using this indicator.
-Made with passion by officialjackofalltrades
Indicator

Stock Market Correlation Heatmap PROStock Market Correlation Heatmap PRO
This script is designed to provide a real-time view of how global equity markets are moving relative to the current chart, using correlation as the primary metric.
Instead of focusing on a single instrument in isolation, it offers a broader perspective by tracking multiple indices simultaneously and visualizing their relationship through a structured heatmap.
Core Concept
Markets rarely move independently.
Major indices across the world are often highly correlated during risk-on or risk-off environments, and understanding these relationships can provide additional context for trade decisions.
This script calculates rolling correlation values between the current chart and a basket of global indices, then translates those values into a visual heatmap.
Correlation Logic
Correlation measures how closely two instruments move together:
• +1.0 → Strong positive correlation (moving together)
• 0.0 → No meaningful relationship
• -1.0 → Strong negative correlation (moving opposite)
By continuously recalculating these values over a configurable lookback period, the script provides a dynamic view of market alignment.
Global Market Coverage
The heatmap includes a wide range of global indices, including:
• US markets (S&P 500, NASDAQ, Dow, Russell)
• European markets (DAX, FTSE, CAC, Euro Stoxx)
• Asian markets (Nikkei, Hang Seng, KOSPI, China A50)
• Emerging and regional indices
This allows users to quickly assess whether moves are localized or part of a broader global trend.
Spectral Heatmap Visualization
Correlation values are mapped to a multi-step color gradient for clarity:
• Dark Green → Strong positive correlation
• Light Green → Moderate alignment
• Yellow → Neutral / decoupled
• Orange → Weak inverse correlation
• Red → Strong negative correlation
This “spectral” approach allows for quick interpretation without needing to read raw numbers.
Market Tide (Average Correlation)
The script calculates an aggregate correlation value across all tracked indices, referred to as the “Market Tide.”
This represents overall global alignment with the current chart and can be used to identify:
• Broad market consensus
• Divergence between the chart and global flows
• Strength or weakness of a move relative to the wider market
Use Cases
This tool can be used for:
• Confirming trade direction with global market alignment
• Identifying divergence (when your chart moves independently)
• Avoiding trades during low correlation / mixed conditions
• Understanding risk-on vs risk-off environments
It is particularly useful for indices, futures, and macro-driven markets.
Interpretation Guide
• Strong Green Across Board → Broad market agreement (trend confirmation)
• Mixed Colors → Fragmented market (lower conviction environment)
• Red Across Board → Inverse positioning (potential hedge or divergence)
• Yellow / Neutral → Lack of clear global direction
Customization
• Adjustable correlation lookback period
• Fully customizable symbol list
• Editable color palette for visual preference
Notes
This script is intended as a contextual tool to support decision-making.
It does not generate direct buy or sell signals and should be used alongside price action, structure, and risk management. Indicator

kNNLib with turboQuant encodingLibrary "kNNLib"
f_quantize_3bit(value, bounds)
Quantize a single feature to 3-bit index (0-7) using percentile boundaries
Parameters:
value (float) : Feature value to quantize
bounds (array) : Array of 9 percentile boundaries
Returns: Integer index 0-7
f_compute_percentile_bounds(feature_array, history_len)
Compute percentile boundaries for a feature over a rolling window
Parameters:
feature_array (array) : Array of feature values (size = history_len)
history_len (int) : Number of bars to use for percentile calculation
Returns: Array of 9 boundaries
f_turboquant_encode(f1, f2, f3, f4, f5, f6)
Encode 6 features into 18-bit TurboQuant state ID
Parameters:
f1 (int) : Feature 1 (VectorOsc) quantized index 0-7
f2 (int) : Feature 2 (BasketCorr) quantized index 0-7
f3 (int) : Feature 3 (InnovZ) quantized index 0-7
f4 (int) : Feature 4 (TE_Osc) quantized index 0-7
f5 (int) : Feature 5 (OrthoZcvb) quantized index 0-7
f6 (int) : Feature 6 (PhiDiv) quantized index 0-7
Returns: 18-bit state ID (0 to 262143)
f_normalize_basket_corr(rho, rho_history, norm_len)
Normalize BasketCorr using Fisher transform then z-score
Parameters:
rho (float) : Raw correlation value
rho_history (array) : Array of historical rho values
norm_len (int) : Normalization window length
Returns: Normalized correlation
f_normalize_te_osc(te_osc, te_history, norm_len)
Normalize TE_Osc using rolling z-score
Parameters:
te_osc (float) : Raw TE oscillator value
te_history (array) : Array of historical TE values
norm_len (int) : Normalization window length
Returns: Normalized TE
f_normalize_phi_div(phi_div, phi_history, norm_len)
Normalize PhiDiv using rolling z-score
Parameters:
phi_div (float) : Raw PhiDiv value
phi_history (array) : Array of historical PhiDiv values
norm_len (int) : Normalization window length
Returns: Normalized PhiDiv
f_euclidean_distance(f1_current, f2_current, f3_current, f4_current, f5_current, f6_current, f1_hist, f2_hist, f3_hist, f4_hist, f5_hist, f6_hist)
Calculate Euclidean distance between two 6D feature vectors
Parameters:
f1_current (float) : Current bar feature 1
f2_current (float) : Current bar feature 2
f3_current (float) : Current bar feature 3
f4_current (float) : Current bar feature 4
f5_current (float) : Current bar feature 5
f6_current (float) : Current bar feature 6
f1_hist (float) : Historical bar feature 1
f2_hist (float) : Historical bar feature 2
f3_hist (float) : Historical bar feature 3
f4_hist (float) : Historical bar feature 4
f5_hist (float) : Historical bar feature 5
f6_hist (float) : Historical bar feature 6
Returns: Euclidean distance
f_find_k_nearest(f1_current, f2_current, f3_current, f4_current, f5_current, f6_current, f1_history, f2_history, f3_history, f4_history, f5_history, f6_history, k, max_history)
Find K nearest neighbors using linear scan
Parameters:
f1_current (float) : Current bar feature 1
f2_current (float) : Current bar feature 2
f3_current (float) : Current bar feature 3
f4_current (float) : Current bar feature 4
f5_current (float) : Current bar feature 5
f6_current (float) : Current bar feature 6
f1_history (array) : Array of historical feature 1 values
f2_history (array) : Array of historical feature 2 values
f3_history (array) : Array of historical feature 3 values
f4_history (array) : Array of historical feature 4 values
f5_history (array) : Array of historical feature 5 values
f6_history (array) : Array of historical feature 6 values
k (int) : Number of neighbors to find
max_history (int) : Maximum bars to search
Returns: Array of K nearest neighbor indices
f_calculate_confidence(f1_current, f2_current, f3_current, f4_current, f5_current, f6_current, f1_history, f2_history, f3_history, f4_history, f5_history, f6_history, k_nearest_indices)
Calculate epistemic confidence score from K-nearest distances
Parameters:
f1_current (float) : Current bar feature 1
f2_current (float) : Current bar feature 2
f3_current (float) : Current bar feature 3
f4_current (float) : Current bar feature 4
f5_current (float) : Current bar feature 5
f6_current (float) : Current bar feature 6
f1_history (array) : Array of historical feature 1 values
f2_history (array) : Array of historical feature 2 values
f3_history (array) : Array of historical feature 3 values
f4_history (array) : Array of historical feature 4 values
f5_history (array) : Array of historical feature 5 values
f6_history (array) : Array of historical feature 6 values
k_nearest_indices (array) : Array of K nearest neighbor indices
Returns: Confidence score Library

Indicator

Strategy

3D Opportunity Cone [LuxAlgo]The 3D Opportunity Cone indicator is a multi-dimensional visualization tool that maps market conditions into a 3D geometric space to identify high-value, low-risk entry points. By synthesizing price action, volatility, and volume into a single spatial model, it allows traders to visualize the "distance" between current market states and optimal buying conditions.
🔶 USAGE
The indicator projects a 3D cone onto the right side of the chart, representing a theoretical "Opportunity Space." A historical trail of dots moves through this space, showing how the market's internal mechanics have evolved over time.
🔹 The 3D Coordinate System
The position of the market "point" within the cone is determined by three distinct factors:
Height (Value Factor): Derived from the Stochastic oscillator. Higher positions in the cone represent oversold (value) conditions, while lower positions represent overbought states.
Radius (Risk Factor): Derived from the Average True Range (ATR). Points closer to the center of the cone represent lower volatility risk, while points pushed toward the outer edges indicate high-volatility environments.
Angle (Conviction Factor): Derived from Normalized Volume. The rotation around the central axis indicates the level of market participation and conviction behind the current price movement.
🔹 Interpreting the Zones
The "Buy Zone" is located at the apex (top) of the cone. An ideal opportunity occurs when the market point is high (Value), centered (Low Risk), and supported by conviction. Conversely, the "Risk Zone" at the base of the cone represents overbought or high-volatility conditions where caution is required.
🔶 DETAILS
The script uses a custom projection engine to convert 3D coordinates (X, Y, Z) into 2D chart space. The "Opportunity Space" is anchored to a Simple Moving Average (SMA) to provide a localized context for the visualization.
The historical trail provides a temporal dimension, allowing users to see if the market is spiraling toward a value zone or drifting away into a high-risk state. The trail colors fade from red (High Risk/Overbought) to green (High Value/Oversold) to provide an immediate visual cue of market health.
🔶 SETTINGS
🔹 Cone Settings
Evaluation Lookback: The period used for calculating the Stochastic, ATR, and Volume normalization.
Cone Scale: Adjusts the visual size of the 3D cone on the chart.
X Offset (Bars): Determines how many bars to the right of the current price the cone is rendered.
3D Tilt: Adjusts the perspective/inclination of the 3D projection.
🔹 Trail & Colors
Highlight Color: The color of the current market point and its projection lines.
Cone Fill Color: The background color of the cone's surface.
Trail Length: The number of historical periods to display within the 3D space.
Indicator
