HTF Ranges - AWR/AMR/AYR [bilal]📊 Overview
Professional higher timeframe range indicator for swing and position traders. Calculate Average Weekly Range (AWR), Average Monthly Range (AMR), and Average Yearly Range (AYR) with precision projection levels.
✨ Key Features
📅 Three Timeframe Modes
AWR (Average Weekly Range): Weekly swing targets - Default 4 weeks
AMR (Average Monthly Range): Monthly position targets - Default 6 months
AYR (Average Yearly Range): Yearly extremes - Default 9 years
🎯 Dual Anchor Options
Period Open: Week/Month/Year opening price
RTH Open: First RTH session (09:30 NY) of the period
📐 Projection Levels
100% Range Levels: Upper and lower targets from anchor
Fractional Levels: 33% and 66% zones for partial targets
Custom Mirrored Levels: Set any percentage (0-200%) with automatic mirroring
Example: 25% shows both 25% and 75%
Example: 150% shows both 150% and -50%
📊 Information Table
Active range type (AWR/AMR/AYR)
Average range value for selected period
Current period range and percentage used
Distance remaining to targets (up/down)
Color-coded progress (green/orange/red)
🎨 Fully Customizable
Orange theme by default (differentiates from daily indicators)
Line colors, styles (solid/dashed/dotted), and widths
Toggle labels on/off
Adjustable lookback periods for each timeframe
Independent settings for each range type
⚡ Smart Features
Lines start at actual period open (not fixed lookback)
Automatically tracks current period high/low
Works on any chart timeframe
Real-time range tracking
Alert conditions when targets reached or exceeded
🎯 Use Cases
AWR (Weekly Ranges):
Swing trade targets (3-7 day holds)
Weekly support/resistance zones
Identify weekly trend vs rotation
Compare daily moves to weekly context
AMR (Monthly Ranges):
Position trade targets (2-4 week holds)
Monthly breakout levels
Institutional-level zones
Earnings play targets
AYR (Yearly Ranges):
Major reversal zones
Long-term support/resistance
Identify macro trend strength
Annual high/low projections
💡 Trading Strategies
AWR Strategy (Swing Trading):
Week opens near AWR lower level = potential long setup
Target AWR 66% and 100% levels
Week hits AWR upper in first 2 days = watch for reversal
Use fractional levels as scale-in/scale-out points
AMR Strategy (Position Trading):
Month opens near AMR extremes = fade setup
Month breaks AMR in week 1 = expansion (trend) month
Target opposite AMR extreme for swing positions
Use 33%/66% for partial profit taking
AYR Strategy (Long-term Context):
Price near AYR extremes = major reversal zones
Breaking AYR levels = historic moves (rare)
Use for macro trend confirmation
Great for yearly forecasting and planning
📊 Range Interpretation
<33% Range Used: Early in period, room for expansion
33-66% Range Used: Normal progression
66-100% Range Used: Extended, approaching extremes
>100% Range Used: Expansion period - trending or high volatility
⚙️ Settings Guide
Lookback Periods:
AWR: 4 weeks (standard) - adjust to 8-12 for smoother average
AMR: 6 months (standard) - seasonal patterns
AYR: 9 years (standard) - captures full cycles
Anchor Type:
Period Open: Use for clean week/month/year open reference
RTH Open: Use if you only trade day session, ignores overnight gaps
Custom Levels:
25% = quartile targets
75% = three-quarter targets
80% = "danger zone" for reversals
111% = extended breakout target
🔄 Combine with ADR Indicator
Run both indicators together for complete multi-timeframe analysis:
ADR for intraday precision
AWR/AMR/AYR for swing/position context
See if today's ADR move is significant in weekly/monthly context
Multi-timeframe confluence = highest probability setups
💼 Ideal For
Swing Traders: Use AWR for 3-10 day holds
Position Traders: Use AMR for 2-8 week holds
Long-term Investors: Use AYR for macro context
Index Futures Traders: ES, NQ, YM, RTY
Multi-timeframe Analysis: Combine with daily ADR
Statistics
CEO Synapse v1.0CEO Synapse — Uyarlanabilir Rejim Stratejisi
This script is invite-only.
What Does This Strategy Do?
Markets are complex systems requiring various expertise. The "CEO Synapse" strategy adopts a "digital dashboard" approach based on the reality that a single viewpoint is insufficient. The strategy combines multiple analytical engines, each developed by me, analyzing different aspects of the market (structure, momentum, rhythm). It detects trend and momentum deviations in markets. A trading decision is made only when there is consensus among these expert engines. The "Synapse Engine" uses adaptive filtering and consensus logic for position management based on market regime (trend/range).
It eliminates the problem of traditional indicators generating misleading signals alone and failing to adapt to volatility and regime changes. Its dynamic threshold mechanism, adaptive periods, and special noise filters reduce unnecessary trades.
Original Methodology and Proprietary Logic: This algorithm does not rely on or copy any open source strategy code. The system uses commonly accepted indicators' mathematical principles such as ADX, EMA, SMA, ATR, True Range, etc., as data sources. The author's methodology combines dynamic period EMA, multi-filter consensus, adaptive threshold, and regime-based execution.
Though our strategy creates an original decision-making mechanism, it leverages foundational building blocks of technical analysis. The traditional indicators we use and their purposes are:
ADX (Average Directional Index): This indicator measures a trend’s strength, not its direction. Our strategy uses ADX as a filter to open positions only under sufficiently strong and distinct trend market conditions. This largely prevents misleading signals in weak or sideways markets.
Moving Averages (EMA and SMA): They form the backbone to determine the main trend direction. By smoothing price data, they reduce noise and reveal the market's general trend. But our strategy processes their outputs not as traditional crossover signals, but as input to an advanced consensus logic with dynamically adjusted periods based on market rhythm combined with other filters.
ATR (Average True Range): This indicator does not produce direct buy-sell signals but measures current market volatility. Especially in "Sideways Market" regime, take profit and stop loss levels are dynamically set based on ATR instead of fixed values, enabling risk management to adapt to market conditions.
Bollinger Band Logic (using Standard Deviation): Though the strategy does not plot Bollinger Bands directly, it uses Standard Deviation, the underlying mathematical concept, to detect excessive price deviations and volatility spikes, producing critical signals for the AMF PG core engine.
"Synapse Engine" consists of two layers: Decision Center (Dynamic Threshold) which automatically adjusts risk appetite based on performance and regime; and Filter Committee (Consensus Score) which weights separate filters to produce a single score. This combination is not reproducible and commercially valuable. Closed source is mandatory.
No classic open source code used. Only publicly available indicators are used. Parameters, order, and usage are fully customized.
Generated Signals: Trend/range entry/exit (long/short), adaptive trailing stop position management, additional risk control signals with Shock Absorber and Quantum Filter.
Purpose: Detect trend breaks and momentum deviations. Components: Volatility filters, adaptive signal weighting, EMA/SMA. Methodology: Combines price and volume change rates via dynamic weighting functions.
What Problem Does CEO Synapse Solve?
CEO Synapse addresses three main issues caused by traditional technical analysis and single indicator usage:
Problem: Misleading Signals and Market Noise
Traditional indicators (MACD, RSI, etc.) generate many "false" buy-sell signals, especially in sideways and choppy markets, causing traders to constantly enter and exit positions (whipsaw) and incur losses.
CEO Synapse Solution: The strategy never relies on a single signal. The Consensus-Based Decision Mechanism ensures no position is opened unless different analytical engines (structural, momentum, rhythm) agree. This "board of directors" approach filters market noise, processing only high-probability signals.
Problem: Static Analysis and Changing Market Conditions
Markets constantly change character; sometimes strong trend, sometimes narrow range. Most strategies try to function with fixed parameters across all conditions, leading to failure.
CEO Synapse Solution: The strategy has Adaptive Regime Switching. It actively analyzes whether the market is in "Trend Mode" or "Sideways Market Mode" and automatically adjusts entry/exit rules and risk management (take profit/stop loss) to the current regime, allowing chameleon-like adaptation to conditions.
Problem: Fixed Parameters and Declining Performance
Many traders believe they find the "best" settings and never change them for months or years. But as market volatility and cycles change, fixed settings lose effectiveness.
CEO Synapse Solution: The strategy operates on Full Adaptation principle.
Market Rhythm Adaptation: Dynamically adjusts analysis speed (e.g., EMA periods) according to market’s natural cycles.
Performance Adaptation: Continuously optimizes risk appetite (signal threshold) based on recent strategy performance, becoming bolder with gains and more cautious with losses.
In summary, CEO Synapse simplifies decision-making, eliminates market noise, and smartly adapts to changing market conditions, protecting the user from common mistakes.
Why "Invite-Only"?
Offering CEO Synapse as "Invite-Only" is a strategic decision to protect the strategy's commercial value and intellectual property and to provide users with the highest quality experience. Key reasons:
Protection of Proprietary IP:
CEO Synapse is the result of hundreds of hours of research, development, and testing. Its consensus logic, adaptive threshold mechanism, and engine integration are unique and patented. Open sourcing it would instantly destroy this trade secret and competitive edge.
Maintaining Performance Integrity and Effectiveness:
Uncontrolled distribution could lead to misuse or signal theft and sale by malicious actors. The invite-only model preserves the strategy’s integrity and ensures access only for serious investors.
Quality User Experience and Support:
Controlled distribution allows better user experience. High-quality documentation explaining features and best practices can be provided, and future updates and support services can be managed better for a limited user base.
Business Model:
CEO Synapse is positioned as a premium analysis tool. Invite-only access reflects its value and compensates the developer for ongoing maintenance, support, and future improvements.
Usage: Available on all timeframes.
Based entirely on my own adaptive filtering methodology.
Proprietary logic: The algorithm’s unique, non-reproducible logic and methodology. Example: Multi-filter consensus + adaptive threshold + regime-based execution.
Why Is This a Premium Tool?
"CEO Synapse"’s value stems from being a proprietary, integrated system beyond free standard indicators:
Advanced Noise Filtering: Not just reduces noise but adjusts filter sensitivity to current market character. Inspired by public mathematical concepts (cycle analysis, statistical filtering) but uniquely combined with proprietary weighting mechanisms and adaptive consensus logic forming the strategy's commercial value. Core indicators (EMA, ATR, ADX, DMI, etc.) are uniquely processed inside this proprietary system.
Full Adaptation: Instead of fixed parameters, the strategy continuously adapts to the market's natural rhythm, volatility, and past performance.
Consensus-Based Decision Making: Relies on collective intelligence of multiple analytical engines, not a single failure point.
These features substantially increase the ability to extract meaningful, actionable insights from raw market data, making it premium. It improves signal accuracy, reduces risk, and adapts to regime shifts. The dynamic threshold mechanism continuously adjusts risk appetite based on recent performance (profitability) and market regime.
By using this script, you agree not to redistribute, sell, or reverse engineer the source code.
This strategy is for educational purposes only. Past performance does not guarantee future results. Always apply proper risk management and protect your capital.
Risk Management: Maximum Drawdown Protection
The strategy includes a built-in capital protection mechanism. Users can specify the percentage drop from peak capital they tolerate. If the capital hits this drawdown limit, protection activates, closing all open positions and blocking new trades, acting as an emergency brake to guard capital against unexpected market conditions.
Automation Ready: Customizable Webhook Alerts
Fully Compatible Automation (JSON): The strategy outputs fully configurable JSON-formatted alert messages for buy, sell, and close actions. This allows connecting CEO Synapse signals to automation platforms like 3Commas and PineConnector for fully automated trading. Dynamic values like position size ({{strategy.order.contracts}}) are automatically included in alerts.
Strategy Backtest Information
Please remember past performance is not indicative of future results. The published chart and report are based on the BTCUSD pair in a 3-hour timeframe with the following settings:
Test Period: January 1, 2018 – November 3, 2025
Default Position Size: 15% of capital
Pyramiding: Off
Commission: 0.0008
Slippage: 2 ticks
Test Approach: The published test contains 201 trades and is statistically significant. Performing your own tests on different assets and timeframes is strongly recommended. Default settings are a template and should be adjusted per your analysis.
Advanced ICT ADR Projections [bilal]📊 Overview
Professional ADR indicator designed specifically for index futures traders. Calculate and visualize Average Daily Range with multiple session options, fractional levels, and higher timeframe context.
✨ Key Features
🎯 Multiple Session Types
Full Day: Standard calendar day calculation
Midnight: Anchored to 00:00 NY time open
RTH (Regular Trading Hours): 09:30-16:00 NY session
Custom: Define your own session hours and anchor point
📐 Projection Levels
100% ADR Levels: Upper and lower range targets from anchor
Fractional Levels: 33% and 66% zones for partial targets
Custom Mirrored Levels: Set any percentage (0-200%) with automatic mirroring
Example: 25% shows both 25% and 75%
Example: 111% shows both 111% and -11%
📅 Higher Timeframe Context (Optional)
AWR: Average Weekly Range overlay
AMR: Average Monthly Range overlay
AYR: Average Yearly Range overlay
All HTF ranges use same anchor as daily session
📊 Information Table
Current session type and anchor time
ADR value for selected period
Current range and percentage used
Distance remaining to ADR targets (up/down)
Color-coded range percentage (green/orange/red)
🎨 Fully Customizable
Line colors, styles (solid/dashed/dotted), and widths
Toggle labels on/off
Adjustable ADR lookback period (1-100 days)
All HTF periods customizable
⚡ Smart Features
Lines start at actual session open (not fixed lookback)
Works on any timeframe
Real-time range tracking
Alert conditions when ADR reached or exceeded
🎯 Use Cases
For Day Traders:
Set profit targets at ADR extremes
Identify range expansion vs rotation days
Know when you've used 75%+ of daily range (possible reversal)
Compare RTH vs full day ranges
For Swing Traders:
Use AWR/AMR for weekly/monthly targets
Understand if today's move is significant in weekly context
Multi-timeframe confluence
Risk Management:
Size positions based on % of ADR remaining
Avoid trading when ADR exhausted (>100%)
Better stop placement using fractional levels
💡 Trading Tips
<50% ADR used = Room to run (continuation trades)
50-75% ADR used = Getting extended (scale out)
75-100% ADR used = Near extremes (reversal setups)
>100% ADR = Expansion day (trend day or volatility spike)
Use fractional levels (33%, 66%) as:
Partial profit targets
Re-entry zones on pullbacks
Confluence with other support/resistance
Compare RTH vs Full Day ADR to see if overnight or day session drives volatility.
⚙️ Settings Guide
ADR Period: 5 days is standard, adjust for different market regimes
Session Types:
Use Midnight for crypto or 24hr markets
Use RTH for pure day session analysis
Use Custom for specific session times (London, Asia, etc.)
Custom Levels:
Set 25% for quartile levels
Set 111% for extended targets beyond ADR
Experiment with 50%, 75%, 80% for your strategy
Perfect for ES, NQ, YM, RTY futures traders who need precise intraday range analysis with higher timeframe context!
Fractal Dimension Index (FDI) by CoryP1990 – Quant ToolkitThe Fractal Dimension Index (FDI) quantifies how directional or choppy price movement is; in other words, it measures the “roughness” of a trend. FDI values near 1.0–1.3 indicate strong directional trends, while values near 1.5–2.0 reflect chaotic or range-bound behavior. This makes FDI a powerful tool for detecting trend vs. mean-reversion regimes.
How it works
Calculates the ratio of average price changes over full and half-length windows to estimate the fractal dimension of price movement.
Teal line = FDI decreasing → trending behavior (market smoother, more directional).
Orange line = FDI increasing → choppiness or consolidation.
Background:
Green tint = trend-friendly regime (FDI below low threshold).
Orange tint = choppy regime (FDI above high threshold).
Use cases
Detect when markets shift from trend-following to mean-reverting conditions.
Filter trades: favor trend strategies when FDI < 1.3 and reversion setups when FDI > 1.7.
Combine with momentum or volatility metrics to classify regimes.
Defaults
Length = 20
High-FDI threshold = 1.8
Low-FDI threshold = 1.2
Example — TSLA (1D, 2021)
Early 2021 trades choppy to sideways with FDI swinging up toward 1.5, then the index drops below 1.2 as Tesla transitions into a persistent trend-friendly regime through the second half of the year (green background). During the Q4 breakout, FDI holds ~1.0–1.2, confirming strong directionality; brief pullbacks lift FDI back toward the mid-range before trending pressure resumes. At the right edge, FDI sits well below the low threshold, signaling that price remains in a trend-supportive state.
Part of the Quant Toolkit — transparent, open-source indicators for modern quantitative analysis. Built by CoryP1990.
Intraday Intensity Percent (IIP) by CoryP1990 – Quant ToolkitThe Intraday Intensity Percent (IIP) quantifies buying vs. selling pressure within each bar by combining price position inside the range and trading volume. It’s essentially a volume-weighted order-flow indicator, showing whether volume concentrates near highs (buying pressure) or lows (selling pressure).
How it works
Computes the Intraday Intensity (II) = ((Close − Low) − (High − Close)) / (High − Low) × Volume.
Then compares total “intensity” to total volume over a look-back window to produce a normalized percentage.
Lime line: IIP rising → accumulation / increasing buy pressure.
Red line: IIP falling → distribution / increasing sell pressure.
Background: Green tint = heavy buying, Red tint = heavy selling.
Use cases
Identify accumulation or distribution phases early.
Confirm momentum with volume-backed pressure.
Detect divergences between price and volume flow.
Defaults
Length = 14
High-pressure threshold = +5 %
Low-pressure threshold = −5 %
Example — AAPL (2H)
Late July into early August shows sustained distribution as IIP sinks below −5% (deep red), marking heavy sell pressure during the drop. From early to mid-August, IIP flips positive and holds > +5% (green background), aligning with the rebound. After a brief mid-September shakeout, late Sep–mid Oct features renewed accumulation with repeated green surges. Most recently, IIP prints around −33%, indicating dominant selling pressure into the latest two-hour bars.
Part of the Quant Toolkit — transparent, open-source indicators for modern quantitative analysis. Built by CoryP1990.
ChainAggLib - library for aggregation of main chain tickersLibrary "ChainAggLib"
ChainAggLib — token -> main protocol coin (chain) and top-5 exchange tickers for volume aggregation.
Library only (no plots). All helpers are pure functions and do not modify globals.
norm_sym(s)
Parameters:
s (string)
get_base_from_symbol(full_symbol)
Parameters:
full_symbol (string)
get_chain_for_token(token_symbol)
Parameters:
token_symbol (string)
get_top5_exchange_tickers_for_chain(chain_code)
Parameters:
chain_code (string)
get_top5_exchange_tickers_for_token(token_symbol)
Parameters:
token_symbol (string)
join_tickers(arr)
Parameters:
arr (array)
contains_symbol(arr, symbol)
Parameters:
arr (array)
symbol (string)
contains_current(arr)
Parameters:
arr (array)
get_arr_for_current_token()
get_chain_for_current()
Yang-Zhang Volatility (YZVol) by CoryP1990 – Quant ToolkitThe Yang-Zhang Volatility (YZVol) estimator measures realized volatility using both overnight gaps and intraday moves. It combines three components: overnight returns, open-to-close returns, and the Rogers–Satchell term, weighted by Zhang’s k to reduce bias.
How to read it
Line color: Green when YZVol is rising (volatility expansion), Red when falling (volatility compression).
Background: Green tint = above High-vol threshold (active regime). Red tint = below Low-vol threshold (quiet regime).
Units: Displays Daily % by default on any timeframe (values are normalized to daily). An optional toggle shows Annualized % (√252 × Daily %).
Typical uses
Spot transitions between quiet and active regimes.
Compare realized vol vs implied vol or a risk-target.
Adapt position sizing to volatility clustering.
Defaults
Length = 20
High-vol threshold = 5% (Daily)
Low-vol threshold = 1% (Daily)
Optional: Annualized % display
Example — SPY (1D)
During the 2020 crash, YZVol surged to 5.8 % per day, capturing the height of pandemic-era volatility before compressing into a calm regime through 2021. Volatility re-expanded in 2022 due to reinflamed COVID fears and gradually stabilized through 2023. A sharp, liquidity-driven volatility event in August 2024 caused another brief YZVol surge, reflecting the historic one-day VIX spike triggered by market-wide risk-off flows and thin pre-market liquidity. A second, policy-driven expansion followed in April–May 2025, coinciding with the renewed U.S.–China tariff conflict and a sharp equity pullback. Since mid-2025, YZVol has settled near 1 % per day, with the red background confirming that realized volatility has once again compressed into a quiet, low-risk regime.
Part of the Quant Toolkit — transparent, open-source indicators for modern quantitative analysis. Built by CoryP1990.
Slick Strategy Weekly PCS TesterInspired by the book “The Slick Strategy: A Unique Profitable Options Trading Method.” This indicator tests weekly SPX put-credit spreads set below Monday’s open and judged at Friday’s close.
WHAT IT DOES
• Sets weekly PCS level = Monday (or first trading day) OPEN − your offset; win/loss checked at Friday close.
• Optional core filter at entry: Price ≥ 200-SMA AND 10-SMA ≥ 20-SMA; pause if Price < both 10 & 20 while > 200.
• Reference modes: Strict = Mon OPEN vs Fri SMAs (no repaint); Mid = Mon OPEN vs Mon SMAs
KEY INPUTS
• Date range (Start/End) to limit backtest window.
• Offset mode/value (Points or Percent).
• Entry day (Monday only or first trading day).
• Core filters (On/Off) and Strict/Mid reference.
• SMA settings (source; 10/20/200 lengths).
• Table settings (position, size, padding, border).
VISUALS
• Active week line: Orange = trade taken; Gray = skipped.
• History: Green = win; Red = loss; Purple = skipped.
• Optional week bands highlight active/win/loss/skipped weeks (adjustable opacity).
TABLE
• Shows Date range, Trades, Wins, Losses, Win rate, and Active level (this week’s PCS price).
NOTES
• PCS level freezes at week open and persists through the week.
TRADE ORBIT:- TREND REVERSAL INDICATORThis indicator combines EMA momentum, Stochastic oscillator behavior, and trend-strength histogram analysis to identify when the market is trending, weakening, or potentially reversing.
✅ Main Components
EMA Difference
Calculates strength as the difference between a fast EMA and slow EMA
Positive → Uptrend
Negative → Downtrend
Stochastics (%K & %D)
Identifies overbought (>80) / oversold (<20) conditions
Signals crossovers:
%K crosses above %D → bullish
%K crosses below %D → bearish
Trend Strength Histogram
Shows the momentum change in color + height:
Condition Color Meaning
Uptrend strength increasing Strong Green Strong buying pressure
Uptrend strength weakening Light Green Buying losing momentum
Downtrend strength increasing Strong Red Strong selling pressure
Downtrend strength weakening Light Red Selling losing momentum
Divergence Yellow Trend may reverse
Divergence Detection
Bullish weakening >80 → Yellow
Uptrend losing strength → risk of reversal
Bearish weakening <20 → Yellow
Downtrend losing strength → risk of reversal
Buy/Sell Signals
Buy: Stoch %K cross above %D below 20
Sell: Stoch %K cross below %D above 80
✅ How to Use
Trade in direction of histogram strength
Exit / reduce position when yellow appears → possible reversal
Confirm with Stoch cross + EMA direction
✅ Best Use Cases
Trend continuation and fade detection
Early reversal warning
Overbought/oversold decision zones
Ulcer Index (UI) by CoryP1990 – Quant ToolkitThe Ulcer Index measures downside volatility, i.e. how deep and persistent drawdowns are from recent highs. Unlike standard deviation, which treats upside and downside equally, the Ulcer Index focuses purely on pain . It’s a favorite of risk-adjusted performance metrics like the Martin Ratio.
How it works
Computes the RMS (root-mean-square) of drawdowns over a look-back window.
Rising UI → drawdowns worsening (stress increasing).
Falling UI → drawdowns shrinking (recovery phase).
Red line = Ulcer Index rising.
Lime line = Ulcer Index falling.
Red background = High-risk regime (above threshold).
Green background = Low-risk regime (below threshold).
Use cases
Gauge portfolio stress levels and timing of recovery phases.
Identify “calm vs storm” periods for position sizing.
Combine with volatility or sentiment measures for regime classification.
Defaults
Length = 14
High-risk threshold = 10
Low-risk threshold = 5
Example — NVIDIA (NVDA, 1D)
During the sharp decline through 2022, the Ulcer Index repeatedly spiked above 10 while the background turned red, highlighting an extended high-stress drawdown phase. As NVDA began recovering in early 2023, the UI line switched to lime and drifted below 5, marking a transition into a low-risk regime. Throughout 2024–2025, the index stayed mostly sub-5 with brief red pulses on minor corrections, which is clear evidence that downside volatility has remained contained during the broader uptrend.
Part of the Quant Toolkit - a series of transparent, open-source indicators designed for professional-grade analytics and education. Built by CoryP1990.
korea time with 200 korea time
start time
08
09
17
18
23
00
This script makes it easier to look at the charts
The time automatically displays even if you don't bother to bring the mouse by hand
Now you can see the time intuitively
Run a very happy trading session
HIPA - High IRL Probability Areas [Pro]Overview
HIPA (High IRL Probability Areas) visualizes statistically derived Internal Range Liquidity (IRL) zones — price areas that have historically shown a higher tendency for revisit or interaction within an intraday session.
When a candle breaks a higher-timeframe reference bar’s high or low, HIPA plots a draw line at the opposite extreme of that bar, highlighting where liquidity is most likely to rest.
Each line displays a live, time-conditioned probability (CH) of being revisited before session end, plus an optional End-of-Day (EOD) probability.
HIPA provides statistical context on how current price interacts with prior structural ranges. It does not issue trade signals or forecasts.
Key Features
• Tracks higher-timeframe reference bars across the session.
• Plots draw lines at the opposite extreme once a break occurs.
• Displays dynamic CH and optional EOD probabilities derived from embedded historical statistics.
• Tested lines change style once price interacts; expired levels are automatically removed.
• Fully customizable palette, text size, and visibility options.
Signal Area Context
HIPA includes an optional Signal Area overlay that blends IRL probabilities with higher-timeframe (HTF) structure.
You can reference candle highs/lows or pivots from selected HTF intervals and display a subtle gradient between these external liquidity points and active IRL zones.
The shaded area is intended to help visualize where intraday behavior aligns with multi-timeframe liquidity zones — not to produce entries or exits.
Traders may use it to study how price develops around these confluence regions.
Methodology (transparency)
HIPA uses embedded statistical references derived from long-term historical market behavior to estimate revisit probabilities conditioned by time-of-day and break direction.
These references are stored directly within the script for deterministic plotting — no external data is fetched or required.
Session data is internally organized into consistent time segments to reflect how revisit tendencies vary through the day.
HIPA is descriptive: it visualizes empirically observed behavior, not predictive outcomes.
How to Use
- Apply HIPA to any intraday chart.
- Observe when price breaks a higher-timeframe candle’s high or low — a draw line appears at the opposite extreme with CH/EOD labels.
- Optionally enable the Signal Area to visualize overlap between HTF liquidity and current IRL zones.
- Use HIPA as structural and statistical context only; combine with your own framework for decision-making.
- Treat draw lines and gradients as reference areas rather than precise trade levels.
Notes
• Historical behavior can evolve under different market conditions.
• CH/EOD probabilities adjust with session time; interpret contextually.
• Rendering many lines simultaneously may affect performance — enable pruning if needed.
• Works on any symbol or timeframe supported by TradingView.
Disclaimers
Educational use only. Past performance does not guarantee future results.
HIPA visualizes statistical context based on historical behavior and does not predict or recommend trades.
ATR Position SizerFound the substack from Ryan Wright (raen prop trading) which has amazing insights into the real prop trading world.
In his post Your Trading Edge Isn't Your Setup . It's Your Knowledge he shared a few interesting nuggets of knowledge.
Especially the part about Risk according to the 20-day ATR caught my eye, so i reconstructed a version of that formula directly for Tradingview. It works with ES (MES), NQ (MNQ), GC (MGC), YM and can be extended.
Additionally I implemented a function that tracks the chart ATR (automatically on the chosen time frame) on a defined period. This can of course be disable.
Hope it helps
India Vix based Strangle StrikesA clean Nifty–VIX dashboard that converts India VIX into expected daily moves, price ranges, and suggested strangle strikes. Includes VIX %, expanded 1.2× range, and smart rounded strike levels for options trading.
This script provides a professional on-chart dashboard that converts India VIX into actionable trading levels for Nifty. It calculates the VIX-based expected daily move, projected price ranges, expanded 1.2× ranges, and suggested strangle strike prices. Includes clean formatting, color-coded sections, and real-time updates.
Ideal for traders using straddles, strangles, intraday volatility models, range-bound setups, and options-based risk management.
1.2x expanded range is better success probability, may keep 20% of strangle value as stop loss.
The vix based system is intended to give approx. 70%+ success rate.
JiNFOJiNFO is a clean, data-driven overlay that displays key information about the current symbol directly on your chart — without clutter.
🧭 What it shows
Company & Symbol Info – Name, ticker, sector, industry, market cap
Timeframe Label – Current chart timeframe (auto-formatted)
ATR (14) & % Volatility – With color dots for low 🟢 / medium 🟡 / high 🔴 volatility
Moving Average Status – Indicates if price is above or below the selected MA (default 150)
RSI & RSI-SMA (14) – Compact line with live values and color dot for overbought/neutral/oversold zones
Distance from SMA (50) – Shows how far price is from the 50 MA (+/- %) and grades it A–D by distance 🟢🟠🔴
Earnings Countdown – Days remaining until the next earnings date (if available)
⚙️ Customization
Position (top/middle/bottom, left/center/right)
Text size (default Small), color, opacity (100 %)
Toggle any data row on or off
Choose compact or verbose labels
🧩 Purpose
JiNFO replaces bulky data panels with a lightweight, transparent information layer — perfect for traders who want essential fundamentals, volatility, and technical context at a glance.
Custom Horizontal Lines | Trade Symmetry📊 Custom Horizontal Lines
🔍 Overview
The Custom Horizontal Lines is a precision utility designed for traders who perform manual higher-timeframe analysis and want to preserve their marked price levels directly on the chart.
It doesn’t calculate or detect anything automatically — instead, it acts as your personal level memory, preserving your analyzed zones and reference prices throughout the session.
Ideal for traders who manually mark the High, Low, Open, Close, Mean Thresholds, and Quarter Levels of Order Blocks, Fair Value Gaps, Inversion Fair Value Gaps and Wicks before the trading day begins.
⚙️ Key Features
✅ Manual Level Entry — Input your analyzed price levels (OB, FVG, WICK,etc) directly into the indicator settings.
✅ Preserved Levels — Once entered, your lines stay visible and consistent — even after switching symbols, timeframes, or reloading the chart.
✅ Supports All Level Types — Store any kind of manually defined level: OB highs/lows, FVG boundaries, Wicks, Mean Thresholds, Quarter levels, or custom reference prices.
✅ Clean Visualization — Customize line color, style, and labels for easy visual organization.
✅ Session-Ready Workflow — Built for pre-market preparation — enter your HTF levels once, and trade around them all day.
✅ No Auto Calculations — 100% manual by design — ensuring only your analyzed levels are shown, exactly as you defined them.
💡 How to Use
Open the indicator’s settings and manually enter those price values.
The indicator will plot and preserve those exact levels on your chart.
Switch to your lower timeframe and observe how price reacts around them — without ever needing to redraw.
🎯 Why It’s Useful
Keeps your HTF levels organized and persistent across sessions.
Saves time by avoiding redrawing.
Fits perfectly into ICT / Smart Money trading workflows.
Ensures full manual control and precision over what’s displayed on your chart.
🧩 Ideal For
ICT and Smart Money traders
Institutional-style manual analysts
Traders marking Mean Thresholds, or Quarter Levels of OBs, FVGs, Wicks etc
Anyone who wants a clean, reliable way to preserve their manual analysis
NSE Pairs Screener-20 pair This advanced Pine Script screener is designed for pairs trading on the National Stock Exchange (NSE) of India. It simultaneously monitors up to 20 stock pairs, calculates key statistical metrics, and provides real-time trading signals based on mean reversion strategies.
Key Features
1. Multi-Pair Analysis
Monitor up to 20 stock pairs simultaneously
Customizable number of pairs to display (1-20)
Pre-configured with popular NSE stock pairs across various sectors
2. Statistical Calculations
Correlation Analysis: Measures the strength of relationship between paired stocks
Z-Score Calculation: Identifies extreme deviations from the mean spread
Cointegration Score: Validates long-term equilibrium relationships
Dynamic Hedge Ratio: Calculates optimal position sizing between pairs
3. Trading Signals
Long Signal: When spread is oversold (Z-score ≤ -2.0)
Short Signal: When spread is overbought (Z-score ≥ 2.0)
Exit Signal: When spread returns to mean (Z-score ≤ 0.5)
Watch Status: Pairs requiring monitoring
4. Automated Alert System
Single comprehensive alert for all qualifying pairs
Customizable alert thresholds for correlation, Z-score, and cointegration
On-chart visual alerts with detailed information
Notification support via TradingView's alert system
5. Visual Display
Clean, color-coded table interface
Adjustable table position (9 positions available)
Highlighted trading opportunities
Real-time metric updates
Configuration Parameters
Screener Settings
Number of Pairs to Display: 1-20 pairs (default: 20)
Calculation Parameters
Parameter Default Range Description Correlation Lookback Period25220-500Historical period for correlation calculation Z-Score SMA Length205-100Moving average length for spread calculation Hedge Ratio Length205-100Period for hedge ratio smoothing Minimum Correlation0.70.5-1.0Threshold for pair validation
Alert Settings
Parameter Default Range Description Alert Correlation Threshold0.70.5-1.0Minimum correlation for alerts Alert Z-Score Threshold2.01.0-3.0Z-score trigger level Alert Cointegration Threshold90%80-99%Minimum cointegration percentage
Display Settings
Table Position: 9 position options (default: middle_center)
Table Background Color: Customizable
Highlight Opportunities: Toggle visual highlighting of trading signals
Pre-Configured Stock Pairs
The script includes 20 carefully selected NSE pairs across various sectors:
Financial Services
RELIANCE / ONGC
HDFCBANK / ICICIBANK
SBIN / PNB
KOTAKBANK / AXISBANK
BAJFINANCE / BAJAJFINSV
Information Technology
TCS / INFY
WIPRO / HCLTECH
TECHM / LTIM
Consumer Goods
ITC / HINDUNILVR
TITAN / TANLA
ASIANPAINT / BERGEPAINT
Telecommunications
BHARTIARTL / IDEA
Automotive
MARUTI / TATAMOTORS
Infrastructure & Industrials
LT / UBL
POWERGRID / NTPC
Pharmaceuticals
SUNPHARMA / CIPLA
DIVISLAB / DRREDDY
Materials
ULTRACEMCO / ACC
UPL / JSWSTEEL
Energy
ADANIENT / ADANIPOWER
🎨 Color-Coded Metrics
Correlation
🟢 Green: ≥ Minimum threshold (strong relationship)
🔴 Red: < Minimum threshold (weak relationship)
Z-Score
🔴 Red: |Z| ≥ 2.0 (extreme deviation - trading opportunity)
🟡 Yellow: 0.5 < |Z| < 2.0 (normal range - watch)
🟢 Green: |Z| ≤ 0.5 (mean reversion - exit signal)
Cointegration
🟢 Green: ≥ 70% (strong cointegration)
🟡 Yellow: 50-70% (moderate cointegration)
🔴 Red: < 50% (weak cointegration)
Status
🟢 Green: Long (buy spread)
🔴 Red: Short (sell spread)
🔵 Blue: Exit (close positions)
⚪ Gray: Watch (monitor)
Validation
🟢 Green: Pass (meets all criteria)
🔴 Red: Fail (doesn't meet criteria)
How It Works
1. Data Collection
The script fetches real-time closing prices for all 20 stock pairs from NSE.
2. Statistical Analysis
For each pair, the script calculates:
Log Returns: Natural logarithm of price changes
Correlation: Pearson correlation coefficient between returns
Hedge Ratio: Price ratio smoothed over specified period
Spread: Price difference adjusted by hedge ratio
Z-Score: Standardized spread deviation
3. Signal Generation
Based on Z-score thresholds:
Z ≥ 2.0: Short spread (short overvalued, long undervalued)
Z ≤ -2.0: Long spread (long overvalued, short undervalued)
|Z| ≤ 0.5: Exit positions (spread reverted to mean)
4. Validation
Pairs must meet criteria:
Correlation ≥ minimum threshold
Valid trading signal (entry or exit)
5. Alert Triggering
Alerts fire when pairs simultaneously meet:
Correlation ≥ alert threshold
|Z-score| ≥ alert threshold
Cointegration ≥ alert threshold
Alert System
The script features a single comprehensive alert that monitors all pairs:
Consolidated Notifications: One alert for all qualifying pairs
Detailed Information: Includes pair names, signal type, and key metrics
Visual Indicators: Red label on chart with complete details
Customizable Thresholds: Adjust sensitivity based on trading style
Alert Message Format
PAIR TRADING OPPORTUNITIES
Pair X: STOCK1/STOCK2
Signal: LONG/SHORT Spread
Z-Score: X.XX
Correlation: X.XXX
Cointegration: XX.X%
Trading Strategy Guide
Entry Rules
Long Spread (Z-score ≤ -2.0):
Buy Stock Y
Sell Stock X (in ratio of hedge ratio)
Short Spread (Z-score ≥ 2.0):
Sell Stock Y
Buy Stock X (in ratio of hedge ratio)
Exit Rules
Close positions when Z-score returns to ±0.5
Set stop-loss at Z-score ±3.0 (extreme deviations)
Risk Management
Only trade pairs with correlation ≥ 0.7
Prefer cointegration scores ≥ 90%
Monitor hedge ratio changes
Diversify across multiple pairs
Customization Options
Adding New Pairs
Simply modify the stock symbol inputs in the respective pair groups (Pair 1 through Pair 20).
Adjusting Sensitivity
Conservative: Increase Z-score threshold to 2.5-3.0
Aggressive: Decrease Z-score threshold to 1.5-2.0
Long-term: Increase lookback period to 500
Short-term: Decrease lookback period to 50-100
Visual Preferences
Change table position to suit your layout
Adjust background colors for better contrast
Toggle opportunity highlighting on/off
Technical Notes
Calculation Method
Uses logarithmic returns for correlation (better statistical properties)
Z-score normalized by standard deviation
Cointegration approximated using correlation strength
Hedge ratio smoothed using simple moving average
Performance Considerations
Calculations update on every bar close
Table displays only on the last bar
Alert checks occur at bar close
Maximum 500 labels supported (more than sufficient)
Limitations
Does not account for transaction costs
Assumes linear relationships between pairs
Historical correlation doesn't guarantee future behaviour
Requires sufficient liquidity in both stocks
Best Practices
Back test Thoroughly: Test parameters on historical data before live trading
Monitor Regularly: Check pairs daily for validation changes
Diversify: Trade multiple pairs to reduce risk
Stay Informed: Be aware of corporate actions, news affecting pairs
Adjust Parameters: Optimize for current market conditions
Use Stop-Losses: Protect against extreme divergences
Track Performance: Maintain trading journal for continuous improvement
Indicator Information
Version: Pine Script v5
Overlay: False (separate pane)
Max Labels: 500
Update Frequency: Every bar close
Compatible Timeframes: All (works best on daily or higher)
Getting Started
Add to Chart: Apply indicator to any NSE stock
Configure Pairs: Adjust stock symbols as needed
Set Parameters: Customize calculation and alert settings
Create Alert: Set up Trading View alert for notifications
Monitor: Watch the table for trading opportunities
Execute: Trade based on validated signals
📞Support & Updates
This script is designed for educational and research purposes. Always:
Conduct thorough back testing
Use proper risk management
Consider transaction costs
Consult with financial advisors
Trade responsibly
Disclaimer: This indicator is for educational purposes only. Past performance does not guarantee future results. Always conduct your own research and risk assessment before trading.
Time & Sales , Volume Delta and CVD, Volume imbalance , Tick
This Pine Script (version 6) creates a comprehensive TradingView indicator combining Time & Sales (Tape) with Volume Delta, Order Flow Pressure Indicator (OFPI), Volume Imbalance detection, Volume Delta (VD) histogram, Cumulative Volume Delta (CVD), TICK.US histogram, and a summary gauge table. It overlays on the chart with customizable tables, boxes, lines, and labels for real-time trade analysis, momentum, imbalances, and volume metrics.
Key Features and Components:
Time & Sales Table: A dynamic table showing recent trades (up to user-defined rows). Columns include Time, Side (▲/▼), Last Price, Volume (or Price-Weighted Volume). Trades below a volume threshold are hidden. Includes a buy/sell scale bar with percentages. Supports timeframe-based or live tick data fetching.
OFPI with Gauge: Calculates net aggressive volume pressure using bar body position, smoothed with T3 moving average. Displays a centered gauge bar (e.g., "░░░|███░░") indicating bullish/bearish momentum or shifts.
Volume Imbalance (VI): Detects bullish/bearish gaps between bars. Draws semi-transparent boxes with labels (e.g., "5 tks (vi)") for imbalances or gaps. Limits display to a max number, removes filled ones, and uses magnets (🧲) for gaps.
Volume Delta (VD): Approximates buy/sell delta via intrabar pressure or polarity. Displays as unipolar/bipolar histogram, optionally overlapping with regular volume or TICK.US. Shows numerical values (green/red/orange for divergences) and price/VD divergences.
Cumulative Volume Delta (CVD): Cumulates VD, reset on anchor timeframe (e.g., daily). Displays as line, area, baseline, or candles. Includes optional EMA smoothing and background fills. Detects divergences with price.
TICK.US Histogram: Overlays US Tick index (from symbol "TICK.US") as positive/negative bars during US market hours (9:30-16:00 ET, Mon-Fri). Replaces regular volume in some modes.
Gauge Summary Table: Bottom-left table with momentum text, OFPI gauge, CVD value, current Tick, and last bar's volume breakdown (total/buy/sell/delta).
Customization Options:
General: Timezone, date format, table position/size, colors (gradients for up/down), calculation mode (timeframe/live tick), volume type (volume/price-volume), thresholds, lengths (e.g., lookback, smoothing).
Display: Heights/offsets for histograms, line widths/styles, transparencies, label sizes/alignments, divergences, MA on volume, CVD smoothing/background.
Technical: Lower timeframe precision (auto or custom), anchor for CVD reset, max VIs to show.
Other: Toggles for VI, TICK.US, numerical values, divergences.
Credit
// FuturesCall @ fcalgobot.com
//Time & Sales (Tape)
// CVD base on Luxalgo CVD indicator
// Momentum Gauge by DskyzInvestments
// volume imbalance by ...
Manifold Singularity EngineManifold Singularity Engine: Catastrophe Theory Detection Through Multi-Dimensional Topology Analysis
The Manifold Singularity Engine applies catastrophe theory from mathematical topology to multi-dimensional price space analysis, identifying potential reversal conditions by measuring manifold curvature, topological complexity, and fractal regime states. Unlike traditional reversal indicators that rely on price pattern recognition or momentum oscillators, this system reconstructs the underlying geometric surface (manifold) that price evolves upon and detects points where this topology undergoes catastrophic folding—mathematical singularities that correspond to forced directional changes in price dynamics.
The indicator combines three analytical frameworks: phase space reconstruction that embeds price data into a multi-dimensional coordinate system, catastrophe detection that measures when this embedded manifold reaches critical curvature thresholds indicating topology breaks, and Hurst exponent calculation that classifies the current fractal regime to adaptively weight detection sensitivity. This creates a geometry-based reversal detection system with visual feedback showing topology state, manifold distortion fields, and directional probability projections.
What Makes This Approach Different
Phase Space Embedding Construction
The core analytical method reconstructs price evolution as movement through a three-dimensional coordinate system rather than analyzing price as a one-dimensional time series. The system calculates normalized embedding coordinates: X = normalize(price_velocity, window) , Y = normalize(momentum_acceleration, window) , and Z = normalize(volume_weighted_returns, window) . These coordinates create a trajectory through phase space where price movement traces a path across a geometric surface—the market manifold.
This embedding approach differs fundamentally from traditional technical analysis by treating price not as a sequential data stream but as a dynamical system evolving on a curved surface in multi-dimensional space. The trajectory's geometric properties (curvature, complexity, folding) contain information about impending directional changes that single-dimension analysis cannot capture. When this manifold undergoes rapid topological deformation, price must respond with directional change—this is the mathematical basis for catastrophe detection.
Statistical normalization using z-score transformation (subtracting mean, dividing by standard deviation over a rolling window) ensures the coordinate system remains scale-invariant across different instruments and volatility regimes, allowing identical detection logic to function on forex, crypto, stocks, or indices without recalibration.
Catastrophe Score Calculation
The catastrophe detection formula implements a composite anomaly measurement combining multiple topology metrics: Catastrophe_Score = 0.45×Curvature_Percentile + 0.25×Complexity_Ratio + 0.20×Condition_Percentile + 0.10×Gradient_Percentile . Each component measures a distinct aspect of manifold distortion:
Curvature (κ) is computed using the discrete Laplacian operator: κ = √ , which measures how sharply the manifold surface bends at the current point. High curvature values indicate the surface is folding or developing a sharp corner—geometric precursors to catastrophic topology breaks. The Laplacian measures second derivatives (rate of change of rate of change), capturing acceleration in the trajectory's path through phase space.
Topological Complexity counts sign changes in the curvature field over the embedding window, measuring how chaotically the manifold twists and oscillates. A smooth, stable surface produces low complexity; a highly contorted, unstable surface produces high complexity. This metric detects when the geometric structure becomes informationally dense with multiple local extrema, suggesting an imminent topology simplification event (catastrophe).
Condition Number measures the Jacobian matrix's sensitivity: Condition = |Trace| / |Determinant|, where the Jacobian describes how small changes in price produce changes in the embedding coordinates. High condition numbers indicate numerical instability—points where the coordinate transformation becomes ill-conditioned, suggesting the manifold mapping is approaching a singularity.
Each metric is converted to percentile rank within a rolling window, then combined using weighted sum. The percentile transformation creates adaptive thresholds that automatically adjust to each instrument's characteristic topology without manual recalibration. The resulting 0-100% catastrophe score represents the current bar's position in the distribution of historical manifold distortion—values above the threshold (default 65%) indicate statistically extreme topology states where reversals become geometrically probable.
This multi-metric ensemble approach prevents false signals from isolated anomalies: all four geometric features must simultaneously indicate distortion for a high catastrophe score, ensuring only true manifold breaks trigger detection.
Hurst Exponent Regime Classification
The Hurst exponent calculation implements rescaled range (R/S) analysis to measure the fractal dimension of price returns: H = log(R/S) / log(n) , where R is the range of cumulative deviations from mean and S is the standard deviation. The resulting value classifies market behavior into three fractal regimes:
Trending Regime (H > 0.55) : Persistent price movement where future changes are positively correlated with past changes. The manifold exhibits directional momentum with smooth topology evolution. In this regime, catastrophe signals receive 1.2× confidence multiplier because manifold breaks in trending conditions produce high-magnitude directional changes.
Mean-Reverting Regime (H < 0.45) : Anti-persistent price movement where future changes tend to oppose past changes. The manifold exhibits oscillatory topology with frequent small-scale distortions. Catastrophe signals receive 0.8× confidence multiplier because reversal significance is diminished in choppy conditions where the manifold constantly folds at minor scales.
Random Walk Regime (H ≈ 0.50) : No statistical correlation in returns. The manifold evolution is geometrically neutral with moderate topology stability. Standard 1.0× confidence multiplier applies.
This adaptive weighting system solves a critical problem in reversal detection: the same geometric catastrophe has different trading implications depending on the fractal regime. A manifold fold in a strong trend suggests a significant reversal opportunity; the same fold in mean-reversion suggests a minor oscillation. The Hurst-based regime filter ensures detection sensitivity automatically adjusts to market character without requiring trader intervention.
The implementation uses logarithmic price returns rather than raw prices to ensure
stationarity, and applies the calculation over a configurable window (default 5 bars) to balance responsiveness with statistical validity. The Hurst value is then smoothed using exponential moving average to reduce noise while maintaining regime transition detection.
Multi-Layer Confirmation Architecture
The system implements five independent confirmation filters that must simultaneously validate
before any singularity signal generates:
1. Catastrophe Threshold : The composite anomaly score must exceed the configured threshold (default 0.65 on 0-1 scale), ensuring the manifold distortion is statistically extreme relative to recent history.
2. Pivot Structure Confirmation : Traditional swing high/low patterns (using ta.pivothigh and ta.pivotlow with configurable lookback) must form at the catastrophe bar. This ensures the geometric singularity coincides with observable price structure rather than occurring mid-swing where interpretation is ambiguous.
3. Swing Size Validation : The pivot magnitude must exceed a minimum threshold measured in ATR units (default 1.5× Average True Range). This filter prevents signals on insignificant price jiggles that lack meaningful reversal potential, ensuring only substantial swings with adequate risk/reward ratios generate signals.
4. Volume Confirmation : Current volume must exceed 1.3× the 20-period moving average, confirming genuine market participation rather than low-liquidity price noise. Manifold catastrophes without volume support often represent false topology breaks that don't translate to sustained directional change.
5. Regime Validity : The market must be classified as either trending (ADX > configured threshold, default 30) or volatile (ATR expansion > configured threshold, default 40% above 30-bar average), and must NOT be in choppy/ranging state. This critical filter prevents trading during geometrically unfavorable conditions where edge deteriorates.
All five conditions must evaluate true simultaneously for a signal to generate. This conjunction-based logic (AND not OR) dramatically reduces false positives while preserving true reversal detection. The architecture recognizes that geometric catastrophes occur frequently in noisy data, but only those catastrophes that align with confirming evidence across price structure, participation, and regime characteristics represent tradable opportunities.
A cooldown mechanism (default 8 bars between signals) prevents signal clustering at extended pivot zones where the manifold may undergo multiple small catastrophes during a single reversal process.
Direction Classification System
Unlike binary bull/bear systems, the indicator implements a voting mechanism combining four
directional indicators to classify each catastrophe:
Pivot Vote : +1 if pivot low, -1 if pivot high, 0 otherwise
Trend Vote : Based on slow frequency (55-period EMA) slope—+1 if rising, -1 if falling, 0 if flat
Flow Vote : Based on Y-gradient (momentum acceleration)—+1 if positive, -1 if negative, 0 if neutral
Mid-Band Vote : Based on price position relative to medium frequency (21-period EMA)—+1 if above, -1 if below, 0 if at
The total vote sum classifies the singularity: ≥2 votes = Bullish , ≤-2 votes = Bearish , -1 to +1 votes = Neutral (skip) . This majority-consensus approach ensures directional classification requires alignment across multiple timeframes and analysis dimensions rather than relying on a single indicator. Neutral signals (mixed voting) are displayed but should not be traded, as they represent geometric catastrophes without clear directional resolution.
Core Calculation Methodology
Embedding Coordinate Generation
Three normalized phase space coordinates are constructed from price data:
X-Dimension (Velocity Space):
price_velocity = close - close
X = (price_velocity - mean) / stdev over hurstWindow
Y-Dimension (Acceleration Space):
momentum = close - close
momentum_accel = momentum - momentum
Y = (momentum_accel - mean) / stdev over hurstWindow
Z-Dimension (Volume-Weighted Space):
vol_normalized = (volume - mean) / stdev over embedLength
roc = (close - close ) / close
Z = (roc × vol_normalized - mean) / stdev over hurstWindow
These coordinates define a point in 3D phase space for each bar. The trajectory connecting these points is the reconstructed manifold.
Gradient Field Calculation
First derivatives measure local manifold slope:
dX/dt = X - X
dY/dt = Y - Y
Gradient_Magnitude = √
The gradient direction indicates where the manifold is "pushing" price. Positive Y-gradient suggests upward topological pressure; negative Y-gradient suggests downward pressure.
Curvature Tensor Components
Second derivatives measure manifold bending using discrete Laplacian:
Laplacian_X = X - 2×X + X
Laplacian_Y = Y - 2×Y + Y
Laplacian_Magnitude = √
This is then normalized:
Curvature_Normalized = (Laplacian_Magnitude - mean) / stdev over embedLength
High normalized curvature (>1.5) indicates sharp manifold folding.
Complexity Accumulation
Sign changes in curvature field are counted:
Sign_Flip = 1 if sign(Curvature ) ≠ sign(Curvature ), else 0
Topological_Complexity = sum(Sign_Flip) over embedLength window
This measures oscillation frequency in the geometry. Complexity >5 indicates chaotic topology.
Condition Number Stability Analysis
Jacobian matrix sensitivity is approximated:
dX/dp = dX/dt / (price_change + epsilon)
dY/dp = dY/dt / (price_change + epsilon)
Jacobian_Determinant = (dX/dt × dY/dp) - (dX/dp × dY/dt)
Jacobian_Trace = dX/dt + dY/dp
Condition_Number = |Trace| / (|Determinant| + epsilon)
High condition numbers indicate numerical instability near singularities.
Catastrophe Score Assembly
Each metric is converted to percentile rank over embedLength window, then combined:
Curvature_Percentile = percentrank(abs(Curvature_Normalized), embedLength)
Gradient_Percentile = percentrank(Gradient_Magnitude, embedLength)
Condition_Percentile = percentrank(abs(Condition_Z_Score), embedLength)
Complexity_Ratio = clamp(Topological_Complexity / embedLength, 0, 1)
Final score:
Raw_Anomaly = 0.45×Curvature_P + 0.25×Complexity_R + 0.20×Condition_P + 0.10×Gradient_P
Catastrophe_Score = Raw_Anomaly × Hurst_Multiplier
Values are clamped to range.
Hurst Exponent Calculation
Rescaled range analysis on log returns:
Calculate log returns: r = log(close) - log(close )
Compute cumulative deviations from mean
Find range: R = max(cumulative_dev) - min(cumulative_dev)
Calculate standard deviation: S = stdev(r, hurstWindow)
Compute R/S ratio
Hurst = log(R/S) / log(hurstWindow)
Clamp to and smooth with 5-period EMA
Regime Classification Logic
Volatility Regime:
ATR_MA = SMA(ATR(14), 30)
Vol_Expansion = ATR / ATR_MA
Is_Volatile = Vol_Expansion > (1.0 + minVolExpansion)
Trend Regime (Corrected ADX):
Calculate directional movement (DM+, DM-)
Smooth with Wilder's RMA(14)
Compute DI+ and DI- as percentages
Calculate DX = |DI+ - DI-| / (DI+ + DI-) × 100
ADX = RMA(DX, 14)
Is_Trending = ADX > (trendStrength × 100)
Chop Detection:
Is_Chopping = NOT Is_Trending AND NOT Is_Volatile
Regime Validity:
Regime_Valid = (Is_Trending OR Is_Volatile) AND NOT Is_Chopping
Signal Generation Logic
For each bar:
Check if catastrophe score > topologyStrength threshold
Verify regime is valid
Confirm Hurst alignment (trending or mean-reverting with pivot)
Validate pivot quality (price extended outside spectral bands then re-entered)
Confirm volume/volatility participation
Check cooldown period has elapsed
If all true: compute directional vote
If vote ≥2: Bullish Singularity
If vote ≤-2: Bearish Singularity
If -1 to +1: Neutral (display but skip)
All conditions must be true for signal generation.
Visual System Architecture
Spectral Decomposition Layers
Three harmonic frequency bands visualize entropy state:
Layer 1 (Surface Frequency):
Center: EMA(8)
Width: ±0.3 × 0.5 × ATR
Transparency: 75% (most visible)
Represents fast oscillations
Layer 2 (Mid Frequency):
Center: EMA(21)
Width: ±0.5 × 0.5 × ATR
Transparency: 85%
Represents medium cycles
Layer 3 (Deep Frequency):
Center: EMA(55)
Width: ±0.7 × 0.5 × ATR
Transparency: 92% (most transparent)
Represents slow baseline
Convergence of layers indicates low entropy (stable topology). Divergence indicates high entropy (catastrophe building). This decomposition reveals how different frequency components of price movement interact—when all three align, the manifold is in equilibrium; when they separate, topology is unstable.
Energy Radiance Fields
Concentric boxes emanate from each singularity bar:
For each singularity, 5 layers are generated:
Layer n: bar_index ± (n × 1.5 bars), close ± (n × 0.4 × ATR)
Transparency gradient: inner 75% → outer 95%
Color matches signal direction
These fields visualize the "energy well" of the catastrophe—wider fields indicate stronger topology distortion. The exponential expansion creates a natural radiance effect.
Singularity Node Geometry
N-sided polygon (default hexagon) at each signal bar:
Vertices calculated using polar coordinates
Rotation angle: bar_index × 0.1 (creates animation)
Radius: ATR × singularity_strength × 2
Connects vertices with colored lines
The rotating geometric primitive marks the exact catastrophe bar with visual prominence.
Gradient Flow Field
Directional arrows display manifold slope:
Spawns every 3 bars when gradient_magnitude > 0.1
Symbol: "↗" if dY/dt > 0.1, "↘" if dY/dt < -0.1, "→" if neutral
Color: Bull/bear/neutral based on direction
Density limited to flowDensity parameter
Arrows cluster when gradient is strong, creating intuitive topology visualization.
Probability Projection Cones
Forward trajectory from each singularity:
Projects 10 bars forward
Direction based on vote classification
Center line: close + (direction × ATR × 3)
Uncertainty width: ATR × singularity_strength × 2
Dashed boundaries, solid center
These are mathematical projections based on current gradient, not price targets. They visualize expected manifold evolution if topology continues current trajectory.
Dashboard Metrics Explanation
The real-time control panel displays six core metrics plus regime status:
H (Hurst Exponent):
Value: Current Hurst (0-1 scale)
Label: TREND (>0.55), REVERT (<0.45), or RANDOM (0.45-0.55)
Icon: Direction arrow based on regime
Purpose: Shows fractal character—only trade when favorable
Σ (Catastrophe Score):
Value: Current composite anomaly (0-100%)
Bar gauge shows relative strength
Icon: ◆ if above threshold, ○ if below
Purpose: Primary signal strength indicator
κ (Curvature):
Value: Normalized Laplacian magnitude
Direction arrow shows sign
Color codes severity (green<0.8, yellow<1.5, red≥1.5)
Purpose: Shows manifold bending intensity
⟳ (Topology Complexity):
Value: Count of sign flips in curvature
Icon: ◆ if >3, ○ otherwise
Color codes chaos level
Purpose: Indicates geometric instability
V (Volatility Expansion):
Value: ATR expansion percentage above 30-bar average
Icon: ● if volatile, ○ otherwise
Purpose: Confirms energy present for reversal
T (Trend Strength):
Value: ADX reading (0-100)
Icon: ● if trending, ○ otherwise
Purpose: Shows directional bias strength
R (Regime):
Label: EXPLOSIVE / TREND / VOLATILE / CHOP / NEUTRAL
Icon: ✓ if valid, ✗ if invalid
Purpose: Go/no-go filter for trading
STATE (Bottom Display):
Shows: "◆ BULL SINGULARITY" (green), "◆ BEAR SINGULARITY" (red), "◆ WEAK/NEUTRAL" (orange), or "— Monitoring —" (gray)
Purpose: Current signal status at a glance
How to Use This Indicator
Initial Setup and Configuration
Apply the indicator to your chart with default settings as a starting point. The default parameters (21-bar embedding, 5-bar Hurst window, 2.5σ singularity threshold, 0.65 topology confirmation) are optimized for balanced detection across most instruments and timeframes. For very fast markets (scalping crypto, 1-5min charts), consider reducing embedding depth to 13-15 bars and Hurst window to 3 bars for more responsive detection. For slower markets (swing trading stocks, 4H-Daily charts), increase embedding depth to 34-55 bars and Hurst window to 8-10 bars for more stable topology measurement.
Enable the dashboard (top right recommended) to monitor real-time metrics. The control panel is your primary decision interface—glancing at the dashboard should instantly communicate whether conditions favor trading and what the current topology state is. Position and size the dashboard to remain visible but not obscure price action.
Enable regime filtering (strongly recommended) to prevent trading during choppy/ranging conditions where geometric edge deteriorates. This single setting can dramatically improve overall performance by eliminating low-probability environments.
Reading Dashboard Metrics for Trade Readiness
Before considering any trade, verify the dashboard shows favorable conditions:
Hurst (H) Check:
The Hurst Exponent reading is your first filter. Only consider trades when H > 0.50 . Ideal conditions show H > 0.60 with "TREND" label—this indicates persistent directional price movement where manifold catastrophes produce significant reversals. When H < 0.45 (REVERT label), the market is mean-reverting and catastrophes represent minor oscillations rather than substantial pivots. Do not trade in mean-reverting regimes unless you're explicitly using range-bound strategies (which this indicator is not optimized for). When H ≈ 0.50 (RANDOM label), edge is neutral—acceptable but not ideal.
Catastrophe (Σ) Monitoring:
Watch the Σ percentage build over time. Readings consistently below 50% indicate stable topology with no imminent reversals. When Σ rises above 60-65%, manifold distortion is approaching critical levels. Signals only fire when Σ exceeds the configured threshold (default 65%), so this metric pre-warns you of potential upcoming catastrophes. High-conviction setups show Σ > 75%.
Regime (R) Validation:
The regime classification must read TREND, VOLATILE, or EXPLOSIVE—never trade when it reads CHOP or NEUTRAL. The checkmark (✓) must be present in the regime cell for trading conditions to be valid. If you see an X (✗), skip all signals until regime improves. This filter alone eliminates most losing trades by avoiding geometrically unfavorable environments.
Combined High-Conviction Profile:
The strongest trading opportunities show simultaneously:
H > 0.60 (strong trending regime)
Σ > 75% (extreme topology distortion)
R = EXPLOSIVE or TREND with ✓
κ (Curvature) > 1.5 (sharp manifold fold)
⟳ (Complexity) > 4 (chaotic geometry)
V (Volatility) showing elevated ATR expansion
When all metrics align in this configuration, the manifold is undergoing severe distortion in a favorable fractal regime—these represent maximum-conviction reversal opportunities.
Signal Interpretation and Entry Logic
Bullish Singularity (▲ Green Triangle Below Bar):
This marker appears when the system detects a manifold catastrophe at a price low with bullish directional consensus. All five confirmation filters have aligned: topology score exceeded threshold, pivot low structure formed, swing size was significant, volume/volatility confirmed participation, and regime was valid. The green color indicates the directional vote totaled +2 or higher (majority bullish).
Trading Approach: Consider long entry on the bar immediately following the signal (bar after the triangle). The singularity bar itself is where the geometric catastrophe occurred—entering after allows you to see if price confirms the reversal. Place stop loss below the singularity bar's low (with buffer of 0.5-1.0 ATR for volatility). Initial target can be the previous swing high, or use the probability cone projection as a guide (though not a guarantee). Monitor the dashboard STATE—if it flips to "◆ BEAR SINGULARITY" or Hurst drops significantly, consider exiting even if target not reached.
Bearish Singularity (▼ Red Triangle Above Bar):
This marker appears when the system detects a manifold catastrophe at a price high with bearish directional consensus. Same five-filter confirmation process as bullish signals. The red color indicates directional vote totaled -2 or lower (majority bearish).
Trading Approach: Consider short entry on the bar following the signal. Place stop loss above the singularity bar's high (with buffer). Target previous swing low or use cone projection as reference. Exit if opposite signal fires or Hurst deteriorates.
Neutral Signal (● Orange Circle at Price Level):
This marker indicates the catastrophe detection system identified a topology break that passed catastrophe threshold and regime filters, but the directional voting system produced a mixed result (vote between -1 and +1). This means the four directional components (pivot, trend, flow, mid-band) are not in agreement about which way the reversal should resolve.
Trading Approach: Skip these signals. Neutral markers are displayed for analytical completeness but should not be traded. They represent geometric catastrophes without clear directional resolution—essentially, the manifold is breaking but the direction of the break is ambiguous. Trading neutral signals dramatically increases false signal rate. Only trade green (bullish) or red (bearish) singularities.
Visual Confirmation Using Spectral Layers
The three colored ribbons (spectral decomposition layers) provide entropy visualization that helps confirm signal quality:
Divergent Layers (High Entropy State):
When the three frequency bands (fast 8-period, medium 21-period, slow 55-period) are separated with significant gaps between them, the manifold is in high entropy state—different frequency components of price movement are pulling in different directions. This geometric tension precedes catastrophes. Strong signals often occur when layers are divergent before the signal, then begin reconverging immediately after.
Convergent Layers (Low Entropy State):
When all three ribbons are tightly clustered or overlapping, the manifold is in equilibrium—all frequency components agree. This stable geometry makes catastrophe detection more reliable because topology breaks clearly stand out against the baseline stability. If you see layers converge, then a singularity fires, then layers diverge, this pattern suggests a genuine regime transition.
Signal Quality Assessment:
High-quality singularity signals should show:
Divergent layers (high entropy) in the 5-10 bars before signal
Singularity bar occurs when price has extended outside at least one of the spectral bands (shows pivot extended beyond equilibrium)
Close of singularity bar re-enters the spectral band zone (shows mean reversion starting)
Layers begin reconverging in 3-5 bars after signal (shows new equilibrium forming)
This pattern visually confirms the geometric narrative: manifold became unstable (divergence), reached critical distortion (extended outside equilibrium), broke catastrophically (singularity), and is now stabilizing in new direction (reconvergence).
Using Energy Fields for Trade Management
The concentric glowing boxes around each singularity visualize the topology distortion
magnitude:
Wide Energy Fields (5+ Layers Visible):
Large radiance indicates strong catastrophe with high manifold curvature. These represent significant topology breaks and typically precede larger price moves. Wide fields justify wider profit targets and longer hold times. The outer edge of the largest box can serve as a dynamic support/resistance zone—price often respects these geometric boundaries.
Narrow Energy Fields (2-3 Layers):
Smaller radiance indicates moderate catastrophe. While still valid signals (all filters passed), expect smaller follow-through. Use tighter profit targets and be prepared for quicker exit if momentum doesn't develop. These are valid but lower-conviction trades.
Field Interaction Zones:
When energy fields from consecutive signals overlap or touch, this indicates a prolonged topology distortion region—often corresponds to consolidation zones or complex reversal patterns (head-and-shoulders, double tops/bottoms). Be more cautious in these areas as the manifold is undergoing extended restructuring rather than a clean catastrophe.
Probability Cone Projections
The dashed cone extending forward from each singularity is a mathematical projection, not a
price target:
Cone Direction:
The center line direction (upward for bullish, downward for bearish, flat for neutral) shows the expected trajectory based on current manifold gradient and singularity direction. This is where the topology suggests price "should" go if the catastrophe completes normally.
Cone Width:
The uncertainty band (upper and lower dashed boundaries) represents the range of outcomes given current volatility (ATR-based). Wider cones indicate higher uncertainty—expect more price volatility even if direction is correct. Narrower cones suggest more constrained movement.
Price-Cone Interaction:
Price following near the center line = catastrophe resolving as expected, geometric projection accurate
Price breaking above upper cone = stronger-than-expected reversal, consider holding for larger targets
Price breaking below lower cone (for bullish signal) = catastrophe failing, manifold may be re-folding in opposite direction, consider exit
Price oscillating within cone = normal reversal process, hold position
The 10-bar projection length means cones show expected behavior over the next ~10 bars. Don't confuse this with longer-term price targets.
Gradient Flow Field Interpretation
The directional arrows (↗, ↘, →) scattered across the chart show the manifold's Y-gradient (vertical acceleration dimension):
Upward Arrows (↗):
Positive Y-gradient indicates the momentum acceleration dimension is pushing upward—the manifold topology has upward "slope" at this location. Clusters of upward arrows suggest bullish topological pressure building. These often appear before bullish singularities fire.
Downward Arrows (↘):
Negative Y-gradient indicates downward topological pressure. Clusters precede bearish singularities.
Horizontal Arrows (→):
Neutral gradient indicates balanced topology with no strong directional pressure.
Using Flow Field:
The arrows provide real-time topology state information even between singularity signals. If you're in a long position from a bullish singularity and begin seeing increasing downward arrows appearing, this suggests manifold gradient is shifting—consider tightening stops. Conversely, if arrows remain upward or neutral, topology supports continuation.
Don't confuse arrow direction with immediate price direction—arrows show geometric slope, not price prediction. They're confirmatory context, not entry signals themselves.
Parameter Optimization for Your Trading Style
For Scalping / Fast Trading (1m-15m charts):
Embedding Depth: 13-15 bars (faster topology reconstruction)
Hurst Window: 3 bars (responsive fractal detection)
Singularity Threshold: 2.0-2.3σ (more sensitive)
Topology Confirmation: 0.55-0.60 (lower barrier)
Min Swing Size: 0.8-1.2 ATR (accepts smaller moves)
Pivot Lookback: 3-4 bars (quick pivot detection)
This configuration increases signal frequency for active trading but requires diligent monitoring as false signal rate increases. Use tighter stops.
For Day Trading / Standard Approach (15m-4H charts):
Keep default settings (21 embed, 5 Hurst, 2.5σ, 0.65 confirmation, 1.5 ATR, 5 pivot)
These are balanced for quality over quantity
Best win rate and risk/reward ratio
Recommended for most traders
For Swing Trading / Position Trading (4H-Daily charts):
Embedding Depth: 34-55 bars (stable long-term topology)
Hurst Window: 8-10 bars (smooth fractal measurement)
Singularity Threshold: 3.0-3.5σ (only extreme catastrophes)
Topology Confirmation: 0.75-0.85 (high conviction only)
Min Swing Size: 2.5-4.0 ATR (major moves only)
Pivot Lookback: 8-13 bars (confirmed swings)
This configuration produces infrequent but highly reliable signals suitable for position sizing and longer hold times.
Volatility Adaptation:
In extremely volatile instruments (crypto, penny stocks), increase Min Volatility Expansion to 0.6-0.8 to avoid over-signaling during "always volatile" conditions. In stable instruments (major forex pairs, blue-chip stocks), decrease to 0.3 to allow signals during moderate volatility spikes.
Trend vs Range Preference:
If you prefer trading only strong trends, increase Min Trend Strength to 0.5-0.6 (ADX > 50-60). If you're comfortable with volatility-based trading in weaker trends, decrease to 0.2 (ADX > 20). The default 0.3 balances both approaches.
Complete Trading Workflow Example
Step 1 - Pre-Session Setup:
Load chart with MSE indicator. Check dashboard position is visible. Verify regime filter is enabled. Review recent signals to gauge current instrument behavior.
Step 2 - Market Assessment:
Observe dashboard Hurst reading. If H < 0.45 (mean-reverting), consider skipping this session or using other strategies. If H > 0.50, proceed. Check regime shows TREND, VOLATILE, or EXPLOSIVE with checkmark—if CHOP, wait for regime shift alert.
Step 3 - Signal Wait:
Monitor catastrophe score (Σ). Watch for it climbing above 60%. Observe spectral layers—look for divergence building. If you see curvature (κ) rising above 1.0 and complexity (⟳) increasing, catastrophe is building. Do not anticipate—wait for the actual signal marker.
Step 4 - Signal Recognition:
▲ Bullish or ▼ Bearish triangle appears at a bar. Dashboard STATE changes to "◆ BULL/BEAR SINGULARITY". Energy field appears around the signal bar. Check signal quality:
Was Σ > 70% at signal? (Higher quality)
Are energy fields wide? (Stronger catastrophe)
Did layers diverge before and reconverge after? (Clean break)
Is Hurst still > 0.55? (Good regime)
Step 5 - Entry Decision:
If signal is green/red (not orange neutral), all confirmations look strong, and no immediate contradicting factors appear, prepare entry on next bar open. Wait for confirmation bar to form—ideally it should close in the signal direction (bullish signal → bar closes higher, bearish signal → bar closes lower).
Step 6 - Position Entry:
Enter at open or shortly after open of bar following signal bar. Set stop loss: for bullish signals, place stop at singularity_bar_low - (0.75 × ATR); for bearish signals, place stop at singularity_bar_high + (0.75 × ATR). The buffer accommodates volatility while protecting against catastrophe failure.
Step 7 - Trade Management:
Monitor dashboard continuously:
If Hurst drops below 0.45, consider reducing position
If opposite singularity fires, exit immediately (manifold has re-folded)
If catastrophe score drops below 40% and stays there, topology has stabilized—consider partial profit taking
Watch gradient flow arrows—if they shift to opposite direction persistently, tighten stops
Step 8 - Profit Taking:
Use probability cone as a guide—if price reaches outer cone boundary, consider taking partial profits. If price follows center line cleanly, hold for larger target. Traditional technical targets work well: previous swing high/low, round numbers, Fibonacci extensions. Don't expect precision—manifold projections give direction and magnitude estimates, not exact prices.
Step 9 - Exit:
Exit on: (a) opposite signal appears, (b) dashboard shows regime became invalid (checkmark changes to X), (c) technical target reached, (d) Hurst deteriorates significantly, (e) stop loss hit, or (f) time-based exit if using session limits. Never hold through opposite singularity signals—the manifold has broken in the other direction and your trade thesis is invalidated.
Step 10 - Post-Trade Review:
After exit, review: Did the probability cone projection align with actual price movement? Were the energy fields proportional to move size? Did spectral layers show expected reconvergence? Use these observations to calibrate your interpretation of signal quality over time.
Best Performance Conditions
This topology-based approach performs optimally in specific market environments:
Favorable Conditions:
Well-Developed Swing Structure: Markets with clear rhythm of advances and declines where pivots form at regular intervals. The manifold reconstruction depends on swing formation, so instruments that trend in clear waves work best. Stocks, major forex pairs during active sessions, and established crypto assets typically exhibit this characteristic.
Sufficient Volatility for Topology Development: The embedding process requires meaningful price movement to construct multi-dimensional coordinates. Extremely quiet markets (tight consolidations, holiday trading, after-hours) lack the volatility needed for manifold differentiation. Look for ATR expansion above average—when volatility is present, geometry becomes meaningful.
Trending with Periodic Reversals: The ideal environment is not pure trend (which rarely reverses) nor pure range (which reverses constantly at small scale), but rather trending behavior punctuated by occasional significant counter-trend reversals. This creates the catastrophe conditions the system is designed to detect: manifold building directional momentum, then undergoing sharp topology break at extremes.
Liquid Instruments Where EMAs Reflect True Flow: The spectral layers and frequency decomposition require that moving averages genuinely represent market consensus. Thinly traded instruments with sporadic orders don't create smooth manifold topology. Prefer instruments with consistent volume where EMA calculations reflect actual capital flow rather than random tick sequences.
Challenging Conditions:
Extremely Choppy / Whipsaw Markets: When price oscillates rapidly with no directional persistence (Hurst < 0.40), the manifold undergoes constant micro-catastrophes that don't translate to tradable reversals. The regime filter helps avoid these, but awareness is important. If you see multiple neutral signals clustering with no follow-through, market is too chaotic for this approach.
Very Low Volatility Consolidation: Tight ranges with ATR below average cause the embedding coordinates to compress into a small region of phase space, reducing geometric differentiation. The manifold becomes nearly flat, and catastrophe detection loses sensitivity. The regime filter's volatility component addresses this, but manually avoiding dead markets improves results.
Gap-Heavy Instruments: Stocks that gap frequently (opening outside previous close) create discontinuities in the manifold trajectory. The embedding process assumes continuous evolution, so gaps introduce artifacts. Most gaps don't invalidate the approach, but instruments with daily gaps >2% regularly may show degraded performance. Consider using higher timeframes (4H, Daily) where gaps are less proportionally significant.
Parabolic Moves / Blowoff Tops: When price enters an exponential acceleration phase (vertical rally or crash), the manifold evolves too rapidly for the standard embedding window to track. Catastrophe detection may lag or produce false signals mid-move. These conditions are rare but identifiable by Hurst > 0.75 combined with ATR expansion >2.0× average. If detected, consider sitting out or using very tight stops as geometry is in extreme distortion.
The system adapts by reducing signal frequency in poor conditions—if you notice long periods with no signals, the topology likely lacks the geometric structure needed for reliable catastrophe detection. This is a feature, not a bug: it prevents forced trading during unfavorable environments.
Theoretical Justification for Approach
Why Manifold Embedding?
Traditional technical analysis treats price as a one-dimensional time series: current price is predicted from past prices in sequential order. This approach ignores the structure of price dynamics—the relationships between velocity, acceleration, and participation that govern how price actually evolves.
Dynamical systems theory (from physics and mathematics) provides an alternative framework: treat price as a state variable in a multi-dimensional phase space. In this view, each market condition corresponds to a point in N-dimensional space, and market evolution is a trajectory through this space. The geometry of this space (its topology) constrains what trajectories are possible.
Manifold embedding reconstructs this hidden geometric structure from observable price data. By creating coordinates from velocity, momentum acceleration, and volume-weighted returns, we map price evolution onto a 3D surface. This surface—the manifold—reveals geometric relationships that aren't visible in price charts alone.
The mathematical theorem underlying this approach (Takens' Embedding Theorem from dynamical systems theory) proves that for deterministic or weakly stochastic systems, a state space reconstruction from time-delayed observations of a single variable captures the essential dynamics of the full system. We apply this principle: even though we only observe price, the embedded coordinates (derivatives of price) reconstruct the underlying dynamical structure.
Why Catastrophe Theory?
Catastrophe theory, developed by mathematician René Thom (Fields Medal 1958), describes how continuous systems can undergo sudden discontinuous changes when control parameters reach critical values. A classic example: gradually increasing force on a beam causes smooth bending, then sudden catastrophic buckling. The beam's geometry reaches a critical curvature where topology must break.
Markets exhibit analogous behavior: gradual price changes build tension in the manifold topology until critical distortion is reached, then abrupt directional change occurs (reversal). Catastrophes aren't random—they're mathematically necessary when geometric constraints are violated.
The indicator detects these geometric precursors: high curvature (manifold bending sharply), high complexity (topology oscillating chaotically), high condition number (coordinate mapping becoming singular). These metrics quantify how close the manifold is to a catastrophic fold. When all simultaneously reach extreme values, topology break is imminent.
This provides a logical foundation for reversal detection that doesn't rely on pattern recognition or historical correlation. We're measuring geometric properties that mathematically must change when systems reach critical states. This is why the approach works across different instruments and timeframes—the underlying geometry is universal.
Why Hurst Exponent?
Markets exhibit fractal behavior: patterns at different time scales show statistical self-similarity. The Hurst exponent quantifies this fractal structure by measuring long-range dependence in returns.
Critically for trading, Hurst determines whether recent price movement predicts future direction (H > 0.5) or predicts the opposite (H < 0.5). This is regime detection: trending vs mean-reverting behavior.
The same manifold catastrophe has different trading implications depending on regime. In trending regime (high Hurst), catastrophes represent significant reversal opportunities because the manifold has been building directional momentum that suddenly breaks. In mean-reverting regime (low Hurst), catastrophes represent minor oscillations because the manifold constantly folds at small scales.
By weighting catastrophe signals based on Hurst, the system adapts detection sensitivity to the current fractal regime. This is a form of meta-analysis: not just detecting geometric breaks, but evaluating whether those breaks are meaningful in the current fractal context.
Why Multi-Layer Confirmation?
Geometric anomalies occur frequently in noisy market data. Not every high-curvature point represents a tradable reversal—many are artifacts of microstructure noise, order flow imbalances, or low-liquidity ticks.
The five-filter confirmation system (catastrophe threshold, pivot structure, swing size, volume, regime) addresses this by requiring geometric anomalies to align with observable market evidence. This conjunction-based logic implements the principle: extraordinary claims require extraordinary evidence .
A manifold catastrophe (extraordinary geometric event) alone is not sufficient. We additionally require: price formed a pivot (visible structure), swing was significant (adequate magnitude), volume confirmed participation (capital backed the move), and regime was favorable (trending or volatile, not chopping). Only when all five dimensions agree do we have sufficient evidence that the geometric anomaly represents a genuine reversal opportunity rather than noise.
This multi-dimensional approach is analogous to medical diagnosis: no single test is conclusive, but when multiple independent tests all suggest the same condition, confidence increases dramatically. Each filter removes a different category of false signals, and their combination creates a robust detection system.
The result is a signal set with dramatically improved reliability compared to any single metric alone. This is the power of ensemble methods applied to geometric analysis.
Important Disclaimers
This indicator applies mathematical topology and catastrophe theory to multi-dimensional price space reconstruction. It identifies geometric conditions where manifold curvature, topological complexity, and coordinate singularities suggest potential reversal zones based on phase space analysis. It should not be used as a standalone trading system.
The embedding coordinates, catastrophe scores, and Hurst calculations are deterministic mathematical formulas applied to historical price data. These measurements describe current and recent geometric relationships in the reconstructed manifold but do not predict future price movements. Past geometric patterns and singularity markers do not guarantee future market behavior will follow similar topology evolution.
The manifold reconstruction assumes certain mathematical properties (sufficient embedding dimension, quasi-stationarity, continuous dynamics) that may not hold in all market conditions. Gaps, flash crashes, circuit breakers, news events, and other discontinuities can violate these assumptions. The system attempts to filter problematic conditions through regime classification, but cannot eliminate all edge cases.
The spectral decomposition, energy fields, and probability cones are visualization aids that represent mathematical constructs, not price predictions. The probability cone projects current gradient forward assuming topology continues current trajectory—this is a mathematical "if-then" statement, not a forecast. Market topology can and does change unexpectedly.
All trading involves substantial risk. The singularity markers represent analytical conditions where geometric mathematics align with threshold criteria, not certainty of directional change. Use appropriate risk management for every trade: position sizing based on account risk tolerance (typically 1-2% maximum risk per trade), stop losses placed beyond recent structure plus volatility buffer, and never risk capital needed for living expenses.
The confirmation filters (pivot, swing size, volume, regime) are designed to reduce false signals but cannot eliminate them entirely. Markets can produce geometric anomalies that pass all filters yet fail to develop into sustained reversals. This is inherent to probabilistic systems operating on noisy real-world data.
No indicator can guarantee profitable trades or eliminate losses. The catastrophe detection provides an analytical framework for identifying potential reversal conditions, but actual trading outcomes depend on numerous factors including execution, slippage, spreads, position sizing, risk management, psychological discipline, and market conditions that may change after signal generation.
Use this tool as one component of a comprehensive trading plan that includes multiple forms of analysis, proper risk management, emotional discipline, and realistic expectations about win rates and drawdowns. Combine catastrophe signals with additional confirmation methods such as support/resistance analysis, volume patterns, multi-timeframe alignment, and broader market context.
The spacing filter, cooldown mechanism, and regime validation are designed to reduce noise and over-signaling, but market conditions can change rapidly and render any analytical signal invalid. Always use stop losses and never risk capital you cannot afford to lose. Past performance of detection accuracy does not guarantee future results.
Technical Implementation Notes
All calculations execute on closed bars only—signals and metric values do not repaint after bar close. The indicator does not use any lookahead bias in its calculations. However, the pivot detection mechanism (ta.pivothigh and ta.pivotlow) inherently identifies pivots with a lag equal to the lookback parameter, meaning the actual pivot occurred at bar but is recognized at bar . This is standard behavior for pivot functions and is not repainting—once recognized, the pivot bar never changes.
The normalization system (z-score transformation over rolling windows) requires approximately 30-50 bars of historical data to establish stable statistics. Values in the first 30-50 bars after adding the indicator may show instability as the rolling means and standard deviations converge. Allow adequate warmup period before relying on signals.
The spectral layer arrays, energy field boxes, gradient flow labels, and node geometry lines are subject to TradingView drawing object limits (500 lines, 500 boxes, 500 labels per indicator as specified in settings). The system implements automatic cleanup by deleting oldest objects when limits approach, but on very long charts with many signals, some historical visual elements may be removed to stay within limits. This does not affect signal generation or dashboard metrics—only historical visual artifacts.
Dashboard and visual rendering update only on the last bar to minimize computational overhead. The catastrophe detection logic executes on every bar, but table cells and drawing objects refresh conditionally to optimize performance. If experiencing chart lag, reduce visual complexity: disable spectral layers, energy fields, or flow field to improve rendering speed. Core signal detection continues to function with all visual elements disabled.
The Hurst calculation uses logarithmic returns rather than raw price to ensure stationarity, and implements clipping to range to handle edge cases where R/S analysis produces invalid values (which can occur during extended periods of identical prices or numerical overflow). The 5-period EMA smoothing reduces noise while maintaining responsiveness to regime transitions.
The condition number calculation adds epsilon (1e-10) to denominators to prevent division by zero when Jacobian determinant approaches zero—which is precisely the singularity condition we're detecting. This numerical stability measure ensures the indicator doesn't crash when detecting the very phenomena it's designed to identify.
The indicator has been tested across multiple timeframes (5-minute through daily) and multiple asset classes (forex majors, stock indices, individual equities, cryptocurrencies, commodities, futures). It functions identically across all instruments due to the adaptive normalization approach and percentage-based metrics. No instrument-specific code or parameter sets are required.
The color scheme system implements seven preset themes plus custom mode. Color assignments are applied globally and affect all visual elements simultaneously. The opacity calculation system multiplies component-specific transparency with master opacity to create hierarchical control—adjusting master opacity affects all visuals proportionally while maintaining their relative transparency relationships.
All alert conditions trigger only on bar close to prevent false alerts from intrabar fluctuations. The regime transition alerts (VALID/INVALID) are particularly useful for knowing when trading edge appears or disappears, allowing traders to adjust activity levels accordingly.
— Dskyz, Trade with insight. Trade with anticipation.
High Accuracy Engulfing Strategy [PIPNEXUS]Title: EMA Engulfing Setup
Description:
This indicator focuses on identifying strong engulfing patterns that form around the EMA line, helping traders catch high-probability moves in line with market direction.
Concept Overview:
The idea is simple — when both the engulfing candle and the candle being engulfed have their bodies touching the EMA line, it often represents a key point of rejection or continuation. These areas can produce clean entries with strong momentum.
How to Use:
1. Wait for a valid engulfing formation near the EMA line.
Both the engulfing and the engulfed candles should have their bodies touching the EMA.
2. Enter in the direction of the engulfing candle once the pattern is confirmed.
3. For pinpoint entries, observe the market during session changes (especially in the first 3–5 minutes after a session opens).
4. For longer and more stable trades, look for the same pattern on 15-minute or 1-hour charts.
5. Always align your trades with the prevailing market structure and avoid counter-trend setups.
Note:
This indicator is designed for technical and educational use. It does not generate buy or sell signals automatically, nor does it guarantee performance. Use it alongside your own market analysis and proper risk management.
ICT ADR/AWR/AMR Levels | Trade Symmetry🌟 ICT ADR/AWR/AMR Levels
📋 Overview
This advanced technical analysis tool calculates and displays Average Daily Range (ADR), Average Weekly Range (AWR), and Average Monthly Range (AMR) levels. The indicator incorporates smart detection technology that automatically maintains monthly level visibility when historical data becomes unavailable.
✨ Key Features
🕒 Precise Time Alignment
True Daily Opens (TDO) aligned with 00:00 UTC
True Weekly Opens (TWO) at 00:00 UTC (configurable Monday/Sunday start)
True Monthly Opens (TMO) at 00:00 UTC on month start
Customizable period start times and parameters
📊 Comprehensive Multi-Timeframe Analysis
Daily Levels (ADR): Base level with multiple extensions including Fibonacci ratios
Weekly Levels (AWR): Weekly range projections and key levels
Monthly Levels (AMR): Monthly range calculations with automatic fallback system
🔄 Intelligent Level Management
Smart Detection: Automatically switches between historical and current monthly levels
Continuous Visibility: Ensures reference levels remain visible regardless of data availability
Seamless Operation: No manual adjustment needed for level transitions
⚙️ Extensive Customization
Adjustable lookback periods for all timeframes
Independent control over each level type and extension
Complete visual customization (colors, styles, widths)
Flexible labeling and display options
Configurable vertical separation lines
🏷️ Advanced Display Options
Clean, organized label placement
Optional price display in labels
Historical period tracking
Overlapping label merging capability
Adjustable label sizing and positioning
🚀 How to Use
Initial Setup: Enable desired timeframes (Daily/Weekly/Monthly)
Range Configuration: Set appropriate averaging periods for each timeframe
Level Selection: Choose which extension levels to display
Visual Settings: Customize colors and styles to match your trading workspace
Automatic Operation: The indicator intelligently manages level transitions
💡 Practical Applications
Identify potential support and resistance areas across multiple timeframes
Establish realistic profit targets based on historical volatility
Plan trade entries and exits around significant time-based levels
Analyze market volatility patterns across different time horizons
Incorporate institutional trading concepts into your analysis
LibVPrfLibrary "LibVPrf"
This library provides an object-oriented framework for volume
profile analysis in Pine Script®. It is built around the `VProf`
User-Defined Type (UDT), which encapsulates all data, settings,
and statistical metrics for a single profile, enabling stateful
analysis with on-demand calculations.
Key Features:
1. **Object-Oriented Design (UDT):** The library is built around
the `VProf` UDT. This object encapsulates all profile data
and provides methods for its full lifecycle management,
including creation, cloning, clearing, and merging of profiles.
2. **Volume Allocation (`AllotMode`):** Offers two methods for
allocating a bar's volume:
- **Classic:** Assigns the entire bar's volume to the close
price bucket.
- **PDF:** Distributes volume across the bar's range using a
statistical price distribution model from the `LibBrSt` library.
3. **Buy/Sell Volume Splitting (`SplitMode`):** Provides methods
for classifying volume into buying and selling pressure:
- **Classic:** Classifies volume based on the bar's color (Close vs. Open).
- **Dynamic:** A specific model that analyzes candle structure
(body vs. wicks) and a short-term trend factor to
estimate the buy/sell share at each price level.
4. **Statistical Analysis (On-Demand):** Offers a suite of
statistical metrics calculated using a "Lazy Evaluation"
pattern (computed only when requested via `get...` methods):
- **Central Tendency:** Point of Control (POC), VWAP, and Median.
- **Dispersion:** Value Area (VA) and Population Standard Deviation.
- **Shape:** Skewness and Excess Kurtosis.
- **Delta:** Cumulative Volume Delta, including its
historical high/low watermarks.
5. **Structural Analysis:** Includes a parameter-free method
(`getSegments`) to decompose a profile into its fundamental
unimodal segments, allowing for modality detection (e.g.,
identifying bimodal profiles).
6. **Dynamic Profile Management:**
- **Auto-Fitting:** Profiles set to `dynamic = true` will
automatically expand their price range to fit new data.
- **Manipulation:** The resolution, price range, and Value Area
of a dynamic profile can be changed at any time. This
triggers a resampling process that uses a **linear
interpolation model** to re-bucket existing volume.
- **Assumption:** Non-dynamic profiles are fixed and will throw
a `runtime.error` if `addBar` is called with data
outside their initial range.
7. **Bucket-Level Access:** Provides getter methods for direct
iteration and analysis of the raw buy/sell volume and price
boundaries of each individual price bucket.
---
**DISCLAIMER**
This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.
The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.
As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.
create(buckets, rangeUp, rangeLo, dynamic, valueArea, allot, estimator, cdfSteps, split, trendLen)
Construct a new `VProf` object with fixed bucket count & range.
Parameters:
buckets (int) : series int number of price buckets ≥ 1
rangeUp (float) : series float upper price bound (absolute)
rangeLo (float) : series float lower price bound (absolute)
dynamic (bool) : series bool Flag for dynamic adaption of profile ranges
valueArea (int) : series int Percentage of total volume to include in the Value Area (1..100)
allot (series AllotMode) : series AllotMode Allocation mode `classic` or `pdf` (default `classic`)
estimator (series PriceEst enum from AustrianTradingMachine/LibBrSt/1) : series LibBrSt.PriceEst PDF model when `model == PDF`. (deflault = 'uniform')
cdfSteps (int) : series int even #sub-intervals for Simpson rule (default 20)
split (series SplitMode) : series SplitMode Buy/Sell determination (default `classic`)
trendLen (int) : series int Look‑back bars for trend factor (default 3)
Returns: VProf freshly initialised profile
method clone(self)
Create a deep copy of the volume profile.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object to copy
Returns: VProf A new, independent copy of the profile
method clear(self)
Reset all bucket tallies while keeping configuration intact.
Namespace types: VProf
Parameters:
self (VProf) : VProf profile object
Returns: VProf cleared profile (chaining)
method merge(self, srcABuy, srcASell, srcRangeUp, srcRangeLo, srcCvd, srcCvdHi, srcCvdLo)
Merges volume data from a source profile into the current profile.
If resizing is needed, it performs a high-fidelity re-bucketing of existing
volume using a linear interpolation model inferred from neighboring buckets,
preventing aliasing artifacts and ensuring accurate volume preservation.
Namespace types: VProf
Parameters:
self (VProf) : VProf The target profile object to merge into.
srcABuy (array) : array The source profile's buy volume bucket array.
srcASell (array) : array The source profile's sell volume bucket array.
srcRangeUp (float) : series float The upper price bound of the source profile.
srcRangeLo (float) : series float The lower price bound of the source profile.
srcCvd (float) : series float The final Cumulative Volume Delta (CVD) value of the source profile.
srcCvdHi (float) : series float The historical high-water mark of the CVD from the source profile.
srcCvdLo (float) : series float The historical low-water mark of the CVD from the source profile.
Returns: VProf `self` (chaining), now containing the merged data.
method addBar(self, offset)
Add current bar’s volume to the profile (call once per realtime bar).
classic mode: allocates all volume to the close bucket and classifies
by `close >= open`. PDF mode: distributes volume across buckets by the
estimator’s CDF mass. For `split = dynamic`, the buy/sell share per
price is computed via context-driven piecewise s(u).
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
offset (int) : series int To offset the calculated bar
Returns: VProf `self` (method chaining)
method setBuckets(self, buckets)
Sets the number of buckets for the volume profile.
Behavior depends on the `isDynamic` flag.
- If `dynamic = true`: Works on filled profiles by re-bucketing to a new resolution.
- If `dynamic = false`: Only works on empty profiles to prevent accidental changes.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
buckets (int) : series int The new number of buckets
Returns: VProf `self` (chaining)
method setRanges(self, rangeUp, rangeLo)
Sets the price range for the volume profile.
Behavior depends on the `dynamic` flag.
- If `dynamic = true`: Works on filled profiles by re-bucketing existing volume.
- If `dynamic = false`: Only works on empty profiles to prevent accidental changes.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
rangeUp (float) : series float The new upper price bound
rangeLo (float) : series float The new lower price bound
Returns: VProf `self` (chaining)
method setValueArea(self, valueArea)
Set the percentage of volume for the Value Area. If the value
changes, the profile is finalized again.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
valueArea (int) : series int The new Value Area percentage (0..100)
Returns: VProf `self` (chaining)
method getBktBuyVol(self, idx)
Get Buy volume of a bucket.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
idx (int) : series int Bucket index
Returns: series float Buy volume ≥ 0
method getBktSellVol(self, idx)
Get Sell volume of a bucket.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
idx (int) : series int Bucket index
Returns: series float Sell volume ≥ 0
method getBktBnds(self, idx)
Get Bounds of a bucket.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
idx (int) : series int Bucket index
Returns:
up series float The upper price bound of the bucket.
lo series float The lower price bound of the bucket.
method getPoc(self)
Get POC information.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
Returns:
pocIndex series int The index of the Point of Control (POC) bucket.
pocPrice. series float The mid-price of the Point of Control (POC) bucket.
method getVA(self)
Get Value Area (VA) information.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
Returns:
vaUpIndex series int The index of the upper bound bucket of the Value Area.
vaUpPrice series float The upper price bound of the Value Area.
vaLoIndex series int The index of the lower bound bucket of the Value Area.
vaLoPrice series float The lower price bound of the Value Area.
method getMedian(self)
Get the profile's median price and its bucket index. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns:
medianIndex series int The index of the bucket containing the Median.
medianPrice series float The Median price of the profile.
method getVwap(self)
Get the profile's VWAP and its bucket index. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns:
vwapIndex series int The index of the bucket containing the VWAP.
vwapPrice series float The Volume Weighted Average Price of the profile.
method getStdDev(self)
Get the profile's volume-weighted standard deviation. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns: series float The Standard deviation of the profile.
method getSkewness(self)
Get the profile's skewness. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns: series float The Skewness of the profile.
method getKurtosis(self)
Get the profile's excess kurtosis. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns: series float The Kurtosis of the profile.
method getSegments(self)
Get the profile's fundamental unimodal segments. Calculates on-demand if stale.
Uses a parameter-free, pivot-based recursive algorithm.
Namespace types: VProf
Parameters:
self (VProf) : VProf The profile object.
Returns: matrix A 2-column matrix where each row is an pair.
method getCvd(self)
Cumulative Volume Delta (CVD) like metric over all buckets.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns:
cvd series float The final Cumulative Volume Delta (Total Buy Vol - Total Sell Vol).
cvdHi series float The running high-water mark of the CVD as volume was added.
cvdLo series float The running low-water mark of the CVD as volume was added.
VProf
VProf Bucketed Buy/Sell volume profile plus meta information.
Fields:
buckets (series int) : int Number of price buckets (granularity ≥1)
rangeUp (series float) : float Upper price range (absolute)
rangeLo (series float) : float Lower price range (absolute)
dynamic (series bool) : bool Flag for dynamic adaption of profile ranges
valueArea (series int) : int Percentage of total volume to include in the Value Area (1..100)
allot (series AllotMode) : AllotMode Allocation mode `classic` or `pdf`
estimator (series PriceEst enum from AustrianTradingMachine/LibBrSt/1) : LibBrSt.PriceEst Price density model when `model == PDF`
cdfSteps (series int) : int Simpson integration resolution (even ≥2)
split (series SplitMode) : SplitMode Buy/Sell split strategy per bar
trendLen (series int) : int Look‑back length for trend factor (≥1)
maxBkt (series int) : int User-defined number of buckets (unclamped)
aBuy (array) : array Buy volume per bucket
aSell (array) : array Sell volume per bucket
cvd (series float) : float Final Cumulative Volume Delta (Total Buy Vol - Total Sell Vol).
cvdHi (series float) : float Running high-water mark of the CVD as volume was added.
cvdLo (series float) : float Running low-water mark of the CVD as volume was added.
poc (series int) : int Index of max‑volume bucket (POC). Is `na` until calculated.
vaUp (series int) : int Index of upper Value‑Area bound. Is `na` until calculated.
vaLo (series int) : int Index of lower value‑Area bound. Is `na` until calculated.
median (series float) : float Median price of the volume distribution. Is `na` until calculated.
vwap (series float) : float Profile VWAP (Volume Weighted Average Price). Is `na` until calculated.
stdDev (series float) : float Standard Deviation of volume around the VWAP. Is `na` until calculated.
skewness (series float) : float Skewness of the volume distribution. Is `na` until calculated.
kurtosis (series float) : float Excess Kurtosis of the volume distribution. Is `na` until calculated.
segments (matrix) : matrix A 2-column matrix where each row is an pair. Is `na` until calculated.
LibBrStLibrary "LibBrSt"
This is a library for quantitative analysis, designed to estimate
the statistical properties of price movements *within* a single
OHLC bar, without requiring access to tick data. It provides a
suite of estimators based on various statistical and econometric
models, allowing for analysis of intra-bar volatility and
price distribution.
Key Capabilities:
1. **Price Distribution Models (`PriceEst`):** Provides a selection
of estimators that model intra-bar price action as a probability
distribution over the range. This allows for the
calculation of the intra-bar mean (`priceMean`) and standard
deviation (`priceStdDev`) in absolute price units. Models include:
- **Symmetric Models:** `uniform`, `triangular`, `arcsine`,
`betaSym`, and `t4Sym` (Student-t with fat tails).
- **Skewed Models:** `betaSkew` and `t4Skew`, which adjust
their shape based on the Open/Close position.
- **Model Assumptions:** The skewed models rely on specific
internal constants. `betaSkew` uses a fixed concentration
parameter (`BETA_SKEW_CONCENTRATION = 4.0`), and `t4Sym`/`t4Skew`
use a heuristic scaling factor (`T4_SHAPE_FACTOR`)
to map the distribution.
2. **Econometric Log-Return Estimators (`LogEst`):** Includes a set of
econometric estimators for calculating the volatility (`logStdDev`)
and drift (`logMean`) of logarithmic returns within a single bar.
These are unit-less measures. Models include:
- **Parkinson (1980):** A High-Low range estimator.
- **Garman-Klass (1980):** An OHLC-based estimator.
- **Rogers-Satchell (1991):** An OHLC estimator that accounts
for non-zero drift.
3. **Distribution Analysis (PDF/CDF):** Provides functions to work
with the Probability Density Function (`pricePdf`) and
Cumulative Distribution Function (`priceCdf`) of the
chosen price model.
- **Note on `priceCdf`:** This function uses analytical (exact)
calculations for the `uniform`, `triangular`, and `arcsine`
models. For all other models (e.g., `betaSkew`, `t4Skew`),
it uses **numerical integration (Simpson's rule)** as
an approximation of the cumulative probability.
4. **Mathematical Functions:** The library's Beta distribution
models (`betaSym`, `betaSkew`) are supported by an internal
implementation of the natural log-gamma function, which is
based on the Lanczos approximation.
---
**DISCLAIMER**
This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.
The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.
As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.
priceStdDev(estimator, offset)
Estimates **σ̂** (standard deviation) *in price units* for the current
bar, according to the chosen `PriceEst` distribution assumption.
Parameters:
estimator (series PriceEst) : series PriceEst Distribution assumption (see enum).
offset (int) : series int To offset the calculated bar
Returns: series float σ̂ ≥ 0 ; `na` if undefined (e.g. zero range).
priceMean(estimator, offset)
Estimates **μ̂** (mean price) for the chosen `PriceEst` within the
current bar.
Parameters:
estimator (series PriceEst) : series PriceEst Distribution assumption (see enum).
offset (int) : series int To offset the calculated bar
Returns: series float μ̂ in price units.
pricePdf(estimator, price, offset)
Probability-density under the chosen `PriceEst` model.
**Returns 0** when `p` is outside the current bar’s .
Parameters:
estimator (series PriceEst) : series PriceEst Distribution assumption (see enum).
price (float) : series float Price level to evaluate.
offset (int) : series int To offset the calculated bar
Returns: series float Density value.
priceCdf(estimator, upper, lower, steps, offset)
Cumulative probability **between** `upper` and `lower` under
the chosen `PriceEst` model. Outside-bar regions contribute zero.
Uses a fast, analytical calculation for Uniform, Triangular, and
Arcsine distributions, and defaults to numerical integration
(Simpson's rule) for more complex models.
Parameters:
estimator (series PriceEst) : series PriceEst Distribution assumption (see enum).
upper (float) : series float Upper Integration Boundary.
lower (float) : series float Lower Integration Boundary.
steps (int) : series int # of sub-intervals for numerical integration (if used).
offset (int) : series int To offset the calculated bar.
Returns: series float Probability mass ∈ .
logStdDev(estimator, offset)
Estimates **σ̂** (standard deviation) of *log-returns* for the current bar.
Parameters:
estimator (series LogEst) : series LogEst Distribution assumption (see enum).
offset (int) : series int To offset the calculated bar
Returns: series float σ̂ (unit-less); `na` if undefined.
logMean(estimator, offset)
Estimates μ̂ (mean log-return / drift) for the chosen `LogEst`.
The returned value is consistent with the assumptions of the
selected volatility estimator.
Parameters:
estimator (series LogEst) : series LogEst Distribution assumption (see enum).
offset (int) : series int To offset the calculated bar
Returns: series float μ̂ (unit-less log-return).






















