Kalman Hull Kijun [BackQuant]Kalman Hull Kijun
A trend baseline that merges three ideas into one clean overlay, Kalman filtering for noise control, Hull-style responsiveness, and a Kijun-like Donchian midline for structure and bias.
Context and lineage
This indicator sits in the same family as two related scripts:
Kalman Price Filter
This is the foundational building block. It introduces the Kalman filter concept, a state-estimation algorithm designed to infer an underlying “true” signal from noisy measurements, originally used in aerospace guidance and later adopted across robotics, economics, and markets.
Kalman Hull Supertrend
This is the original script made, which people loved. So it inspired me to create this one.
Kalman Hull Kijun uses the same core philosophy as the Supertrend variant, but instead of building a Supertrend band system, it produces a single structural baseline that behaves like a Kijun-style reference line.
What this indicator is trying to solve
Most trend baselines sit on a bad trade-off curve:
If you smooth hard, the line reacts late and misses turns.
If you react fast, the line whipsaws and tracks noise.
Kalman Hull Kijun is designed to land closer to the middle:
Cleaner than typical fast moving averages in chop.
More responsive than slow averages in directional phases.
More “structure aware” than pure averages because the baseline is range-derived (Kijun-like) after filtering.
Core idea in plain language
The plotted line is a Kijun-like baseline, but it is not built from raw candles directly.
High level flow:
Start with a chosen price stream (source input).
Reduce measurement noise using Kalman-style state estimation.
Add Hull-style responsiveness so the filtered stream stays usable for trend work.
Build a Kijun-like baseline by taking a Donchian midpoint of that filtered stream over the base period.
So the output is a single baseline that is intended to be:
Less jittery than a simple fast MA.
Less laggy than a slow MA.
More “range anchored” than standard smoothing lines.
How to read it
1) Trend and bias (the primary use)
Price above the baseline, bullish bias.
Price below the baseline, bearish bias.
Clean flips across the baseline are regime changes, especially when followed by a hold or retest.
2) Retests and dynamic structure
Treat the baseline like dynamic S/R rather than a signal generator:
In uptrends, pullbacks that respect the baseline can act as continuation context.
In downtrends, reclaim failures around the baseline can act as continuation context.
Repeated back-and-forth around the line usually means compression or chop, not clean trend.
3) Extension vs compression (using the fill)
The fill is meant to communicate “distance” and “pressure” visually:
Large separation between price and baseline suggests expansion.
Price compressing into the baseline suggests rebalancing and decision points.
Inputs and what they change
Kijun Base Period
Controls the structural memory of the baseline.
Higher values track broader swings and reduce flips.
Lower values track tighter swings and react faster.
Kalman Price Source
Defines what data the filter is estimating.
Close is usually the cleanest default.
HL2 often “feels” smoother as an average price.
High/Low sources can become more reactive and less stable depending on the market.
Measurement Noise
Think of this as the main smoothness knob:
Higher values generally produce a calmer filtered stream.
Lower values generally produce a faster, more reactive stream.
Process Noise
Think of this as adaptability:
Higher values adapt faster to changing conditions but can get twitchy.
Lower values adapt slower but stay stable.
Plotting and UI (what you see on chart)
1) Adaptive line coloring
Baseline turns bullish color when price is above it.
Baseline turns bearish color when price is below it.
This makes the state readable without extra panels.
2) Gradient “energy” fill
Bull fill appears between price and baseline when above.
Bear fill appears between price and baseline when below.
The goal is clarity on separation and control, not decoration.
3) Rim effect
A subtle band around price that only appears on the active side.
Helps highlight directional control without hiding candles.
4) Candle painting (optional)
Candles can be colored to match the current bias.
Useful for scanning many charts quickly.
Disable if you prefer raw candles.
Alerts
Long state alert when price is above the baseline.
Short state alert when price is below the baseline.
Best used as a bias or regime notification, not a standalone entry trigger.
Where it fits in a workflow
This is a context layer, it pairs well with:
Market structure tools, BOS/MSB, OBs, FVGs.
Momentum triggers that need a regime filter.
Mean reversion tools that need “do not fade trends” context.
Limitations
No baseline eliminates chop whipsaws, tuning only manages the trade-off.
Settings should not be copy pasted across assets without checking behavior.
This does not forecast, it estimates and smooths state, then expresses it as a structural baseline.
Disclaimer
Educational and informational only, not financial advice.
Not a complete trading system.
If you use it in any trading workflow, do proper backtesting, forward testing, and risk management before any live execution.
Statistics
Interest Zones ScannerThis indicator automatically scans a user-defined price range (on current or higher timeframe) to detect and plot the strongest horizontal support/resistance zones based on validated price reactions. It intelligently identifies levels where price has repeatedly bounced without breaking for a specified number of bars, prioritizing high-probability reaction areas.
How It Works (Technical Methodology)
Range Calculation
The script determines the high/low range using a configurable method:
"Lookback Bars": User-defined number of bars (default 400) on the target timeframe.
"Fixed Start Date": Bars since a specified date (default dynamic).
Data is fetched via request.security() from a selectable timeframe (default current chart TF) for multi-timeframe alignment.
Auto Mode Scanning
When enabled:
Scans the entire range in small percentage steps (default 1.0%, adjustable down to 0.5%).
For each potential level, creates a thin volatility-adjusted zone (height % of price, default 0.07%).
Counts "valid hits": Instances where price touches the zone and holds (no break) for user-defined bars (default 10).
Break detection: Configurable "Close" (strict) or "Wick" (sensitive).
Assumes support/resistance direction based on close relative to zone center.
Level Selection and Filtering
Ranks candidates by hit count (highest first).
Applies minimum distance filter (% apart, default 8%) to avoid clustering.
Limits to user-defined max zones (default 9) for clean display.
Sorts final zones from low to high price.
Manual Mode Alternative
When auto disabled: Directly uses user-input percentages (e.g., classic Fibo levels like 23.6, 50, 61.8) applied to the range – no validation/scoring.
Zone Construction
Horizontal boxes centered on validated levels, with dynamic height (% of price).
Colored by position: Supply (above close, default light gray), Demand (below close, default cyan).
Optional full extension (both sides) or right-only.
Labeled with percentage from range low.
Dashboard and Visuals
Table (positionable) shows:
% Level, Exact Price, Hit Count (green if >3).
Header with validation details and lookback info.
Vertical line marks range start for reference.
How to Use
This scanner excels at finding statistically validated horizontal zones where price has shown respect – ideal for support/resistance, mean reversion, or breakout setups.
Auto Mode: Best for discovering hidden/non-obvious levels. Higher hit counts = stronger zones (expect reactions/retests).
Validation Bars: Increase (e.g., 20+) for stricter, higher-quality zones in trending markets; lower for more sensitive detection.
Min Distance: Higher % for fewer, separated zones; lower for denser grids.
Multi-Timeframe: Set target TF higher (e.g., Daily) for major structural levels on lower charts.
Supply Zones (Above Price): Potential resistance – shorts or take-profits.
Demand Zones (Below Price): Potential support – longs or stops below.
Confluence: Combine with volume, order blocks, or fibo for entries. Watch for multiple hits + confluence.
Manual Mode: Quick plotting of custom % (e.g., fibo retracements/extensions).
Fine-tune scan step smaller for precision (slower on large lookbacks) or larger for speed.
Disclaimer
This indicator is a technical analysis tool and should be used in conjunction with other forms of analysis. Past performance does not guarantee future results. Always use proper risk management.
Wickless Candle Revisit TrackerWickless Candle Revisit Tracker
Identifies wickless candles (strong momentum candles) and tracks whether price revisits their opening level, providing statistical insights into price behavior patterns.
WHAT ARE WICKLESS CANDLES?
• Green wickless: Open = Low (no lower wick) - opened at the low and moved only upward
• Red wickless: Open = High (no upper wick) - opened at the high and moved only downward
These candles represent strong directional momentum, and their opening levels often act as support/resistance zones that price may revisit.
KEY FEATURES:
• Automatic Detection: Identifies wickless candles with configurable tolerance for broker spread
• Real-time Tracking: Monitors each wickless candle until price revisits its opening level
• Visual Indicators:
- Labels show "WL↑" or "WL↓" with bars count when revisited (or "N/A" if pending)
- Horizontal lines mark price levels (gray dashed = pending, green solid = revisited)
• Comprehensive Statistics Table:
- Total wickless candles detected
- Revisit rate percentage
- Min/Max/Average bars until revisit
- Pending count
• History Limit: Configure how far back to analyze (default: 500 bars)
• Customizable: Adjust colors, toggle labels/lines/table, reposition statistics
USE CASES:
• Identify potential support/resistance levels from momentum candles
• Measure how often price fills "fair value gaps" or inefficiencies
• Track mean reversion patterns after strong momentum moves
• Backtest the reliability of wickless candle levels as trading zones
SETTINGS:
• Wick Tolerance: Allow small wicks due to broker spread (e.g., 0.0001 for forex)
• History Limit: Number of bars to analyze (older candles are hidden)
• Visual Controls: Toggle labels, lines, and statistics table
• Color Customization: Adjust line colors for pending/revisited states
ALERTS:
Built-in alerts for wickless candle detection (green, red, or both).
Perfect for traders analyzing price inefficiencies, fair value gaps, and momentum-based support/resistance levels.
QuantLabs MASM Correlation TableThe Market is a graph. See the flows:
The QuantLabs MASM is not a standard correlation table. It is an Alpha-Grade Scanner architected to reveal the hidden "hydraulic" relationships between global macro assets in real-time.
Rebuilt from the ground up for Version 3, this engine pushes the absolute limits of the Pine Script™ runtime. It utilizes a proprietary Logarithmic Math Engine, Symmetric Compute Optimization, and a futuristic "Ghost Mode" interface to deliver a 15x15 real-time correlation matrix with zero lag.
Under the Hood: The Quant Architecture
We stripped away standard libraries to build a lean, high-performance engine designed for institutional-grade accuracy.
1. Alpha Math Engine (Logarithmic Returns) Most tools calculate correlation based on Price, which generates spurious signals (e.g., "Everything is correlated in a bull run").
The Solution: Our engine computes Logarithmic Returns (log(close/close )) by default. This measures the correlation of change (Velocity & Vector), not price levels.
The Result: A mathematically rigorous view of statistical relationships that filters out the noise of general market drift.
Dual-Core: Toggle seamlessly between "Alpha Mode" (Log Returns) for verified stats and "Visual Mode" (Price) for trend alignment.
Calculation Modes: Pearson (Standard), Euclidean (Distance), Cosine (Vector), Manhattan (Grid).
2. Symmetric Compute Optimization Calculating a 15x15 matrix requires evaluating 225 unique relationships per bar, which often crashes memory limits.
The Fix: The V3 Engine utilizes Symmetric Logic, recognizing that Correlation(A, B) == Correlation(B, A).
The Gain: By computing only the lower triangle of the matrix and mirroring pointers to the upper triangle, we reduced computational load by 50%, ensuring a lightning-fast data feed even on lower timeframes.
3. Context-Aware "Ghost Mode" The UI is designed for professional traders who need focus, not clutter.
Smart Detection: The matrix automatically detects your current chart's Ticker ID. If you are trading QQQ, the matrix will visually highlight the Nas100 row and column, making them opaque and bright while dimming the rest.
Dynamic Transparency: Irrelevant data ("Noise" < 0.3 correlation) fades into the background. Only significant "Alpha Signals" (> 0.7) glow with full Neon Saturation.
Key Features
Dominant Flow Scanner: The matrix scans all 105 unique pairs every tick and prints the #1 Strongest Correlation at the bottom of the pane (e.g., DOMINANT FLOW: Bitcoin ↔ Nas100 ).
Streak Counter: A "Stubbornness" metric that tracks how many consecutive days a strong correlation has persisted. Instantly identify if a move is a "flash event" or a "structural trend."
Neon Palette: Proprietary color mapping using Electric Blue (+1.0) for lockstep correlation and Deep Red (-1.0) for inverse hedging.
Usage Guide
Placement: Best viewed in a bottom pane (Footer).
Assets: Pre-loaded with the Essential 15 Macro Drivers (Indices, BTC, Gold, Oil, Rates, FX, Key Sectors). Fully editable via settings (Ticker|Name).
Reading the Grid:
🔵 Bright Blue: Assets moving in lockstep (Risk-On).
🔴 Bright Red: Assets moving perfectly opposite (Hedge/Risk-Off).
⚫ Faded/Black: No statistical relationship (Decoupled).
Key Improvements Made:
Formatting: Added clear bullet points and bolding to make it scannable.
Clarity: Clarified the "Logarithmic Returns" section to explain why it matters (Velocity vs. Price Levels).
Tone: Maintained the "high-tech/quant" vibe but removed slightly clunky phrases like "spurious signals" (unless you prefer that academic tone, in which case I left it in as it fits the persona).
Structure: Grouped the "Modes" under the Math Engine for better logic.
Created and designed by QuantLabs
Diagonal Interest Zones ScannerThis indicator automatically scans and plots diagonal (slanted) interest zones – dynamic trend-parallel channels that identify statistically validated support/resistance levels within a trending price structure. It detects the strongest "bounce" zones where price has repeatedly respected slanted lines without breaking for a specified hold period, ideal for trending markets.
How It Works (Technical Methodology)
Trend Channel Detection
The script calculates a linear trend slope from a user-defined anchor point (start of lookback or fixed date) to the current close.
Range is determined by finding the maximum deviation above/below this trend line over the lookback period.
This creates a "channel envelope" capturing the full price oscillation around the trend.
Data can be sourced from current or higher timeframe for structural alignment.
Stable Update Mechanism
To prevent flickering on live bars:
Full recalculation (scanning + slope) occurs only after user-defined "Update Frequency" bars close (default 50).
All calculated values (slope, channel bottom, levels, scores) are "snapshotted" and frozen until next confirmed update.
Drawing uses these stable snapshots, ensuring zones remain fixed during real-time price movement.
Auto Mode Scanning
When enabled:
Scans the channel height in percentage steps (default 1.0%).
Each candidate creates a thin diagonal zone (thickness % of price, default 0.04%) parallel to the trend.
Counts valid "hits": Price touches zone and holds (no break) for user-defined bars (default 10).
Break source: "Close" (strict) or "Wick" (sensitive).
Direction assumed by close relative to zone center (support/resistance).
Level Selection and Filtering
Ranks by hit count, applies minimum distance (% of channel height) to avoid overlap.
Limits to max zones (default 9), sorted low to high.
Manual mode alternative: Directly uses input percentages (e.g., 0, 50, 100 for channel bottom/mid/top).
Diagonal Zone Construction
Zones are drawn as filled diagonal bands using two parallel lines (top/bottom) with linefill.
Thickness is volatility-adjusted (% of current price).
Optional extension far into future or limited projection.
Colors: Supply (above price, default light gray), Demand (below price, default cyan) – updates live but positions stay stable.
Dashboard and Visuals
Table shows current price at each zone (stable during bar), % level, hit count (green if high).
Update countdown displayed for transparency.
How to Use
Perfect for trending markets – identifies dynamic, parallel support/resistance zones that move with price structure.
High hit counts: Strong diagonal zones – expect bounces or acceleration on retest.
Update Frequency: Higher values (100+) for very stable long-term channels; lower for adaptive intraday.
Validation Bars: Increase for stricter zones (fewer false positives).
Multi-Timeframe: Use higher TF input for major trend channels on lower charts.
Supply Zones (Diagonal above price): Dynamic resistance – potential shorts or profit targets.
Demand Zones (Diagonal below price): Dynamic support – potential longs or trailing stops.
Manual Mode: Quick plotting of fixed % (e.g., channel median, quartiles).
Confluence: Combine with horizontal levels, volume, or order flow for entries.
Zones remain visually stable (no repainting during bar) thanks to snapshot logic – reliable for live trading decisions.
Disclaimer
This indicator is a technical analysis tool and should be used in conjunction with other forms of analysis. Past performance does not guarantee future results. Always use proper risk management.
CCI Standard DeviationCCI Standard Deviation – Asymmetric Volatility-Adjusted Trend Filter (CCI SD)
The Commodity Channel Index (CCI), created by Donald Lambert in 1980, measures how far the typical price deviates from its statistical average to identify cyclical momentum and trend strength.
The standard formula is:
CCI = (Typical Price − SMA(Typical Price, n)) / (0.015 × Mean Deviation)
where Typical Price = (High + Low + Close)/3.
CCI is unbounded and centered around zero: sustained readings above zero indicate bullish momentum, below zero bearish. Classic interpretations often use zero-line crosses or fixed levels (±100, ±200, ±250), but these can be unreliable when CCI volatility changes across market regimes.
This indicator was developed to create a more disciplined trend-following tool that aligns with my core risk principle: “always protect to the downside.”
Starting from the standard CCI zero-line concept for trend direction, I experimented with standard deviation bands to make the oscillator volatility-adjusted. I then applied deliberate asymmetry: requiring the lower 1σ envelope (CCI − stdev) to cross above a positive threshold for bullish confirmation (high-probability entry only in robust trends), while exiting immediately on any raw CCI weakness below a negative threshold (quick downside protection). User inputs for both thresholds were added to allow fine-tuning and adaptability across different assets and timeframes.
An optional DEMA-smoothed version of the lower envelope provides additional clarity when desired.
Extreme zones
raw CCI ±240 and lower envelope > 200 or < –200 - are highlighted with background shading to flag rare acceleration or capitulation phases.
How it works
Standard CCI calculated on typical price (default length 38).
Rolling standard deviation of the CCI itself (default length 13) measures the oscillator’s recent volatility.
Lower envelope = CCI − stdev (dn).
Optional DEMA smoothing (default length 12) can be toggled.
Trend logic:
Bullish regime only when lower envelope
→ Long Threshold (default +10)
→ statistical proof of strength
Bearish/neutral immediately when raw CCI
→ Short Threshold (default –25)
→ fast downside protection
Origin and development
The indicator emerged from wanting a cleaner, more reliable CCI for trend direction. After testing volatility-adjusted versions, the asymmetric design proved superior:
it enters only high-conviction uptrends and exits rapidly on weakness, significantly reducing whipsaws while preserving trend capture.
Parameters were optimized through extensive backtests on major assets (BTC, ETH, SOL and many more Cryptos; Magnificent 7 stocks, QQQ, SPX, gold).
The defaults were selected for the best average Sortino ratio and lowest maximum drawdown across this broad universe, ensuring robustness and avoiding single-asset overfitting.
How to use it
Green triangle below bar
→ lower envelope crosses above Long Threshold
→ high-conviction bullish trend confirmed
→ enter or add to longs
Magenta triangle above bar
→ CCI crosses below Short Threshold
→ exit longs or go cash/short
While lower envelope remains above Long Threshold
→ hold bullish positions
Extreme background shading (dn >200 or CCI ±240)
→ rare high-attention zones (potential acceleration or exhaustion)
Recommended defaults
CCI length: 38
SD length: 13
Long threshold: +10
Short threshold: –25
Optional MA length: 12 (DEMA of lower envelope)
All visual elements (bar coloring, signals, background, smoothed line) are toggleable for personal preference.
This indicator is designed as a trend-strength and risk-management filter and is not intended as a standalone trading system.
Disclaimer:
This is not financial advice. Backtests are based on past results and are not indicative of future performance.
SMC Post-Analysis Lab [PhenLabs]📊 SMC Post-Analysis Lab
Version: PineScript™ v6
📌 Description
The SMC Post-Analysis Lab is a dedicated hindsight analysis tool built for traders who want to understand what really happened during any historical trading period. Unlike forward-looking indicators, this tool lets you scroll back through time and instantly receive algorithmic classification of market states using Smart Money Concepts methodology.
Whether you’re reviewing a losing trade, studying a successful session, or building your pattern recognition skills, this indicator provides immediate context. The expansion-aware algorithm processes price action within your selected window and outputs clear, actionable classifications ranging from Parabolic Expansion to Consolidation Inducements.
Stop relying on subjective post-trade analysis. Let the algorithm objectively tell you whether institutional players were accumulating, distributing, or running inducements during your trades.
🚀 Points of Innovation
First indicator specifically designed for SMC-based post-trade review rather than live signal generation
Dual-mode analysis system allowing both dynamic scrollback and precise date selection
Expansion-aware classification algorithm that weighs range position against net displacement
Real-time efficiency metrics calculating directional quality of price movement
Integrated visual FVG detection within the analysis window only
Interactive table with clickable date range adjustment via chart interface
🔧 Core Components
Pivot Detection Engine: Uses configurable pivot length to identify significant swing highs and lows for structure break detection
Window Calculator: Determines active analysis zone based on either bar offset or timestamp boundaries
Data Aggregator: Tracks window open, high, low, close and counts bullish/bearish structure break events
State Classification Algorithm: Applies hierarchical logic to determine market state from six possible classifications
Visual Renderer: Draws structure breaks, FVG boxes, and window highlighting within the active zone
🔥 Key Features
Sliding Window Mode: Use the Scroll Back slider to dynamically move your analysis zone backwards through history bar-by-bar
Date Range Mode: Select specific start and end timestamps for precise session or trade review
Six Market State Classifications: Parabolic Expansion (Bull/Bear), Bullish/Bearish Order Flow, Accumulation/Distribution Reversal, and Consolidation/Inducement
Range Position Percentile: See exactly where price closed relative to the window’s high-low range as a percentage
Bull/Bear Event Counter: Quantified count of structure breaks in each direction during the analysis period
Efficiency Calculation: Net move divided by total range reveals trending quality versus chop
🎨 Visualization
Blue Window Highlight: Active analysis zone is clearly marked with blue background shading on the chart
Structure Break Lines: Dashed lines appear at each bullish or bearish structure break within the window
FVG Boxes: Fair Value Gaps automatically render as semi-transparent boxes in bullish or bearish colors
Dashboard Table: Top-right positioned table displays State, Analysis description, and Metrics in real-time
Color-Coded States: Each classification uses distinct coloring for immediate visual recognition
Interactive Tip Row: Optional help text guides users on clicking the table to adjust date range
📖 Usage Guidelines
General Configuration
Analysis Mode: Default is Sliding Window. Choose Date Range for specific timestamp analysis.
Sliding Window Settings
Scroll Back (Bars): Default 0. Increase to move window backwards into history.
Window Width (Bars): Default 100. Range 20-50 for scalping, 100+ for swing analysis.
Date Range Settings
Start Date: Select the beginning timestamp for your analysis period.
End Date: Select the ending timestamp for your analysis period.
Visual Settings
Show Help Tip: Default true. Toggle to hide instructional row in dashboard.
Bullish Color: Default teal. Customize for bullish elements.
Bearish Color: Default red. Customize for bearish elements.
SMC Parameters
Pivot Length: Default 5. Lower values (3-5) catch minor breaks. Higher values (10+) focus on major swings.
✅ Best Use Cases
Post-trade review to understand why entries succeeded or failed
Session analysis to identify institutional activity patterns
Trade journaling with objective algorithmic classifications
Pattern recognition training through historical scrollback
Identifying whether stop hunts were inducements or legitimate breaks
Comparing your real-time read versus what the algorithm detected
⚠️ Limitations
Designed for historical analysis only, not live trade signals
Classification accuracy depends on appropriate pivot length for the timeframe
FVG detection uses simple gap logic without mitigation tracking
State classification is based on window data only, not broader context
Requires manual scrolling or date input to review different periods
💡 What Makes This Unique
Purpose-Built for Review: Unlike most indicators focused on live signals, this is designed specifically for post-trade analysis
Expansion-Aware Logic: Algorithm weighs both position in range AND directional efficiency for accurate state detection
Interactive Date Control: Click the dashboard table to reveal draggable anchors for window adjustment directly on chart
🔬 How It Works
1. Window Definition:
User selects either Sliding Window or Date Range mode
System calculates which bars fall within the active analysis zone
Active zone receives blue background highlighting
2. Data Collection:
Algorithm captures window open, running high, running low, and current close
Structure breaks are detected when price crosses above last pivot high or below last pivot low
Bullish and bearish events are counted separately
3. State Classification:
Range Position calculates where close sits as percentage of high-low range
Efficiency calculates net move divided by total range
Hierarchical logic applies priority rules from Parabolic states down to Consolidation
4. Output Rendering:
Dashboard table updates with State title, Analysis description, and Metrics
Visual elements render within window only to keep chart clean
Colors reflect bullish, bearish, or neutral classification
💡 Note:
This indicator is intended for educational and review purposes. Use it to develop your understanding of Smart Money Concepts by analyzing what institutional order flow looked like during historical periods. Combine insights with your own analysis methodology for best results.
ETF-Futures Opening Ratio (Table)This indicator calculates the opening price ratio between an ETF and its corresponding futures contract using the 9:30 AM New York (RTH) opening price.
The ratio is locked at the official market open and remains fixed throughout the session, providing a stable reference for:
Translating ETF price levels into futures equivalents
Comparing relative value and premium/discount behavior
Maintaining consistent cross-instrument analysis during the trading day
The output is displayed in a simple on-chart table for quick reference and minimal chart clutter.
Account GuardianAccount Guardian: Dynamic Risk/Reward Overlay
Introduction
Account Guardian is an open-source indicator for TradingView designed to help traders evaluate trade setups before entering positions. It automatically calculates Risk-to-Reward ratios based on market structure, displays visual Stop Loss and Take Profit zones, and provides real-time position sizing recommendations.
The indicator addresses a fundamental question every trader should ask before entering a trade: "Does this setup make mathematical sense?" Account Guardian answers this question visually and numerically, helping traders avoid impulsive entries with poor risk profiles.
Core Functionality
Account Guardian performs four primary functions:
Detects swing highs and swing lows to identify logical stop loss placement levels
Calculates Risk-to-Reward ratios for both long and short setups in real-time
Displays visual SL/TP zones on the chart for immediate trade planning
Computes position sizing based on your account size and risk tolerance
The goal is to provide traders with instant feedback on whether a potential trade meets their minimum risk/reward criteria before committing capital.
How It Works
Swing Detection
The indicator uses pivot point detection to identify recent swing highs and swing lows on the chart. These swing points serve as logical areas for stop loss placement:
For Long Trades: The most recent swing low becomes the stop loss level. Price breaking below this level would invalidate the bullish thesis.
For Short Trades: The most recent swing high becomes the stop loss level. Price breaking above this level would invalidate the bearish thesis.
The swing detection lookback period is configurable, allowing you to adjust sensitivity based on your trading timeframe and style.
It automatically adjusts the tp and sl when it is applied to your chart so it is always moving up and down!
Risk/Reward Calculation
Once swing levels are identified, the indicator calculates:
Entry Price: Current close price (where you would enter)
Stop Loss: Recent swing low (for longs) or swing high (for shorts)
Risk: Distance from entry to stop loss
Take Profit: Entry plus (Risk × Target Multiplier)
R:R Ratio: Reward divided by Risk
The R:R ratio is then evaluated against your configured thresholds to determine if the setup is valid, marginal, or poor.
Visual Elements
SL/TP Zones
When enabled, the indicator draws colored boxes on the chart showing:
Red Zone: Stop Loss area - the region between your entry and stop loss
Green/Gold/Red Zone: Take Profit area - colored based on R:R quality
The color coding provides instant visual feedback:
Green: R:R meets or exceeds your "Good R:R" threshold (default 3:1)
Gold: R:R meets minimum threshold but below "Good" (between 2:1 and 3:1)
Red: R:R below minimum threshold - setup should be avoided
Swing Point Markers
Small circles mark detected swing points on the chart:
Green circles: Swing lows (potential support / long SL levels)
Red circles: Swing highs (potential resistance / short SL levels)
Dashboard Panel
The dashboard in the top-right corner displays comprehensive trade planning information:
R:R Row: Current Risk-to-Reward ratio for long and short setups
Status Row: VALID, OK, BAD, or N/A based on R:R thresholds
Stop Loss Row: Exact price level for stop loss placement
Take Profit Row: Exact price level for take profit placement
Pos Size Row: Recommended position size based on your risk parameters
Risk $ Row: Dollar amount at risk per trade
Position Sizing Logic
The indicator calculates position size using the formula:
Position Size = Risk Amount / Risk per Unit
Where:
Risk Amount = Account Size × (Risk Percentage / 100)
Risk per Unit = Entry Price - Stop Loss Price
For example, with a $10,000 account risking 1% per trade ($100), if your entry is at 100 and stop loss at 98 (risk of 2 per unit), your position size would be 50 units.
Input Parameters
Swing Detection:
Swing Lookback: Number of bars to look back for pivot detection (default: 10). Higher values find more significant swing points but may be slower to update.
Target Multiplier: Multiplier applied to risk to calculate take profit distance (default: 2). A value of 2 means TP is 2× the distance of SL from entry.
Risk/Reward Thresholds:
Minimum R:R: Minimum acceptable Risk-to-Reward ratio (default: 2.0). Setups below this show as "BAD" in red.
Good R:R: Threshold for excellent setups (default: 3.0). Setups at or above this show as "VALID" in green.
Account Settings:
Account Size ($): Your trading account size in dollars (default: 10,000). Used for position sizing calculations.
Risk Per Trade (%): Percentage of account to risk per trade (default: 1.0%). Professional traders typically risk 0.5-2% per trade.
Display:
Show SL/TP Zones: Toggle visibility of the colored zone boxes on chart (default: enabled)
Show Dashboard: Toggle visibility of the information panel (default: enabled)
Analyze Direction: Choose to analyze Long only, Short only, or Both directions (default: Both)
How to Use This Indicator
Basic Workflow:
Add the indicator to your chart
Configure your account size and risk percentage in the settings
Set your minimum and good R:R thresholds based on your trading rules
Look at the dashboard to see current R:R for potential long and short entries
Only consider trades where the status shows "VALID" or at minimum "OK"
Use the displayed SL and TP levels for your order placement
Use the position size recommendation to determine lot/contract size
Interpreting the Dashboard:
VALID (Green): Excellent setup - R:R meets your "Good" threshold. This is the ideal scenario for taking a trade.
OK (Gold): Acceptable setup - R:R meets minimum but isn't optimal. Consider taking if other confluence factors align.
BAD (Red): Poor setup - R:R below minimum threshold. Avoid this trade or wait for better entry.
N/A (Gray): Cannot calculate - usually means no valid swing point detected yet.
Best Practices:
Use this indicator as a filter, not a signal generator. It tells you IF a trade makes sense, not WHEN to enter.
Combine with your existing entry strategy - use Account Guardian to validate setups from other analysis.
Adjust the swing lookback based on your timeframe. Lower timeframes may need smaller lookback values.
Be honest with your account size input - accurate position sizing requires accurate inputs.
Consider the target multiplier carefully. Higher multipliers mean larger potential reward but lower probability of hitting TP.
Alerts
The indicator includes four alert conditions:
Good Long Setup: Triggers when long R:R reaches or exceeds your "Good R:R" threshold
Good Short Setup: Triggers when short R:R reaches or exceeds your "Good R:R" threshold
Bad Long Setup: Triggers when long R:R falls below your minimum threshold
Bad Short Setup: Triggers when short R:R falls below your minimum threshold
These alerts can help you monitor multiple charts and get notified when favorable setups appear.
Technical Implementation
The indicator is built using Pine Script v6 and includes:
Pivot-based swing detection using ta.pivothigh() and ta.pivotlow()
Dynamic box drawing for visual SL/TP zones
Table-based dashboard for clean information display
Color-coded visual feedback system
Persistent variable tracking for swing levels
Code Structure:
// Swing Detection
float swingHi = ta.pivothigh(high, swingLen, swingLen)
float swingLo = ta.pivotlow(low, swingLen, swingLen)
// R:R Calculation for Long
float longSL = recentSwingLo
float longRisk = entry - longSL
float longTP = entry + (longRisk * targetMult)
float longRR = (longTP - entry) / longRisk
// Position Sizing
float riskAmount = accountSize * (riskPct / 100)
float posSize = riskAmount / longRisk
Limitations
The indicator uses historical swing points which may not always represent optimal SL placement for your specific strategy
Position sizing assumes you can trade fractional units - adjust accordingly for instruments with minimum lot sizes
R:R calculations assume linear price movement and don't account for gaps or slippage
The indicator doesn't predict price direction - it only evaluates the mathematical viability of a setup
Swing detection has inherent lag due to the lookback period required for pivot confirmation
Recommended Settings by Trading Style
Scalping (1-5 minute charts):
Swing Lookback: 5-8
Target Multiplier: 1-2
Minimum R:R: 1.5
Good R:R: 2.0
Day Trading (15-60 minute charts):
Swing Lookback: 8-12
Target Multiplier: 2
Minimum R:R: 2.0
Good R:R: 3.0
Swing Trading (4H-Daily charts):
Swing Lookback: 10-20
Target Multiplier: 2-3
Minimum R:R: 2.5
Good R:R: 4.0
Why Risk/Reward Matters
Many traders focus solely on win rate, but profitability depends on the combination of win rate AND risk/reward ratio. Consider these scenarios:
50% win rate with 1:1 R:R = Breakeven (before costs)
50% win rate with 2:1 R:R = Profitable
40% win rate with 3:1 R:R = Profitable
60% win rate with 1:2 R:R = Losing money
Account Guardian helps ensure you only take trades where the math works in your favor, even if you're wrong more often than you're right.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not intended as financial, investment, trading, or any other type of advice or recommendation.
Trading involves substantial risk of loss and is not suitable for all investors. The calculations provided by this indicator are based on historical price data and mathematical formulas that may not accurately predict future price movements.
Position sizing recommendations are estimates based on user inputs and should be verified before placing actual trades. Always consider factors such as leverage, margin requirements, and broker-specific rules when determining actual position sizes.
The Risk-to-Reward ratios displayed are theoretical calculations based on swing point detection. Actual trade outcomes will vary based on market conditions, execution quality, and other factors not captured by this indicator.
Past performance does not guarantee future results. Users should thoroughly test any trading approach in a demo environment before risking real capital. The authors and publishers of this indicator are not responsible for any losses or damages arising from its use.
Always consult with a qualified financial advisor before making investment decisions.
Position Avg Line + P/L Table - SightLine LabsPosition Avg – SLL is a lightweight position-tracking indicator designed to display a persistent average price level on the chart along with a real-time position summary table.
This script is non-trading and does not generate signals, entries, or exits. It is intended strictly for position awareness and visual reference.
What this indicator does:
Plots a persistent horizontal average price line (dashed by default)
Displays a live position statistics table showing:
Shares owned
Average price
Current price
Unrealized profit/loss in dollars
Unrealized profit/loss in percent
Updates automatically as price changes
Works across all timeframes
Does not depend on broker integration or strategy logic
Key features:
Average Price Line:
User-defined average price input
Persistent across the entire chart
Adjustable color and width
Visibility toggle
Position Table:
Six selectable table positions:
Top Left, Top Center, Top Right, Bottom Left, Bottom Center, Bottom Right
Adjustable text size (Tiny through Huge)
Optional table background fill
Optional inner grid lines
Optional outer frame border
Independent color control for:
Header background
Header text
Value text
Positive and negative P/L values
Chart Overlay Options:
Optional chart background tint
Does not modify the global chart theme
Inputs overview:
Position Settings:
Shares Owned
Average Price
Visual Settings:
Show or hide average price line
Line color and width
Table Settings:
Table position
Table text size
Color Settings:
Header background and text colors
Value text color
Positive and negative P/L colors
Optional table background, grid, and frame colors
How to use:
Add the indicator to a chart
Open the settings panel
Enter the number of shares and the average price
Adjust table position, size, and colors as desired
Use the average price line and table as a visual reference for trade and risk management
Notes and limitations:
This indicator does not place trades
It does not connect to any broker
All values are manually entered
Unrealized P/L is calculated using the chart’s current price
Commissions, fees, and slippage are not included
Disclaimer:
This script is provided for educational and informational purposes only. It does not constitute financial advice, investment recommendations, or trade signals. All trading decisions are the sole responsibility of the user.
Developed by SightLine Labs.
Elite Net Cash by Mashrab🚀 Elite Net Cash Dashboard code by Mashrab
Stop switching tabs. Get the full fundamental picture instantly.
This dual-panel dashboard puts institutional-grade data right on your chart. It splits the "heavy math" from the "market context," giving you a clean, professional view of a company's true value and trading personality.
🔥 Why You’ll Love It
Two Smart Tables:
Financials: See the health check immediately—Net Cash, Cash Backed %, Free Cash Flow, and Revenue Growth.
Profile: Know who you are trading—Market Cap (with auto-class like "Mega" or "Small"), Volatility (ADR), and Sector.
Auto-ETF Mapping: It automatically tags the sector with its matching ETF (e.g., Technology (XLK)). Perfect for quickly checking relative strength!
Volatility Alerts: The ADR (Average Daily Range) turns Yellow if the stock moves more than 5% a day. Know the risk before you size your position.
Minimalist Mode: Want a clean chart? Uncheck the "Borders" box in settings for a sleek, text-only floating display.
🎯 How to Trade It
Check the Green: Look at the Financials table. Green numbers mean the company is cash-rich and growing.
Check the Moves: Look at the Profile table. High ADR means expect wild swings; Mega Cap means steady stability.
Check the Sector: Use the ETF tag to see if the whole industry is moving or just this stock.
⚙️ Make It Yours
Split the View: Put Financials top-right and Profile bottom-right (or anywhere else).
Style It: Toggle borders on/off and pick your colors.
Portfolio P&L Table 10 SlotsOverview
This indicator displays a compact, Excel-style position P&L table directly on your TradingView chart. It is designed to help traders track unrealized profit/loss for a manually-entered position and ensure the calculations only apply to the symbols you actually trade, preventing confusion when switching between tickers.
The script is symbol-aware: it checks the current chart symbol against up to 10 user-defined position slots and shows P&L only when a match is found.
Core Concept
Most P&L scripts on TradingView rely on a single set of inputs (average price, quantity), which remains active even when the user changes chart symbols. That can lead to incorrect P&L displays on instruments where no position exists.
This indicator solves that by combining:
Symbol matching logic (ticker / exchange:ticker / base ticker normalization)
Slot-based position storage (up to 10 positions)
Dynamic real-time P&L calculations driven by the chart’s live price
As a result, the table behaves like a “position panel” that follows the chart, while respecting your actual holdings list.
Matching & Display Logic
Symbol Detection
The indicator compares the current chart symbol to each slot’s symbol using multiple matching methods to reduce false mismatches:
Full symbol (EXCHANGE:TICKER)
Ticker only (TICKER)
Normalized “base ticker” extraction (useful when your chart format differs from inputs)
Position Selection
The first matching slot is selected and displayed.
If no slot matches, the table shows “No position for this symbol” and does not output P&L values.
P&L Calculation Logic
When a valid slot is matched and its values are valid:
Unrealized Gross P&L
Long: (Last Price − Avg Price) × Quantity
Short: (Avg Price − Last Price) × Quantity (handled via direction multiplier)
Unrealized Net P&L (optional)
If fees are enabled, the script subtracts the slot’s total fees from gross P&L.
P&L %
Calculated relative to average price, direction-adjusted for long/short positions.
Breakeven Price
Without fees: breakeven = average price
With fees: breakeven is adjusted using fees / quantity and direction.
The table updates automatically with market movement because all values are recalculated from the chart’s current price.
Inputs and Defaults
General
Include Fees? (default: Off)
Text Size
Table Position (Top/Bottom, Left/Right)
Slots (1 → 10)
Each slot contains:
Symbol (example formats: NVTS, NASDAQ:NVTS, NYSE:PATH)
Side (Long / Short)
Average Price
Quantity
Total Fees (optional; applied only when “Include Fees” is enabled)
Colors (Fully Customizable)
The table supports user-defined colors for:
Header text/background
Body text/background
Positive P&L color
Negative P&L color
Neutral/no-position color
This allows you to match the table visually to any chart theme.
The indicator is intended for :
Quick P&L visibility while charting
Avoiding accidental P&L “carry over” when switching symbols
Tracking a shortlist of positions without external spreadsheets
If you trade more than 10 tickers regularly, the script can be extended further using the same slot architecture.
Limitations
Values are unrealized and based on the chart’s price (close/last available feed).
The script does not track multiple lots per symbol automatically; each slot represents a single consolidated position (avg + total qty).
Disclaimer
This script is provided for educational and analytical purposes only. It does not constitute financial advice, investment recommendations, or an invitation to trade. Trading involves risk, and past performance does not guarantee future results. Always verify your position data and calculations independently before making trading decisions.
Xbirch_Turtle_ Crypto_CalcМодернизированная стратегия Черепах.
Вход/выход по каналу Дончиана, стопы по величине ATR, возможность выбора лонг/шорт/всё. Имеется пирамидинг - добавление по +0,5ATR от первого бая, не более 4х входов. Модернизированный стоп - по ATR от первого бая.
Не финансовый совет.
A modernized Turtle strategy.
Entry/exit based on the Donchian Channel, stops based on the ATR value, and the ability to choose long/short/all options. Pyramiding is available – adding +0.5 ATR from the first buy, with a maximum of four entries. The modernized stop is based on the ATR value from the first buy.
This is not financial advice.
Binance futures Funding Rate Sentiment ZonesHello,
This script is pretty much self explanatory.
Instead of having to have Binance open to check the Funding rate for futures USDT coins, it is shown in TradingView.
There are multiple colors that are shown:
-0.05% to 0.05% = neutral funding, no color on background
-+0.05% to -+0.1% = transition zone, long/short population increasing/decreasing
-+0.1% to -+ 2% = extreme positive / negative funding, red color
Daily candle separation + NY open + First hour open Daily candle separation + NY open + First hour open
Print Bar DataThis script print out the recent bar data. You can configure the position, bar numbers, of the data
Body Close Continuity & failure Backtesting @MaxMaseratiThis indicator, is a highly advanced institutional-grade tool designed to track the "lifespan" of a trend based on Body Close (BC) sequences.
Unlike basic indicators that just show direction, this script analyzes the structural integrity of a trend by monitoring how many candles continue the move before a "Touch" (retest) or a "Break" (failure) occurs.
The Continuity & Failure Stats indicator tracks sequences of Bullish Body Closes (BuBC) and Bearish Body Closes (BeBC). It measures three critical phases: Building (pure momentum), Touching (price retesting the low/high of the sequence), and Resumption (price continuing the trend after a retest). It provides a statistical distribution of how long these "buildings" typically last before failing, allowing traders to know exactly when a trend is overextended.
This comprehensive analysis blends the statistical breakdown of the Continuity & Failure Stats indicator to provide a deep understanding of the structural momentum for the S&P 500 E-mini (ES1!) on a 4-hour timeframe.
1. Extensive Table Breakdown
A. Building Distribution (Left Table): The Fatigue Gauge
This table acts as a histogram of momentum, tracking the "Building Count"—the number of consecutive candles closing in a trend without price returning to its origin.
Count Column: Represents the streak length (e.g., 1, 2, or 3 candles).
Touch Column: Shows how many times a streak was interrupted by a retest ("touch") but remained structurally intact.
Break Column: Counts total structural failures where price closed beyond the sequence's anchor.
Data Insight: For BuBC, 92 sequences reached Count 1, but only 28 remained by Count 4. This reveals a steep momentum decay after the 3rd candle, establishing a "Statistical Wall" where only 2 sequences in history reached a count of 9.
B. MMM Summary Stats (Top Right): The Mathematical DNA
This table provides the "Expected Value" and behavior of a trend over the lookback period.
Avg Building (2.39 for BuBC): On average, a bullish move lasts ~2.4 candles of pure momentum before a retest or reversal occurs.
Avg Touches (0.8): This low number indicates "clean" trends that rarely wobble back to retest levels multiple times before reaching a conclusion.
Avg R Cycles (0.55): This suggests that once a bullish trend is interrupted, it only successfully resumes its momentum about half the time.
Max R Count (1): Typically, once a trend is "touched," it only manages one more push before failing.
C. Multi-Timeframe (MTF) Quick Stats (Bottom Right): Trend Weight
This compares the 4H chart against other layers of the market to identify "global" alignment.
Sample Comparison: There are 3,594 tracked BuBC sequences on the 4H compared to only 142 on the Weekly chart.
Fractal Law: The Avg Building (2.4) is consistent across several timeframes, implying that the "Rule of Three" (momentum fading after 3 candles) is a fractal characteristic of this asset.
2. Table Comparison: Synthesizing the Data
To trade effectively, you must compare Distribution (timing) against Summary Stats (averages):
Continuity vs. Failure: The Summary Stats show an average building of 2.39. When checking the Distribution table at Count 2, the "Break" count (58) is already high relative to the "Total". This confirms that the risk of failure increases exponentially the moment you exceed the average.
Momentum vs. Mean Reversion: Distribution tells you when a trend is "tired". If the 4H is at a "Building Count 4" (statistically overextended) while the Weekly chart is at "Building Count 1" (fresh momentum), you may choose to prioritize the higher timeframe's strength despite the local overextension.
3. Strategic Summary & Application
This indicator proves that market momentum follows a predictable "Building" cycle rather than an infinite streak.
The "Rule of Three" for ES1! 4H:
The Entry Zone (Momentum Start): The most profitable entries occur at Building Count 1. Statistically, you have a high probability of reaching a count of 2 or 3.
The Exit Zone (Momentum Limit): Take profits or tighten stops at Count 3. The data shows the sample size drops by nearly 50% between Count 3 and Count 4.
The "Touch" Rule (Retest Reliability): If price returns to the sequence low (a "Touch"), do not expect a massive continuation. The Max R Count of 1 tells us that resumptions are usually short-lived.
Danger Zone: Entering at Building Count 4 or higher is statistically dangerous, as the "Break" probability significantly outweighs the "Touch" or continuation probability.
Session Opening Bar RangeSession Opening Bar Range (OBR) - Advanced Opening Range Indicator with Statistical Analysis
Overview
The Session First Bar Range (FBR) indicator is a comprehensive tool that captures and projects key levels based on the first bar of a user-defined trading session. Unlike traditional daily opening range indicators, this script allows traders to focus on specific session windows (New York RTH, London, Asia, etc.) and analyze price behavior relative to the initial momentum established in that session's opening bar.
What makes this indicator unique is its combination of three distinct projection methodologies: statistical analysis based on historical range data, Fibonacci extensions, and fixed-point rotation levels commonly used by institutional traders. To our knowledge, this is the only opening range indicator that incorporates statistical standard deviation levels calculated from historical first bar ranges, making it both a technical and probabilistic tool.
Core Concept
The opening range concept is based on the principle that the initial price action of a trading session often sets the tone for the remainder of that session.
Professional traders have long observed that:
The first bar's high and low act as key reference points
Price often respects or breaks these levels with significance
Expansion beyond the opening range tends to occur in measurable increments
This indicator takes these observations and enhances them with:
Historical probability analysis - "Based on the last 60 sessions, price typically extends X standard deviations beyond the opening range"
Proportional projections - Fibonacci-based extensions showing where measured moves typically target
Fixed-point rotations - Institutional rotation levels (e.g., 65 points for NQ, 15 points for ES)
How It Works
Session Detection & First Bar Capture
The indicator uses Pine Script's time() function with timezone support to precisely detect when a trading session begins. When the first bar of the selected timeframe occurs within the session window, the script captures:
High (H): The high of the first bar
Low (L): The low of the first bar
Mid (M): The midpoint (hl2) of the first bar
Critical Detail: These levels are fixed from the first bar only - they do not update as the session progresses. This differs from many "opening range" indicators that use a time period (e.g., first 30 minutes). Here, you select the bar timeframe (default 5-minute), and only that single first bar's range is captured.
Statistical Level Calculation
The indicator maintains a rolling array of the last N session's first bar ranges (default: 60 sessions). For each new session, it calculates:
Average Range: Mean of historical first bar ranges
Standard Deviation: Volatility of those ranges
Projection Levels: High/Low ± (Average Range + Std Dev × Multiplier)
This provides probability-based levels. For example, a +2σ level suggests: "Historically, price extending this far beyond the opening range is a 2-standard-deviation event (approximately 95th percentile)."
Fibonacci Extensions
Using the first bar range as the base unit (100%), the indicator projects Fibonacci levels:
100% extension: One full range above the high / below the low
1.618x extension: (Default) Golden ratio projection
2.618x, 3.618x extensions: Additional Fibonacci levels
Calculation: Range = H - L, then Target = H + (Range × Multiplier) for upside projections.
OR Rotation Levels
These are fixed-point increments from the first bar's high and low. Unlike percentage-based methods, rotations use absolute point values:
NQ traders often use 65-point increments
ES traders often use 15-point increments
Gold/bonds use different values
The indicator draws 5 levels above the high (R+1 through R+5) and 5 below the low (R-1 through R-5), each separated by your specified point increment.
Features:
Session Options
Pre-configured Sessions:
New York RTH (9:30am - 4:00pm)
New York Futures (8:00am - 5:00pm)
London (2:00am - 8:00am)
Asia (7:00pm - 2:00am)
Midnight to 5pm
ZB/Gold/Silver OR (8:20am - 4:00pm)
CL OR (9:00am - 4:00pm)
Custom Session: Define your own start/end times in HHMM format
Timezone Support: All sessions respect the selected timezone (default: America/New_York)
Customizable Timeframe
Select any timeframe for the first bar (1min, 5min, 15min, etc.)
Default: 5-minute bars
Important: This is the timeframe for the first bar capture, independent of your chart's timeframe
Display Options
Historical Ranges: Show/hide past session ranges (with configurable limit to manage performance)
Line Styles: Choose between Solid, Dashed, or Dotted for range lines and midline
Label Position: Left or Right side of range
Show Prices: Optionally display actual price values on labels
Custom Colors: Fully customizable colors for all components
Statistical Levels
Lookback Period: Number of historical sessions to analyze (default: 60)
Two Multiplier Levels: Default 1σ and 2σ, fully adjustable
Separate styling: Different line styles (dashed vs dotted) for each sigma level
Optional Labels: Show/hide sigma notation labels
Fibonacci Extensions
Four Extension Levels: 100%, 1.618x, 2.618x, 3.618x (all customizable)
Bidirectional: Projections both above and below the opening range
Optional Labels: Toggle percentage/multiplier labels
OR Rotation Levels
Configurable Increment: Set the point value for your instrument
Five Levels Each Direction: R±1 through R±5
Dynamic Labels: Show both rotation number and point value (e.g., "R+1 (65)")
Three Line Styles: Solid, Dashed, or Dotted
How to Use
Setup
Add the indicator to your chart
Select your trading session from the dropdown
Set the timeframe for first bar capture (typically 5-15 minutes)
Configure which projection methods you want to see (Statistical, Fibonacci, and/or Rotations)
For Day Traders
Scenario: Trading NQ during New York RTH
Session: Select "New York RTH (9:30am - 4:00pm)"
Timeframe: 5-minute (captures 9:30-9:35 bar)
Enable: OR Rotations with 65-point increments
Strategy:
Watch for acceptance/rejection at rotation levels
Use R+1/R-1 as initial profit targets
R+2/R-2 as extended targets
Statistical levels show when price is in "outlier" territory
and rotation levels
Performance Notes
The indicator limits objects to stay within TradingView's constraints (500 max)
If you enable all features, reduce "Maximum Historical Ranges" to prevent slowdown
Typical configuration: 10-20 historical ranges with all features enabled works well
Settings Guide
Session Settings
Session: Choose from pre-configured sessions or "Custom"
Custom Session Start/End: HHMM format (e.g., "0930" for 9:30am)
Timezone: Critical for accurate session detection
Opening Bar Format
Timeframe: The bar size for capturing the first bar's range
Show Midline: Toggle the mid-point line
Show Historical Ranges: Display previous sessions (recommended: leave ON)
Maximum Historical Ranges: Limit history to manage performance (1-500)
Range Style / MidLine Style: Solid, Dashed, or Dotted
Position: Label placement (Left or Right)
Show Prices: Include actual price values on labels
Statistical Levels
Lookback Periods: How many historical first bar ranges to analyze (default: 60)
Std Dev Multiplier 1/2: The sigma levels to project (default: 1.0 and 2.0)
All visual settings (colors, line width, label size)
Fibonacci Extensions
Show Fib Extensions: Enable/disable Fibonacci projections
Measured Move Extensions 1-4: The multipliers (default: 1.618, 2.618, 3.618, 4.618)
Visual customization options
OR Rotations
Rotation Increment: The point value for your instrument
NQ: 65 points
ES: 15 points
Adjust for other instruments based on their typical rotation behavior
Show Rotation Labels: Display level numbers and point values
Visual customization options
Use Cases
Gap Trading: When price gaps away from previous day's close, the first bar range shows the initial gap acceptance/rejection zone
Breakout Confirmation: Price breaking and holding above the first bar high with volume suggests trend day potential. Rotation levels provide measured targets.
Reversal Identification: Price reaching +2σ statistical level = rare event, potential exhaustion
Range Bound Days: Price oscillating between first bar high/low suggests range-bound session; trade reversals at extremes
Institutional Level Awareness: OR Rotations at 65 points (NQ) align with levels professional traders watch
Technical Notes
The indicator uses request.security() with lookahead=barmerge.lookahead_on to ensure the first bar levels are captured correctly
All drawing objects (lines, labels, fills) are managed in arrays with automatic cleanup to prevent memory issues
The statistical calculations use array.avg() and array.stdev() for accurate probability estimates
Rotation levels use individual line variables (like Fibonacci) rather than loops for reliability
Summary
This indicator is original in its combination of three distinct methodologies for projecting levels from a session's opening range:
Statistical Analysis - No other opening range indicator (to our knowledge) calculates standard deviation projections from historical first bar ranges
Time-Based Session Flexibility - Most OR indicators use only daily or fixed time periods; this allows any custom session window
Multiple Projection Methods - Traders can use statistical, Fibonacci, AND rotation levels together or separately
High/Low Tracker ARDR/ADR V4High and lows in 2 timeframes
16:00 -> 03:55
19:30 -> 02:55
Toggle on/off of
- Auto extending untill 09:25
- Live updating during price action
Configure linestyles, box styles
It is now displaying correctly for both CL and ES
Dynamic EMA Trend Table [Customizable]Overview
The Dynamic EMA Trend Table is a comprehensive dashboard designed to give traders an instant overview of the market trend across five distinct Exponential Moving Averages (EMAs). Instead of cluttering your chart with multiple lines, this script organizes the data into a clean, customizable table, allowing you to assess trend alignment at a glance.
How It Works
This indicator calculates five user-defined EMAs (defaulting to the popular 5, 20, 50, 100, and 200 periods). It then compares the Current Price against each EMA value to determine the immediate trend status:
Bullish State: When the current price is above the specific EMA, the table cell turns Green (customizable).
Bearish State: When the current price is below the specific EMA, the table cell turns Red (customizable).
This logic allows swing traders and scalpers to instantly see if the asset is in a strong uptrend (all cells Green), a strong downtrend (all cells Red), or a consolidation phase (mixed colors).
Key Features
Fully Customizable Periods: Change the length of all 5 EMAs to fit your specific strategy (e.g., Fibonacci numbers or standard Swing Trading settings).
Dynamic UI: Position the table anywhere on the screen (Top/Bottom/Left/Right) and adjust the size to fit your screen resolution.
Visual Cleanliness: You can choose to show the table only, or toggle the "Show EMAs on Chart" option to plot the actual lines on your chart.
Smart Coloring: The lines on the chart (if enabled) inherit the same color logic as the table—turning Green when price is above them and Red when price is below.
Settings & Configuration
Price Source: Select Close, High, Low, etc. (Default is Close).
Table Position & Size: Customize where the dashboard appears.
EMA Lengths: Set your 5 preferred lookback periods.
Color Theme: Fully adjustable colors for Bullish, Bearish, Neutral, and Background elements to match your chart theme (Dark/Light mode friendly).
Use Case Example
Trend Confirmation: A trader looking for a "Buy" entry might wait for the short-term EMAs (5 and 20) and the medium-term EMA (50) to all turn Green in the table before entering.
Support/Resistance Watch: By quickly glancing at the values in the table, you can see exactly where the 200 EMA sits without needing to scroll back on your chart to find the line.
Universal Moving Average🙏🏻 UMA (Universal Moving Average) represents the most natural and prolly ‘the’ final general universal entity for calculating rolling typical value for any type of time-series. Simply via different weighting schemes applied together, it encodes:
Location of each datapoint in corresponding fields (price, time, volume)
Informational relevance of each datapoint via using windowing functions that are fundamental in nature and go beyond DSP inventions & approximations
Innovation in state space (in our case = volatility)
The real beauty of this development: being simply a weighting scheme that can be applied to anything: be it weighted median , weighted quantile regression, or weighted KDE , or a simple weighted mean (like in this script). As long as a method accepts weights, you can harness the power of this entity. It means that final algorithmic complexity will match your initial tool.
As a moving ‘average’ it beats ALMA, KAMA, MAMA, VIDYA and all others because it is a simple and general entity, and all it does is encoding ‘all’ available information. I think that post might anger a lot of people, because lotta things will be realized as legacy and many paywalls gonna be ignored, specially for the followers of DSP cult, the ones who yet don’t understand that aggregated tick data is not a signal omg, it’s a completely different type of time series where your methods simply don’t fit even closely. I am also sorry to inform y’all, that spectral analysis is much closer to state-space methods in spirit than to DSP. But in fact DSP is cool and I love it, well for actual signals xD
...
Weights explained & how to use them: as I already said, the whole thing is based on combining different set of weights, and you can turn them on/off in script settings. Btw I've set em up defaults so you can use the thing on price data out of the box right away.
Price, Time, Volume weights: encode location of every datapoint in Price & TIme & Volume field
Howtouse: u have to disable one weight that corresponds to the field you apply UMA to. E.g if you apply UMA to prices, you turn off price weighting And turn on time and volume weighting. Or if you apply UMA to volume delta, you turn off volume weighting And turn on price and time weighting.
Higher prices are more important, this asymmetry is confirmed and even proved by the fact that prices can’t be negative (don’t even mention that incorrect rollover on CL contract in 2k20...).
Signal weights: encode actuality/importance/relevance of datapoints.
Howtouse: in DSP terms, it provides smoothing, but also compensates for the lag it introduces. This smoothness is useful if you use slope reversals for signal generation aka watching peaks and valleys in a moving average shape. It's also better to perturb smoothed outputs with this , this way you inject high freq content back, But in controlled way!
Signal = information.
The fundamental universal entity behind so-called “smoothing” in DSP has nothing to do with signals and goes eons beyond DSP. This is simply about measuring the relevance of data in time.
First, new datapoints need some time to be “embedded” into the timeline, you can think of it as time proof, kinda stuff needs time to be proved, accepted; while earliest datapoints lose relevance in time.
Second, along with the first notion, at the same time there’s the counter notion that simply weights new data more, acting as a counterweight from the down-weighting of the latest datapoints introduced by the first notion.
The first part can be represented as PDF of beta(2, 2) window (a set of weights in our case). It’s actually well known as the Welch window, that lives in between so called statistical and DSP worlds, emerges in multiple contexts. Mainstream DSP users tho mostly don’t use this one, they use primitive legacy windowing function, you can find all kinds on this wiki page.
Now the second part, where DSP adepts usually stop, is to introduce the second compensating windowing function. Instead they try to reduce window size, or introduce other kinds of volatility weights, do some tricks, but it ain’t provides obviously. The natural step here is to simply use the integral of the initial window; if the initial window is beta(2, 2) then what we simply need is CDF of beta(2, 2), in fact the vertically inverted shape of it aka survival function . That’s it bros. Simply as that.
When both of these are applied you have smth magical, your output becomes smooth and yet not lagging. No arbitrary windowing functions, tricks with data modification etc
Why beta(2, 2)? It naturally arises in many contexts, it’s based on one of the most fundamental functions in the universe: x^2. It has finite support. I can talk more bout it on request, but I am absolutely sure this is it.
^^ impulse response of the resulting weighs together (green) compared with uniform weights aka boxcar (red). Made with this script .
Weighing by state: encodes state-space innovation of each datapoint, basically magnitude of changes, strength of these changes, aka volatility.
Howtouse: this makes your moving average volatility aware in proper math ways. The influence of datapoints will be stronger when changes are stronger. This is weighting by innovations, or weighting by volatility by using squared returns.
Why squared returns? They encode state‑space innovations properly because the innovation of any continuous‑time semimartingale is about its quadratic variation, and quadratic variation is built from squared increments, not absolute increments.
Adaptive length is not the right way to introduce adaptivity by volatility xD. When you weight datapoints by squared returns you’re already dynamically varying ‘effective’ data size, you don’t need anything else.
...
It’s all good, progress happens, that’s how the Universe works, that's how Universal Moving Average works. Time to evolve. I might update other scripts with this complete weighting scheme, either by my own desire or your request.
...
∞
NeuralFlow Forecast Levels - User InputsThis is a companion indicator that plots AI-adaptive market equilibrium and expansion mapping levels directly on the SPY chart.
NeuralFlow Forecast Levels are generated through a Artificial Intelligence framework trained to identify:
Where price is statistically inclined to re-balance
Where expansion zones historically exhaust rather than extend
This is structure mapping, not prediction.
......................................................................................
What the Bands Represent?
AI Equilibrium (white core)
Primary weekly balance zone where price is most likely to mean-revert.
Predictive Rails (aqua / purple)
High-confidence corridor of institutional flow containment.
Outer Zones (green / red)
Expansion limits where continuation historically begins to decay.
Extreme Zones (top / bottom)
Rare deviation envelope where auction completion is statistically favored.
.The engine updates only when underlying structure changes —
not when candles fluctuate intraday.
.................................................................................................................
Usage Context
These levels are contextual reference zones, not entry signals. They are designed to answer:
Where does price matter?
Where does continuation weaken?
Where does balance statistically reassert itself?
Risk Disclaimer
Educational and analytical use only. Not financial advice.





















