First Passage Time - Distribution AnalysisThe First Passage Time (FPT) Distribution Analysis indicator is a sophisticated probabilistic tool that answers one of the most critical questions in trading: "How long will it take for price to reach my target, and what are the odds of getting there first?"
Unlike traditional technical indicators that focus on what might happen, this indicator tells you when it's likely to happen.
 Mathematical Foundation: First Passage Time Theory 
What is First Passage Time?
First Passage Time (FPT) is a concept in stochastic processes that measures the time it takes for a random process to reach a specific threshold for the first time. Originally developed in physics and mathematics, FPT has applications in:
 
 Quantitative Finance: Option pricing, risk management, and algorithmic trading
 Neuroscience: Modeling neural firing patterns
 Biology: Population dynamics and disease spread
 Engineering: Reliability analysis and failure prediction
 
 The Mathematics Behind It 
This indicator uses Geometric Brownian Motion (GBM), the same stochastic model used in the Black-Scholes option pricing formula:
dS = μS dt + σS dW
Where:
S = Asset price
μ = Drift (trend component)
σ = Volatility (uncertainty component)
dW = Wiener process (random walk)
Through Monte Carlo simulation, the indicator runs 1,000+ price path simulations to statistically determine:
 
 When each threshold (+X% or -X%) is likely to be hit
 Which threshold is hit first (directional bias)
 How often each scenario occurs (probability distribution)
 
 🎯 How This Indicator Works 
Core Algorithm Workflow: 
 
 Calculate Historical Statistics
 Measures recent price volatility (standard deviation of log returns)
 Calculates drift (average directional movement)
 Annualizes these metrics for meaningful comparison
 Run Monte Carlo Simulations
 Generates 1,000+ random price paths based on historical behavior
 Tracks when each path hits the upside (+X%) or downside (-X%) threshold
 Records which threshold was hit first in each simulation
 Aggregate Statistical Results
 Calculates percentile distributions (10th, 25th, 50th, 75th, 90th)
 Computes "first hit" probabilities (upside vs downside)
 Determines average and median time-to-target
 Visual Representation
 Displays thresholds as horizontal lines
 Shows gradient risk zones (purple-to-blue)
 Provides comprehensive statistics table
 
 📈 Use Cases 
1. Options Trading
 
 Selling Options: Determine if your strike price is likely to be hit before expiration
 Buying Options: Estimate probability of reaching profit targets within your time window
 Time Decay Management: Compare expected time-to-target vs theta decay
 Example: You're considering selling a 30-day call option 5% out of the money. The indicator shows there's a 72% chance price hits +5% within 12 days. This tells you the trade has high assignment risk.
 
2. Swing Trading
 
 Entry Timing: Wait for higher probability setups when directional bias is strong
 Target Setting: Use median time-to-target to set realistic profit expectations
 Stop Loss Placement: Understand probability of hitting your stop before target
 Example: The indicator shows 85% upside probability with median time of 3.2 days. You can confidently enter long positions with appropriate position sizing.
 
3. Risk Management
 
 Position Sizing: Larger positions when probability heavily favors one direction
 Portfolio Allocation: Reduce exposure when probabilities are near 50/50 (high uncertainty)
 Hedge Timing: Know when to add protective positions based on downside probability
 Example: Indicator shows 55% upside vs 45% downside—nearly neutral. This signals high uncertainty, suggesting reduced position size or wait for better setup.
 
4. Market Regime Detection
 
 Trending Markets: High directional bias (70%+ one direction)
 Range-bound Markets: Balanced probabilities (45-55% both directions)
 Volatility Regimes: Compare actual vs theoretical minimum time
 Example: Consistent 90%+ bullish bias across multiple timeframes confirms strong uptrend—stay long and avoid counter-trend trades.
 
 First Hit Rate (Most Important!) 
Shows which threshold is likely to be hit FIRST:
 
 Upside %: Probability of hitting upside target before downside
 Downside %: Probability of hitting downside target before upside
 These always sum to 100%
 
 ⚠️ Warning: If you see "Low Hit Rate" warning, increase this parameter! 
 Advanced Parameters 
Drift Mode
Allows you to explore different scenarios:
 
 Historical: Uses actual recent trend (default—most realistic)
 Zero (Neutral): Assumes no trend, only volatility (symmetric probabilities)
 50% Reduced: Dampens trend effect (conservative scenario)
 Use Case: Switch to "Zero (Neutral)" to see what happens in a pure volatility environment, useful for range-bound markets.
 
Distribution Type
 
 Percentile: Shows 10%, 25%, 50%, 75%, 90% levels (recommended for most users)
 Sigma: Shows standard deviation levels (1σ, 2σ)—useful for statistical analysis
 
 ⚠️ Important Limitations & Best Practices 
Limitations
 
 Assumes GBM: Real markets have fat tails, jumps, and regime changes not captured by GBM
 Historical Parameters: Uses recent volatility/drift—may not predict regime shifts
 No Fundamental Events: Cannot predict earnings, news, or macro shocks
 Computational: Runs only on last bar—doesn't give historical signals
 
Remember: Probabilities are not certainties. Use this indicator as part of a comprehensive trading plan with proper risk management.
Created by: Henrique Centieiro. feedback is more than welcome!
Probability
Hummingbird Probability Mapping IndicatorHummingbird Probability Mapping Indicator  - A nature inspired indicator that utilizes combinations of the following trend patterns and projects a probability mapping with greater than 70% accuracy based on real-time analysis.
 EMA Trend 
 MACD 
 RSI 
 VWAP Spread 
 Burst 
 Squeeze 
 Volatility (ATRp) 
Qi Dass
Institutional Levels (CNN) - [PhenLabs]📊Institutional Levels (Convolutional Neural Network-inspired)  
 Version : PineScript™v6
 📌Description 
The CNN-IL Institutional Levels indicator represents a breakthrough in automated zone detection technology, combining convolutional neural network principles with advanced statistical modeling. This sophisticated tool identifies high-probability institutional trading zones by analyzing pivot patterns, volume dynamics, and price behavior using machine learning algorithms.
The indicator employs a proprietary 9-factor logistic regression model that calculates real-time reaction probabilities for each detected zone. By incorporating CNN-inspired filtering techniques and dynamic zone management, it provides traders with unprecedented accuracy in identifying where institutional money is likely to react to price action.
 🚀Points of Innovation 
●  CNN-Inspired Pivot Analysis  - Advanced binning system using convolutional neural network principles for superior pattern recognition
●  Real-Time Probability Engine  - Live reaction probability calculations using 9-factor logistic regression model
●  Dynamic Zone Intelligence  - Automatic zone merging using Intersection over Union (IoU) algorithms
●  Volume-Weighted Scoring  - Time-of-day volume Z-score analysis for enhanced zone strength assessment
●  Adaptive Decay System  - Intelligent zone lifecycle management based on touch frequency and recency
●  Multi-Filter Architecture  - Optional gradient, smoothing, and Difference of Gaussians (DoG) convolution filters
 🔧Core Components 
●  Pivot Detection Engine  - Advanced pivot identification with configurable left/right bars and ATR-normalized strength calculations
●  Neural Network Binning  - Price level clustering using CNN-inspired algorithms with ATR-based bin sizing
●  Logistic Regression Model  - 9-factor probability calculation including distance, width, volume, VWAP deviation, and trend analysis
●  Zone Management System  - Intelligent creation, merging, and decay algorithms for optimal zone lifecycle control
●  Visualization Layer  - Dynamic line drawing with opacity-based scoring and optional zone fills
 🔥Key Features 
●  High-Probability Zone Detection  - Automatically identifies institutional levels with reaction probabilities above configurable thresholds
●  Real-Time Probability Scoring  - Live calculation of zone reaction likelihood using advanced statistical modeling
●  Session-Aware Analysis  - Optional filtering to specific trading sessions for enhanced accuracy during active market hours
●  Customizable Parameters  - Full control over lookback periods, zone sensitivity, merge thresholds, and probability models
●  Performance Optimized  - Efficient processing with controlled update frequencies and pivot processing limits
●  Non-Repainting Mode  - Strict mode available for backtesting accuracy and live trading reliability
 🎨Visualization 
●  Dynamic Zone Lines  - Color-coded support and resistance levels with opacity reflecting zone strength and confidence scores
●  Probability Labels  - Real-time display of reaction probabilities, touch counts, and historical hit rates for active zones
●  Zone Fills  - Optional semi-transparent zone highlighting for enhanced visual clarity and immediate pattern recognition
●  Adaptive Styling  - Automatic color and opacity adjustments based on zone scoring and statistical significance
 📖Usage Guidelines 
●  Lookback Bars  - Default 500, Range 100-1000, Controls the historical data window for pivot analysis and zone calculation
●  Pivot Left/Right  - Default 3, Range 1-10, Defines the pivot detection sensitivity and confirmation requirements
●  Bin Size ATR units  - Default 0.25, Range 0.1-2.0, Controls price level clustering granularity for zone creation
●  Base Zone Half-Width ATR units  - Default 0.25, Range 0.1-1.0, Sets the minimum zone width in ATR units for institutional level boundaries
●  Zone Merge IoU Threshold  - Default 0.5, Range 0.1-0.9, Intersection over Union threshold for automatic zone merging algorithms
●  Max Active Zones  - Default 5, Range 3-20, Maximum number of zones displayed simultaneously to prevent chart clutter
●  Probability Threshold for Labels  - Default 0.6, Range 0.3-0.9, Minimum reaction probability required for zone label display and alerts
●  Distance Weight w1  - Controls influence of price distance from zone center on reaction probability
●  Width Weight w2  - Adjusts impact of zone width on probability calculations
●  Volume Weight w3  - Modifies volume Z-score influence on zone strength assessment
●  VWAP Weight w4  - Controls VWAP deviation impact on institutional level significance
●  Touch Count Weight w5  - Adjusts influence of historical zone interactions on probability scoring
●  Hit Rate Weight w6  - Controls prior success rate impact on future reaction likelihood predictions
●  Wick Penetration Weight w7  - Modifies wick penetration analysis influence on probability calculations
●  Trend Weight w8  - Adjusts trend context impact using ADX analysis for directional bias assessment
 ✅Best Use Cases 
●  Swing Trading Entries  - Enter positions at high-probability institutional zones with 60%+ reaction scores
●  Scalping Opportunities  - Quick entries and exits around frequently tested institutional levels
●  Risk Management  - Use zones as dynamic stop-loss and take-profit levels based on institutional behavior
●  Market Structure Analysis  - Identify key institutional levels that define current market structure and sentiment
●  Confluence Trading  - Combine with other technical indicators for high-probability trade setups
●  Session-Based Strategies  - Focus analysis during high-volume sessions for maximum effectiveness
 ⚠️Limitations 
●  Historical Pattern Dependency  - Algorithm effectiveness relies on historical patterns that may not repeat in changing market conditions
●  Computational Intensity  - Complex calculations may impact chart performance on lower-end devices or with multiple indicators
●  Probability Estimates  - Reaction probabilities are statistical estimates and do not guarantee actual market outcomes
●  Session Sensitivity  - Performance may vary significantly between different market sessions and volatility regimes
●  Parameter Sensitivity  - Results can be highly dependent on input parameters requiring optimization for different instruments
 💡What Makes This Unique 
●  CNN Architecture  - First indicator to apply convolutional neural network principles to institutional-level detection
●  Real-Time ML Scoring  - Live machine learning probability calculations for each zone interaction
●  Advanced Zone Management  - Sophisticated algorithms for zone lifecycle management and automatic optimization
●  Statistical Rigor  - Comprehensive 9-factor logistic regression model with extensive backtesting validation
●  Performance Optimization  - Efficient processing algorithms designed for real-time trading applications
 🔬How It Works 
●  Multi-timeframe pivot identification  - Uses configurable sensitivity parameters for advanced pivot detection
●  ATR-normalized strength calculations  - Standardizes pivot significance across different volatility regimes
●  Volume Z-score integration  - Enhanced pivot weighting based on time-of-day volume patterns
●  Price level clustering  - Neural network binning algorithms with ATR-based sizing for zone creation
●  Recency decay applications  - Weights recent pivots more heavily than historical data for relevance
●  Statistical filtering  - Eliminates low-significance price levels and reduces market noise
●  Dynamic zone generation  - Creates zones from statistically significant pivot clusters with minimum support thresholds
●  IoU-based merging algorithms  - Combines overlapping zones while maintaining accuracy using Intersection over Union
●  Adaptive decay systems  - Automatic removal of outdated or low-performing zones for optimal performance
●  9-factor logistic regression  - Incorporates distance, width, volume, VWAP, touch history, and trend analysis
●  Real-time scoring updates  - Zone interaction calculations with configurable threshold filtering
●  Optional CNN filters  - Gradient detection, smoothing, and Difference of Gaussians processing for enhanced accuracy
 💡Note 
This indicator represents advanced quantitative analysis and should be used by traders familiar with statistical modeling concepts. The probability scores are mathematical estimates based on historical patterns and should be combined with proper risk management and additional technical analysis for optimal trading decisions.
Mean Reversion Probability Zones [BigBeluga]🔵 OVERVIEW 
The  Mean Reversion Probability Zones   indicator measures the likelihood of price  reverting back toward its mean . By analyzing oscillator dynamics (RSI, MFI, or Stochastic), it calculates probability zones both above and below the oscillator. These zones are visualized as histograms, colored regions on the main chart, and a compact dashboard, helping traders spot when the market is statistically stretched and more likely to revert.
 🔵 CONCEPTS 
 
   Mean Reversion : The tendency of price to return to its average after significant extensions.
   Oscillator-Based Analysis : Uses RSI, MFI, or Stochastic as the base signal for detecting overextension.
  
   Probability Model : The probability of reversion is computed using three factors:
 
  Whether the oscillator is rising or declining.
  Whether the oscillator is above or below user-defined thresholds.
  The oscillator’s actual value (distance from equilibrium).
  
 
   Dual-Zone Output :
 
  Upper histogram = probability of downward mean reversion.
  Lower histogram = probability of upward mean reversion.
  
 
   Historical Extremes : The dashboard highlights the recent maximum probability values for both upward and downward scenarios.
  
 
 🔵 FEATURES 
 
   Oscillator Choice : Switch between RSI, MFI, and Stochastic.
   Customizable Zones : User-defined upper/lower thresholds with independent colors.
   Probability Histograms :
 
  Above oscillator → down reversion probability.
  Below oscillator → up reversion probability.
 
   Colored Gradient Zones on Chart : Visual overlays showing where mean reversion probabilities are strongest.
  
   Probability Labels : Percentages displayed next to histogram values for clarity.
  
   Dashboard : Compact table in the corner showing the  recent maximum probabilities  for both upward and downward mean reversion.
   Overlay Compatibility : Works in both chart pane and sub-pane with oscillators.
 
 🔵 HOW TO USE 
 
   Set Oscillator : Choose RSI, MFI, or Stochastic depending on your strategy style.
   Adjust Zones : Define upper/lower bounds for when oscillator values indicate strong overbought/oversold conditions.
   Interpret Histograms :
  Orange (upper) histogram → higher chance of a pullback/downward mean reversion.
  Green (lower) histogram → higher chance of upward reversion/bounce.
   Watch Gradient Zones : On the main chart, shaded areas highlight where probability of mean reversion is elevated.
  
   Consult Dashboard : Use the “Recent MAX” values to understand how strong recent reversion probabilities have been in either direction.
   Confluence Strategy : Combine with support/resistance, order flow, or trend filters to avoid counter-trend trades.
 
 🔵 CONCLUSION 
The  Mean Reversion Probability Zones   provides traders with an advanced way to quantify and visualize mean reversion opportunities. By blending oscillator momentum, threshold logic, and probability calculations, it highlights when markets are statistically stretched and primed for reversal. Whether you are a contrarian trader or simply looking for exhaustion signals to fade, this tool helps bring structure and clarity to mean reversion setups.
Likelihood of Winning - Probability Density FunctionIn developing the "Likelihood of Winning - Probability Density Function (PDF)" indicator, my aim was to offer traders a statistical tool to quantify the probability of reaching target prices. This indicator, grounded in risk assessment principles, enables users to analyze potential outcomes based on the normal distribution, providing insights into market dynamics.
The tool's flexibility allows for customization of the data series, lookback periods, and target settings for both long and short scenarios. It features a color-coded visualization to easily distinguish between probabilities of hitting specified targets, enhancing decision-making in trading strategies.
I'm excited to share this indicator with the trading community, hoping it will enhance data-driven decision-making and offer a deeper understanding of market risks and opportunities. My goal is to continuously improve this tool based on user feedback and market evolution, contributing to more informed trading practices.
This indicator leverages the "NormalDistributionFunctions" library, enabling easy integration into other indicators or strategies. Users can readily embed advanced statistical analysis into their trading tools, fostering innovation within the Pine Script community.
BUY & SELL Probability (M5..D1) - MTFMTF Probability Indicator (M5 to D1)
Indicator — Dual Histogram with Buy/Sell Labels
This indicator is designed to provide a probabilistic bias for bullish or bearish conditions by combining three different analytical components across multiple timeframes. The goal is to reduce noise from single-indicator signals and instead highlight confluence where trend, momentum, and strength agree.
Why this combination is useful
- EMA(200) Trend Filter: Identifies whether price is trading above or below a widely used long-term moving average.
- MACD Momentum: Detects short-term directional momentum through line crossovers.
- ADX Strength: Measures how strong the trend is, preventing signals in weak or flat markets.
By combining these, the indicator avoids situations where one tool signals a trade but others do not, helping to filter out low-probability setups.
How it works
- Each timeframe (M5, M15, H1, H4, D1) generates its own trend, momentum, and strength score.
- Scores are weighted according to user-defined importance and then aggregated into a single probability.
- Proximity to recent support and resistance levels can adjust the final score, accounting for nearby barriers.
- The final probability is displayed as:
   - Histogram (subwindow): Green bars for bullish probability >50%, red bars for bearish <50%.
   - On-chart labels: Showing exact buy/sell percentages on the last bar for quick reference.
Inputs
- EMA length (default 200), MACD settings, ADX period.
- Weights for each timeframe and component (trend, momentum, strength).
- Optional boost for the chart’s current timeframe.
- Smoothing length for probability values.
- Lookback period for support/resistance adjustment.
How to use it
- A green histogram above zero indicates bullish probability >50%.
- A red histogram below zero indicates bearish probability >50%.
- Neutral readings near 50% show low confluence and may be best avoided.
- Users can adjust weights to emphasize higher or lower timeframes, depending on their trading style.
Notes
- This script does not guarantee profitable trades.
- Best used together with price action, volume, or additional confirmation tools.
- Signals are calculated only on closed bars to avoid repainting.
- For testing and learning purposes — not financial advice.
Stop Loss vs Take Profit Probability and EVThis stop loss and take profit calculator uses a Monte Carlo simulation to calculate the probability of hitting your Stop Loss or Take Profit levels across different time horizons (expressed in bars). 
It provides data-driven insights to optimize your risk management and position sizing by showing Expected Value for each scenario.
As a quant, I love using statistical data to help my decisions and get better EV from my trades. 
 🔬 How It's Calculated 
 
 Monte Carlo Simulation: Runs 1,000-10,000 price simulations using a random walk model
 Volatility Analysis: Combines ATR-based and Historical Volatility for accurate price movement modeling
 Expected Value: Calculates profit/loss expectation using formula: (TP_Probability × Reward) - (SL_Probability × Risk)
 Time Horizons: Tests multiple timeframes (1, 5, 10, 20, 50 bars) to find optimal holding periods
 Risk/Reward Ratios: Automatically calculates and displays R:R ratios for quick assessment
 
 💡 Use Cases 
 
 Position Sizing - Determine optimal risk per trade based on Expected Value
 Time Horizon Optimization - Find the best holding period for your strategy
 Stop Loss Placement - Validate SL levels using probability analysis
 Take Profit Optimization - Set TP levels with statistical backing
 Strategy Backtesting - Compare different R:R setups before entering trades
 Risk Management - Avoid trades with negative Expected Value
 Swing vs Day Trading - Choose timeframes with highest success probability
 
 🎯 How to Use 
 
 Setup Trade: Enter your entry price, stop loss, and take profit levels
 You can add or remove time horizons denominated in bars. Say you are looking at 1h candles, adding a 24-bar time horizon means you are looking into 24 hours
 Choose Direction: Select Long or Short position
 Review Table
 Analyze Expected Value: Focus on positive EV scenarios (green background)
 Optimize Timing: Select time horizons with best risk/reward profile
 Adjust Parameters: Modify volatility calculation method and simulation count if needed
 
 Examples 
Here's how you can read the tables.
Example 1:
  
In this chart, we are analyzing the TP and SL probabilities as well as the EV (expected value) for a stock. I want to check what the likelihood is that my SL and TP get triggered over the next 5 days. The stock market is open for 6.5 hours per day, which is 13 bars in this 30-minute bar chart. 26 bars is 2 days, 39 bars is 3 days and so on. 
Although this trade is more likely to trigger my SL than my TP, in some of the time horizons we have a positive expected value because of the risk/reward of our trade (i.e. distance of the SL and TP from the price) and the probability of hitting SL and TP. 
Example 2:
  
In this example, we have applied the indicator to gold. Because the TP is much closer to the price, the probability of hitting the TP is much higher. 
We can also observe that the expected Value in the shorter time frames is better than in the longer ones. This can give us some clues to set up our trade. If we know that the EV is positive, we can allocate more to that specific trade. 
Enjoy, and please let me know your feedback! 😊🥂
Advanced Range Analyzer ProAdvanced Range Analyzer Pro – Adaptive Range Detection & Breakout Forecasting 
 Overview 
Advanced Range Analyzer Pro is a comprehensive trading tool designed to help traders identify consolidations, evaluate their strength, and forecast potential breakout direction. By combining volatility-adjusted thresholds, volume distribution analysis, and historical breakout behavior, the indicator builds an adaptive framework for navigating sideways price action. Instead of treating ranges as noise, this system transforms them into opportunities for mean reversion or breakout trading.
  
 How It Works 
The indicator continuously scans price action to identify active range environments. Ranges are defined by volatility compression, repeated boundary interactions, and clustering of volume near equilibrium. Once detected, the indicator assigns a strength score (0–100), which quantifies how well-defined and compressed the consolidation is.
Breakout probabilities are then calculated by factoring in:
 
 Relative time spent near the upper vs. lower range boundaries
 Historical breakout tendencies for similar structures
 Volume distribution inside the range
 Momentum alignment using auxiliary filters (RSI/MACD)
 
This creates a live probability forecast that updates as price evolves. The tool also supports range memory, allowing traders to analyze the last completed range after a breakout has occurred. A dynamic strength meter is displayed directly above each consolidation range, providing real-time insight into range compression and breakout potential.
 Signals and Breakouts 
Advanced Range Analyzer Pro includes a structured set of visual tools to highlight actionable conditions:
 
 Range Zones  – Gradient-filled boxes highlight active consolidations.
 Strength Meter  – A live score displayed in the dashboard quantifies compression.
 Breakout Labels  – Probability percentages show bias toward bullish or bearish continuation.
 Breakout Highlights  – When a breakout occurs, the range is marked with directional confirmation.
 Dashboard Table  – Displays current status, strength, live/last range mode, and probabilities.
 
These elements update in real time, ensuring that traders always see the current state of consolidation and breakout risk.
 Interpretation 
 Range Strength : High scores (70–100) indicate strong consolidations likely to resolve explosively, while low scores suggest weak or choppy ranges prone to false signals.
 Breakout Probability : Directional bias greater than 60% suggests meaningful breakout pressure. Equal probabilities indicate balanced compression, favoring mean-reversion strategies.
 Market Context : Ranges aligned with higher timeframe trends often resolve in the dominant direction, while counter-trend ranges may lead to reversals or liquidity sweeps.
 Volatility Insight : Tight ranges with low ATR imply imminent expansion; wide ranges signal extended consolidation or distribution phases.
 Strategy Integration 
Advanced Range Analyzer Pro can be applied across multiple trading styles:
 
 Breakout Trading : Enter on probability shifts above 60% with confirmation of volume or momentum.
 Mean Reversion : Trade inside ranges with high strength scores by fading boundaries and targeting equilibrium.
 Trend Continuation : Focus on ranges that form mid-trend, anticipating continuation after consolidation.
 Liquidity Sweeps : Use failed breakouts at boundaries to capture reversals.
 Multi-Timeframe : Apply on higher timeframes to frame market context, then execute on lower timeframes.
 
 Advanced Techniques 
 
 Combine with volume profiles to identify areas of institutional positioning within ranges.
 Track sequences of strong consolidations for trend development or exhaustion signals.
 Use breakout probability shifts in conjunction with order flow or momentum indicators to refine entries.
 Monitor expanding/contracting range widths to anticipate volatility cycles.
 
Custom parameters allow fine-tuning sensitivity for different assets (crypto, forex, equities) and trading styles (scalping, intraday, swing).
Inputs and Customization
 
 Range Detection Sensitivity : Controls how strictly ranges are defined.
 Strength Score Settings : Adjust weighting of compression, volume, and breakout memory.
 Probability Forecasting : Enable/disable directional bias and thresholds.
 Gradient & Fill Options : Customize range visualization colors and opacity.
 Dashboard Display : Toggle live vs last range, info table size, and position.
 Breakout Highlighting : Choose border/zone emphasis on breakout events.
 
 Why Use Advanced Range Analyzer Pro 
This indicator provides a data-driven approach to trading consolidation phases, one of the most common yet underutilized market states. By quantifying range strength, mapping probability forecasts, and visually presenting risk zones, it transforms uncertainty into clarity.
Whether you’re trading breakouts, fading ranges, or mapping higher timeframe context, Advanced Range Analyzer Pro delivers a structured, adaptive framework that integrates seamlessly into multiple strategies.
Seasonality Monte Carlo Forecaster [BackQuant]Seasonality Monte Carlo Forecaster  
 Plain-English overview 
This tool projects a cone of plausible future prices by combining two ideas that traders already use intuitively: seasonality and uncertainty. It watches how your market typically behaves around this calendar date, turns that seasonal tendency into a small daily “drift,” then runs many randomized price paths forward to estimate where price could land tomorrow, next week, or a month from now. The result is a probability cone with a clear expected path, plus optional overlays that show how past years tended to move from this point on the calendar. It is a planning tool, not a crystal ball: the goal is to quantify ranges and odds so you can size, place stops, set targets, and time entries with more realism.
 What Monte Carlo is and why quants rely on it 
•  Definition . Monte Carlo simulation is a way to answer “what might happen next?” when there is randomness in the system. Instead of producing a single forecast, it generates thousands of alternate futures by repeatedly sampling random shocks and adding them to a model of how prices evolve.
•  Why it is used . Markets are noisy. A single point forecast hides risk. Monte Carlo gives a  distribution  of outcomes so you can reason in probabilities: the median path, the 68% band, the 95% band, tail risks, and the chance of hitting a specific level within a horizon.
•  Core strengths in quant finance .
–  Path-dependent questions : “What is the probability we touch a stop before a target?” “What is the expected drawdown on the way to my objective?”
–  Pricing and risk : Useful for path-dependent options, Value-at-Risk (VaR), expected shortfall (CVaR), stress paths, and scenario analysis when closed-form formulas are unrealistic.
–  Planning under uncertainty : Portfolio construction and rebalancing rules can be tested against a cloud of plausible futures rather than a single guess.
•  Why it fits trading workflows . It turns gut feel like “seasonality is supportive here” into quantitative ranges: “median path suggests +X% with a 68% band of ±Y%; stop at Z has only ~16% odds of being tagged in N days.”
 How this indicator builds its probability cone 
 1) Seasonal pattern discovery 
The script builds two day-of-year maps as new data arrives:
• A  return map  where each calendar day stores an exponentially smoothed average of that day’s log return (yesterday→today). The smoothing (90% old, 10% new) behaves like an EWMA, letting older seasons matter while adapting to new information.
• A  volatility map  that tracks the typical absolute return for the same calendar day.
It calculates the day-of-year carefully (with leap-year adjustment) and indexes into a 365-slot seasonal array so “March 18” is compared with past March 18ths. This becomes the  seasonal bias  that gently nudges simulations up or down on each forecast day.
 2) Choice of randomness engine 
You can pick how the future shocks are generated:
•  Daily mode  uses a Gaussian draw with the seasonal bias as the mean and a volatility that comes from realized returns, scaled down to avoid over-fitting. It relies on the Box–Muller transform internally to turn two uniform random numbers into one normal shock.
•  Weekly mode  uses  bootstrap sampling  from the seasonal return history (resampling actual historical daily drifts and then blending in a fraction of the seasonal bias). Bootstrapping is robust when the empirical distribution has asymmetry or fatter tails than a normal distribution.
Both modes seed their random draws deterministically per path and day, which makes plots reproducible bar-to-bar and avoids flickering bands.
 3) Volatility scaling to current conditions 
Markets do not always live in average volatility. The engine computes a simple  volatility factor  from ATR(20)/price and scales the simulated shocks up or down within sensible bounds (clamped between 0.5× and 2.0×). When the current regime is quiet, the cone narrows; when ranges expand, the cone widens. This prevents the classic mistake of projecting calm markets into a storm or vice versa.
 4) Many futures, summarized by percentiles 
The model generates a matrix of price paths (capped at 100 runs for performance inside TradingView), each path stepping forward for your selected horizon. For each forecast day it sorts the simulated prices and pulls key percentiles:
•  5th and 95th  → approximate 95% band (outer cone).
•  16th and 84th  → approximate 68% band (inner cone).
•  50th  → the median or “expected path.”
These are drawn as polylines so you can immediately see central tendency and dispersion.
 5) A historical overlay (optional) 
Turn on the overlay to sketch a dotted path of what a purely seasonal projection would look like for the next ~30 days using only the return map, no randomness. This is not a forecast; it is a visual reminder of the seasonal drift you are biasing toward.
 Inputs you control and how to think about them 
 Monte Carlo Simulation 
•  Price Series for Calculation . The source series, typically close.
•  Enable Probability Forecasts . Master switch for simulation and drawing.
•  Simulation Iterations . Requested number of paths to run. Internally capped at 100 to protect performance, which is generally enough to estimate the percentiles for a trading chart. If you need ultra-smooth bands, shorten the horizon.
•  Forecast Days Ahead . The length of the cone. Longer horizons dilute seasonal signal and widen uncertainty.
•  Probability Bands . Draw all bands, just 95%, just 68%, or a custom level (display logic remains 68/95 internally; the custom number is for labeling and color choice).
•  Pattern Resolution .  Daily  leans on day-of-year effects like “turn-of-month” or holiday patterns.  Weekly  biases toward day-of-week tendencies and bootstraps from history.
•  Volatility Scaling . On by default so the cone respects today’s range context.
 Plotting & UI 
•  Probability Cone . Plots the outer and inner percentile envelopes.
•  Expected Path . Plots the median line through the cone.
•  Historical Overlay . Dotted seasonal-only projection for context.
•  Band Transparency/Colors . Customize primary (outer) and secondary (inner) band colors and the mean path color. Use higher transparency for cleaner charts.
 What appears on your chart 
• A  cone  starting at the most recent bar, fanning outward. The outer lines are the ~95% band; the inner lines are the ~68% band.
• A  median path  (default blue) running through the center of the cone.
• An  info panel  on the final historical bar that summarizes simulation count, forecast days, number of seasonal patterns learned, the current day-of-year, expected percentage return to the median, and the approximate 95% half-range in percent.
• Optional  historical seasonal path  drawn as dotted segments for the next 30 bars.
 How to use it in trading 
 1) Position sizing and stop logic 
The cone translates “volatility plus seasonality” into distances.
• Put stops  outside  the inner band if you want only ~16% odds of a stop-out due to noise before your thesis can play.
• Size positions so that a test of the inner band is survivable and a test of the outer band is rare but acceptable.
• If your target sits  inside  the 68% band at your horizon, the payoff is likely modest; outside the 68% but inside the 95% can justify “one-good-push” trades; beyond the 95% band is a low-probability flyer—consider scaling plans or optionality.
 2) Entry timing with seasonal bias 
When the median path slopes up from this calendar date and the cone is relatively narrow, a pullback toward the lower inner band can be a high-quality entry with a tight invalidation. If the median slopes down, fade rallies toward the upper band or step aside if it clashes with your system.
 3) Target selection 
Project your time horizon to N bars ahead, then pick targets around the median or the opposite inner band depending on your style. You can also anchor dynamic take-profits to the moving median as new bars arrive.
 4) Scenario planning & “what-ifs” 
Before events, glance at the cone: if the 95% band already spans a huge range, trade smaller, expect whips, and avoid placing stops at obvious band edges. If the cone is unusually tight, consider breakout tactics and be ready to add if volatility expands beyond the inner band with follow-through.
 5) Options and vol tactics 
•  When the cone is tight : Prefer long gamma structures (debit spreads) only if you expect a regime shift; otherwise premium selling may dominate.
•  When the cone is wide : Debit structures benefit from range; credit spreads need wider wings or smaller size. Align with your separate IV metrics.
 Reading the probability cone like a pro 
•  Cone slope  = seasonal drift. Upward slope means the calendar has historically favored positive drift from this date, downward slope the opposite.
•  Cone width  = regime volatility. A widening fan tells you that uncertainty grows fast; a narrow cone says the market typically stays contained.
•  Mean vs. price gap . If spot trades well above the median path and the upper band, mean-reversion risk is high. If spot presses the lower inner band in an up-sloping cone, you are in the “buy fear” zone.
•  Touches and pierces . Touching the inner band is common noise; piercing it with momentum signals potential regime change; the outer band should be rare and often brings snap-backs unless there is a structural catalyst.
 Methodological notes (what the code actually does) 
•  Log returns  are used for additivity and better statistical behavior: sim_ret is applied via exp(sim_ret) to evolve price.
•  Seasonal arrays  are updated online with EWMA (90/10) so the model keeps learning as each bar arrives.
•  Leap years  are handled; indexing still normalizes into a 365-slot map so the seasonal pattern remains stable.
•  Gaussian engine  (Daily mode) centers shocks on the seasonal bias with a conservative standard deviation.
•  Bootstrap engine  (Weekly mode) resamples from observed seasonal returns and adds a fraction of the bias, which captures skew and fat tails better.
•  Volatility adjustment  multiplies each daily shock by a factor derived from ATR(20)/price, clamped between 0.5 and 2.0 to avoid extreme cones.
•  Performance guardrails : simulations are capped at 100 paths; the probability cone uses polylines (no heavy fills) and only draws on the last confirmed bar to keep charts responsive.
•  Prerequisite data : at least ~30 seasonal entries are required before the model will draw a cone; otherwise it waits for more history.
 Strengths and limitations 
•  Strengths :
– Probabilistic thinking replaces single-point guessing.
– Seasonality adds a small but meaningful directional bias that many markets exhibit.
– Volatility scaling adapts to the current regime so the cone stays realistic.
•  Limitations :
– Seasonality can break around structural changes, policy shifts, or one-off events.
– The number of paths is performance-limited; percentile estimates are good for trading, not for academic precision.
– The model assumes tomorrow’s randomness resembles recent randomness; if regime shifts violently, the cone will lag until the EWMA adapts.
– Holidays and missing sessions can thin the seasonal sample for some assets; be cautious with very short histories.
 Tuning guide 
•  Horizon : 10–20 bars for tactical trades; 30+ for swing planning when you care more about broad ranges than precise targets.
•  Iterations : The default 100 is enough for stable 5/16/50/84/95 percentiles. If you crave smoother lines, shorten the horizon or run on higher timeframes.
•  Daily vs. Weekly : Daily for equities and crypto where month-end and turn-of-month effects matter; Weekly for futures and FX where day-of-week behavior is strong.
•  Volatility scaling : Keep it on. Turn off only when you intentionally want a “pure seasonality” cone unaffected by current turbulence.
 Workflow examples 
•  Swing continuation : Cone slopes up, price pulls into the lower inner band, your system fires. Enter near the band, stop just outside the outer line for the next 3–5 bars, target near the median or the opposite inner band.
•  Fade extremes : Cone is flat or down, price gaps to the upper outer band on news, then stalls. Favor mean-reversion toward the median, size small if volatility scaling is elevated.
•  Event play : Before CPI or earnings on a proxy index, check cone width. If the inner band is already wide, cut size or prefer options structures that benefit from range.
 Good habits 
• Pair the cone with your entry engine (breakout, pullback, order flow). Let Monte Carlo do range math; let your system do signal quality.
• Do not anchor blindly to the median; recalc after each bar. When the cone’s slope flips or width jumps, the plan should adapt.
• Validate seasonality for your symbol and timeframe; not every market has strong calendar effects.
 Summary 
The Seasonality Monte Carlo Forecaster wraps institutional risk planning into a single overlay: a data-driven seasonal drift, realistic volatility scaling, and a probabilistic cone that answers “where could we be, with what odds?” within your trading horizon. Use it to place stops where randomness is less likely to take you out, to set targets aligned with realistic travel, and to size positions with confidence born from distributions rather than hunches. It will not predict the future, but it will keep your decisions anchored to probabilities—the language markets actually speak.
Markov Chain Trend ProbabilityA Markov Chain is a mathematical model that predicts future states based on the current state, assuming that the future depends only on the present (not the past). Originally developed by Russian mathematician Andrey Markov, this concept is widely used in:
 
 Finance: Risk modeling, portfolio optimization, credit scoring, algorithmic trading
 Weather Forecasting: Predicting sunny/rainy days, temperature patterns, storm tracking
 
Here's an example of a Markov chain: If the weather is sunny, the probability that will be sunny 30 min later is say 90%. However, if the state changes, i.e. it starts raining, how the probability that will be raining 30 min later is say 70% and only 30% sunny. 
Similar concept can be applied to markets price action and trends. 
 Mathematical Foundation 
The core principle follows the Markov Property: P(X_{t+1}|X_t, X_{t-1}, ..., X_0) = P(X_{t+1}|X_t)
Transition Matrix : 
-------------Next State
Current----     
 --------P11    P12
 -----P21    P22
Probability Calculations:
P(Up→Up) = Count(Up→Up) / Count(Up states)
P(Down→Down) = Count(Down→Down) / Count(Down states)
Steady-state probability: π = πP (where π is the stationary distribution)
State Definition:
State = UPTREND if (Price_t - Price_{t-n})/ATR > threshold
State = DOWNTREND if (Price_t - Price_{t-n})/ATR < -threshold
 How It Works in Trading 
This indicator applies Markov Chain theory to market trends by:
 
 Defining States: Classifies market conditions as UPTREND or DOWNTREND based on price movement relative to ATR (Average True Range)
 Learning Transitions: Analyzes historical data to calculate probabilities of moving from one state to another
 Predicting Probabilities: Estimates the likelihood of future trend continuation or reversal
 
 How to Use 
Parameters:
 
 Lookback Period: Number of bars to analyze for trend detection (default: 14)
 ATR Threshold: Sensitivity multiplier for state changes (default: 0.5)
 Historical Periods: Sample size for probability calculations (default: 33)
 
 Trading Applications: 
 
 Trend confirmation for entry/exit decisions
 Risk assessment through probability analysis
 Market regime identification 
 Early warning system for potential trend reversals
 
The indicator works on any timeframe and asset class. Enjoy!
Risk Distribution HistogramStatistical risk visualization and analysis tool for any ticker 📊 
The Risk Distribution Histogram visualizes the statistical distribution of different risk metrics for any financial instrument. It converts risk data into histograms with quartile-based color coding, so that traders can understand their risk, tail-risks, exposure patterns and make data-driven decisions based on empirical evidence rather than assumptions.
The indicator supports multiple risk calculation methods, each designed for different aspects of market analysis, from general volatility assessment to tail risk analysis.
 Risk Measurement Methods 
 Standard Deviation 
Captures raw daily price volatility by measuring the dispersion of price movements. Ideal for understanding overall market conditions and timing volatility-based strategies.
Use case: Options trading and volatility analysis.
 Average True Range (ATR) 
Measures true range as a percentage of price, accounting for gaps and limit moves. Valuable for position sizing across different price levels.
Use case: Position sizing and stop-loss placement.
  
The chart above illustrates how ATR statistical distribution can be used by looking at the ATR % of price distribution. For example, 90% of the movements are below 5%.
 Downside Deviation 
Only considers negative price movements, making it ideal for checking downside risk and  capital protection rather than capturing upside volatility.
Use case: Downside protection strategies and stop losses.
 Drawdown Analysis 
Tracks peak-to-trough declines, providing insight into maximum loss potential during different market conditions.
Use case: Risk management and capital preservation.
  
The chart above illustrates tale risk for the asset (TQQQ), showing that it is possible to have drawdowns higher than 20%. 
 Entropy-Based Risk (EVaR) 
Uses information theory to quantify market uncertainty. Higher entropy values indicate more unpredictable price action, valuable for detecting regime changes.
Use case: Advanced risk modeling and tail-risk.
 VIX Histogram 
Incorporates the market's fear index directly into analysis, showing how current volatility expectations compare to historical patterns. The  CAPITALCOM:VIX  histogram is independent from the ticker on the chart. 
Use case: Volatility trading and market timing.
 Visual Features 
The histogram uses quartile-based color coding that immediately shows where current risk levels stand relative to historical patterns:
 
 Green (Q1): Low Risk (0-25th percentile)
 Yellow (Q2): Medium-Low Risk (25-50th percentile)
 Orange (Q3): Medium-High Risk (50-75th percentile)
 Red (Q4): High Risk (75-100th percentile)
 
The data table provides detailed statistics, including:
 
 Count Distribution: Historical observations in each bin
 PMF: Percentage probability for each risk level
 CDF: Cumulative probability up to each level
 Current Risk Marker: Shows your current position in the distribution
 
 Trading Applications 
When current risk falls into upper quartiles (Q3 or Q4), it signals conditions are riskier than 50-75% of historical observations. This guides position sizing and portfolio adjustments.
Key applications:
 
 Position sizing based on empirical risk distributions
 Monitoring risk regime changes over time
 Comparing risk patterns across timeframes
 
Risk distribution analysis improves trade timing by identifying when market conditions favor specific strategies.
 
 Enter positions during low-risk periods (Q1)
 Reduce exposure in high-risk periods (Q4)
 Use percentile rankings for dynamic stop-loss placement
 Time volatility strategies using distribution patterns
 Detect regime shifts through distribution changes
 Compare current conditions to historical benchmarks
 Identify outlier events in tail regions
 Validate quantitative models with empirical data
 
 Configuration Options 
Data Collection
 
 Lookback Period: Control amount of historical data analyzed
 Date Range Filtering: Focus on specific market periods
 Sample Size Validation: Automatic reliability warnings
 
Histogram Customization
 
 Bin Count: 10-50 bins for different detail levels
 Auto/Manual Bin Width: Optimize for your data range
 Visual Preferences: Custom colors and font sizes
 
 Implementation Guide 
Start with Standard Deviation on daily charts for the most intuitive introduction to distribution-based risk analysis.
 
 Method Selection: Begin with Standard Deviation
 Setup: Use daily charts with 20-30 bins
 Interpretation: Focus on quartile transitions as signals
 Monitoring: Track distribution changes for regime detection
 
The tool provides comprehensive statistics including mean, standard deviation, quartiles, and current position metrics like Z-score and percentile ranking.
Enjoy, and please let me know your feedback! 😊🥂
Liquidity Break Probability [PhenLabs]📊 Liquidity Break Probability  
 Version:  PineScript™ v6
The Liquidity Break Probability indicator revolutionizes how traders approach liquidity levels by providing real-time probability calculations for level breaks. This advanced indicator combines sophisticated market analysis with machine learning inspired probability models to predict the likelihood of high/low breaks before they happen.
Unlike traditional liquidity indicators that simply draw lines, LBP analyzes market structure, volume profiles, momentum, volatility, and sentiment to generate dynamic break probabilities ranging from 5% to 95%. This gives traders unprecedented insight into which levels are most likely to hold or break, enabling more confident trading decisions.
 🚀 Points of Innovation 
 
  Advanced 6-factor probability model weighing market structure, volatility, volume, momentum, patterns, and sentiment
  Real-time probability updates that adjust as market conditions change
  Intelligent trading style presets (Scalping, Day Trading, Swing Trading) with optimized parameters
  Dynamic color-coded probability labels showing break likelihood percentages
  Professional tiered input system - from quick setup to expert-level customization
  Smart volume filtering that only highlights levels with significant institutional interest
 
 🔧 Core Components 
 
   Market Structure Analysis:  Evaluates trend alignment, level strength, and momentum buildup using EMA crossovers and price action
   Volatility Engine:  Incorporates ATR expansion, Bollinger Band positioning, and price distance calculations
   Volume Profile System:  Analyzes current volume strength, smart money proxies, and level creation volume ratios
   Momentum Calculator:  Combines RSI positioning, MACD strength, and momentum divergence detection
   Pattern Recognition:  Identifies reversal patterns (doji, hammer, engulfing) near key levels
   Sentiment Analysis:  Processes fear/greed indicators and market breadth measurements
 
 🔥 Key Features 
 
   Dynamic Probability Labels:  Real-time percentage displays showing break probability with color coding (red >70%, orange >50%, white <50%)
   Trading Style Optimization:  One-click presets automatically configure sensitivity and parameters for your trading timeframe
   Professional Dashboard:  Live market state monitoring with nearest level tracking and active level counts
   Smart Alert System:  Customizable proximity alerts and high-probability break notifications
   Advanced Level Management:  Intelligent line cleanup and historical analysis options
   Volume-Validated Levels:  Only displays levels backed by significant volume for institutional-grade analysis
 
 🎨 Visualization 
 
   Recent Low Lines:  Red lines marking validated support levels with probability percentages
   Recent High Lines:  Blue lines showing resistance zones with break likelihood indicators
   Probability Labels:  Color-coded percentage labels that update in real-time
   Professional Dashboard:  Customizable panel showing market state, active levels, and current price
   Clean Display Modes:  Toggle between active-only view for clean charts or historical view for analysis
 
 📖 Usage Guidelines 
 Quick Setup 
 
   Trading Style Preset 
    Default: Day Trading
    Options: Scalping, Day Trading, Swing Trading, Custom
    Description: Automatically optimizes all parameters for your preferred trading timeframe and style
   Show Break Probability % 
    Default: True
    Description: Displays percentage labels next to each level showing break probability
   Line Display 
    Default: Active Only
    Options: Active Only, All Levels
    Description: Choose between clean active-only view or comprehensive historical analysis
 
 Level Detection Settings 
 
   Level Sensitivity 
    Default: 5
    Range: 1-20
    Description: Lower values show more levels (sensitive), higher values show fewer levels (selective)
   Volume Filter Strength 
    Default: 2.0
    Range: 0.5-5.0
    Description: Controls minimum volume threshold for level validation
 
 Advanced Probability Model 
 
   Market Trend Influence 
    Default: 25%
    Range: 0-50%
    Description: Weight given to overall market trend in probability calculations
   Volume Influence 
    Default: 20%
    Range: 0-50%
    Description: Impact of volume analysis on break probability
 
 ✅ Best Use Cases 
 
  Identifying high-probability breakout setups before they occur
  Determining optimal entry and exit points near key levels
  Risk management through probability-based position sizing
  Confluence trading when multiple high-probability levels align
  Scalping opportunities at levels with low break probability
  Swing trading setups using high-probability level breaks
 
 ⚠️ Limitations 
 
  Probability calculations are estimations based on historical patterns and current market conditions
  High-probability setups do not guarantee successful trades - risk management is essential
  Performance may vary significantly across different market conditions and asset classes
  Requires understanding of support/resistance concepts and probability-based trading
  Best used in conjunction with other analysis methods and proper risk management
 
 💡 What Makes This Unique 
 
   Probability-Based Approach:  First indicator to provide quantitative break probabilities rather than simple S/R lines
   Multi-Factor Analysis:  Combines 6 different market factors into a comprehensive probability model
   Adaptive Intelligence:  Probabilities update in real-time as market conditions change
   Professional Interface:  Tiered input system from beginner-friendly to expert-level customization
   Institutional-Grade Filtering:  Volume validation ensures only significant levels are displayed
 
 🔬 How It Works 
1.  Level Detection: 
    
     Identifies pivot highs and lows using configurable sensitivity settings
     Validates levels with volume analysis to ensure institutional significance
    
2.  Probability Calculation: 
    
     Analyzes 6 key market factors: structure, volatility, volume, momentum, patterns, sentiment
     Applies weighted scoring system based on user-defined factor importance
     Generates probability score from 5% to 95% for each level
    
3.  Real-Time Updates: 
    
     Continuously monitors price action and market conditions
     Updates probability calculations as new data becomes available
     Adjusts for level touches and changing market dynamics
    
 💡 Note:  This indicator works best on timeframes from 1-minute to 4-hour charts. For optimal results, combine with proper risk management and consider multiple timeframe analysis. The probability calculations are most accurate in trending markets with normal to high volatility conditions.
Leavitt Convolution ProbabilityTechnical Analysis of Markets with Leavitt Market Projections and Associated Convolution Probability 
The aim of this study is to present an innovative approach to market analysis based on the research "Leavitt Market Projections." This technical tool combines one indicator and a probability function to enhance the accuracy and speed of market forecasts.
 Key Features 
 Advanced Indicators : the script includes the Convolution line and a probability oscillator, designed to anticipate market changes. These indicators provide timely signals and offer a clear view of price dynamics.
 Convolution Probability Function : The Convolution Probability (CP) is a key element of the script. A significant increase in this probability often precedes a market decline, while a decrease in probability can signal a bullish move.  The Convolution Probability Function:
 
   At each bar, i, the linear regression routine finds the two parameters for the straight line: y=mix+bi.
     Standard deviations can be calculated from the sequence of slopes, {mi}, and intercepts, {bi}.
     Each standard deviation has a corresponding probability.
     Their adjusted product is the Convolution Probability, CP. The construction of the Convolution Probability is straightforward. The adjusted product is the probability of one times 1− the probability of the other.
 
 Customizable Settings : Users can define oversold and overbought levels, as well as set an offset for the linear regression calculation. These options allow for tailoring the script to individual trading strategies and market conditions.
 Statistical Analysis : Each analyzed bar generates regression parameters that allow for the calculation of standard deviations and associated probabilities, providing an in-depth view of market dynamics.
The results from applying this technical tool show increased accuracy and speed in market forecasts. The combination of Convolution indicator and the probability function enables the identification of turning points and the anticipation of market changes.
Additional information:
 
     Leavitt, in his study, considers the SPY chart.
     When the Convolution Probability (CP) is high, it indicates that the probability P1 (related to the slope) is high, and conversely, when CP is low, P1 is low and P2 is high.
     For the calculation of probability, an approximate formula of the Cumulative Distribution Function (CDF) has been used, which is given by: CDF(x)=21(1+erf(σ2x−μ)) where μ is the mean and σ is the standard deviation.
    For the calculation of probability, the formula used in this script is: 0.5 * (1 + (math.sign(zSlope) * math.sqrt(1 - math.exp(-0.5 * zSlope * zSlope)))) 
 
 Conclusions 
This study presents the approach to market analysis based on the research "Leavitt Market Projections." The script combines Convolution indicator and a Probability function to provide more precise trading signals. The results demonstrate greater accuracy and speed in market forecasts, making this technical tool a valuable asset for market participants.
Probability Grid [LuxAlgo]The  Probability Grid  tool allows traders to see the probability of where and when the next reversal would occur, it displays a 10x10 grid and/or dashboard with the probability of the next reversal occurring beyond each cell or within each cell.
🔶  USAGE 
  
By default, the tool displays deciles (percentiles from 0 to 90), users can enable, disable and modify each percentile, but two of them must always be enabled or the tool will display an error message alerting of it.
  
The use of the tool is quite simple, as shown in the chart above, the further the price moves on the grid, the higher the probability of a reversal.
In this case, the reversal took place on the cell with a probability of 9%, which means that there is a probability of 91% within the square defined by the last reversal and this cell.
🔹  Grid vs Dashboard 
  
The tool can display a grid starting from the last reversal and/or a dashboard at three predefined locations, as shown in the chart above.
🔶  DETAILS 
🔹  Raw Data vs Normalized Data 
  
By default the tool displays the normalized data, this means that instead of using the raw data (price delta between reversals) it uses the returns between each reversal, this is useful to make an apples to apples comparison of all the data in the dataset.
This can be seen in the left side of the chart above (BTCUSD Daily chart) where normalize data is disabled, the percentiles from 0 to 40 overlap and are indistinguishable from each other because the tool uses the raw price delta over the entire bitcoin history, with normalize data enabled as we can see in the right side of the chart we can have a fair comparison of the data over the entire history.
🔹  Probability Beyond or Within Each Cell 
  
Two different probability modes are available, the default mode is Probability Beyond Each Cell, the number displayed in each cell is the probability of the next reversal to be located in the area beyond the cell, for example, if the cell displays 20%, it means that in the area formed by the square starting from the last reversal and ending at the cell, there is an 80% probability and outside that square there is a 20% probability for the location of the next reversal.
The second probability mode is the probability within each cell, this outlines the chance that the next reversal will be within the cell, as we can see on the right chart above, when using deciles as percentiles (default settings), each cell has the same 1% probability for the 10x10 grid.
🔶  SETTINGS 
 
 Swing Length: The maximum length in bars used to identify a swing
 Maximum Reversals: Maximum number of reversals included in calculations
 Normalize Data: Use returns between swings instead of raw price
 Probability: Choose between two different probability modes: beyond and inside each cell
 Percentiles: Enable/disable each of the ten percentiles and select the percentile number and line style
 
🔹  Dashboard 
 
 Show Dashboard: Enable or disable the dashboard
 Position: Choose dashboard location
 Size: Choose dashboard size
 
🔹  Style 
 
 Show Grid: Enable or disable the grid
 Size: Choose grid text size
 Colors: Choose grid background colors
 Show Marks: Enable/disable reversal markers
SuperTrend + Relative Volume (Kernel Optimized)Introducing our new KDE Optimized Supertrend + Relative Volume Indicator! 
This innovative indicator combines the power of the Supertrend indicator along with Relative Volume. It utilizes the Kernel Density Estimation (KDE) to estimate the probability of a candlestick marking a significant trend break or reversal.
 ❓How to Interpret the KDE %: 
The KDE % is a crucial metric that reflects the likelihood that the current candlestick represents a true break in the SuperTrend line, supported by an increase in relative volume. It estimates the probability of a trend shift or continuation based on historical SuperTrend breaks and volume patterns:
Low KDE %: A lower probability that the current break is significant. Price action is less likely to reverse, and the trend may continue.
Moderate KDE - High KDE %: An increased possibility that a trend reversal or consolidation could occur. Traders should start watching for confirmation signals.
 📌How Does It Work? 
The SuperTrend indicator uses the Average True Range (ATR) to determine the direction of the trend and identifies when the price crosses the SuperTrend line, signaling a potential trend reversal. Here's how the KDE Optimized SuperTrend Indicator works:
 
 SuperTrend Calculation: The SuperTrend indicator is calculated, and when the price breaks above (bullish) or below (bearish) the SuperTrend line, it is logged as a significant event.
 Relative Volume: For each break in the SuperTrend line, we calculate the relative volume (current volume vs. the average volume over a defined period). High relative volume can suggest stronger confirmation of the trend break.
 KDE Array Calculation: KDE is applied to the break points and relative volume data:
 Define the KDE options: Bandwidth, Number of Steps, and Array Range (Array Max - Array Min).
 Create a density range array using the defined number of steps, corresponding to potential break points.
 Apply a Gaussian kernel function to the break points and volume data to estimate the likelihood of the trend break being significant.
 KDE Value and Signal Generation: The KDE array is updated as each break occurs. The KDE % is calculated for the breakout candlestick, representing the likelihood of the trend break being significant. If the KDE value exceeds the defined activation threshold, a darker bullish or bearish arrow is plotted after bar confirmation. If the KDE value falls below the threshold, a more transparent arrow is drawn, indicating a possible but lower probability break.
 
 ⚙️Settings: 
SuperTrend Settings:
 
 ATR Length: The period over which the Average True Range (ATR) is calculated.
 Multiplier: The multiplier applied to the ATR to determine the SuperTrend threshold.
 
 KDE Settings: 
 
 Bandwidth: Determines the smoothness of the KDE function and the width of the influence of each break point.
 Number of Bins (Steps): Defines the precision of the KDE algorithm, with higher values offering more detailed calculations.
 KDE Threshold %: The level at which relative volume is considered significant for confirming a break.
 Relative Volume Length: The number of historic candles used in calculating KDE %
Reversal Probability Zone & Levels [LuxAlgo]The  Reversal Probability Zone & Levels  tool allows traders to identify a zone starting from the last detected reversal to highlight the probability of where the next reversal would be from a price and time perspective. 
Price and time levels within the zone are displayed for up to 4 percentiles defined by the user.
🔶  USAGE 
  
By default, the tool displays a zone with the 25th, 50th, 75th and 90th percentiles on both the price and time axis, indicating where, when and how many of the past reversals have occurred.
Traders can select the length for swing detection and the maximum number of reversals for probability calculations. The tool considers both bullish and bearish reversals separately, which means that if the last reversal was a swing high, the zone would show the probabilities for the last defined  Maximum reversals 
The  Maximum reversals  value has a direct impact on the probabilities, the more data traders use the more significant the result, probabilities over 10 occurrences are far weak compared to probabilities over 1000 occurrences.
🔹  Percentiles 
  
Traders can fine-tune the percentile parameters in the settings panel.
A given percentile means that the number of occurrences in the data set is less than or equal to the percentile.
In English, this means
 
 Percentile 20th:  20% of the occurrences are less than or equal to this value, so 80% of the occurrences are greater than this value.
 Percentile 50th:  50% of the occurrences are below and 50% are above this value.
 Percentile 80th:  80% of occurrences are lower than or equal to this value, so 20% of occurrences are greater than this value.
 
🔹  Normalize data 
  
The Normalize Data feature allows traders to make an apples to apples comparison when we have a lot of historical data on high timeframe charts, using returns between swings instead of raw price. 
🔹  Display Style 
  
By default, the tool has the No overlapping feature enabled to display a clean chart, traders can turn it off, but this can fill the chart with too much information and barely see the price.
Traders can enable/disable settings to show only the last zone and the swing markers on the chart.
🔶  SETTINGS 
 
 Swing Length:  The maximum length in bars used to identify a swing
 Maximum Reversals:  Maximum number of reversals included in calculations
 Normalize Data:  Use returns between swings instead of raw price
 Percentiles:  Enable/disable each of the four percentiles and select the percentile number, line style, colors, and size
 
🔹  Style 
 
 No Overlapping Zones:  Enable or disable the No overlap between zones feature
 Show Only Last Zone:  Enable/disable display of last zone only
 Show Marks:  Enable/disable reversal markers
QT RSI [ W.ARITAS ]The  QT RSI   is an innovative technical analysis indicator designed to enhance precision in market trend identification and decision-making. Developed using advanced concepts in quantum mechanics, machine learning (LSTM), and signal processing, this indicator provides actionable insights for traders across multiple asset classes, including stocks, crypto, and forex.
 Key Features: 
 
 Dynamic Color Gradient: Visualizes market conditions for intuitive interpretation:
 Green: Strong buy signal indicating bullish momentum.
 Blue: Neutral or observation zone, suggesting caution or lack of a clear trend.
 Red: Strong sell signal indicating bearish momentum.
 Quantum-Enhanced RSI: Integrates adaptive energy levels, dynamic smoothing, and quantum oscillators for precise trend detection.
 Hybrid Machine Learning Model: Combines LSTM neural networks and wavelet transforms for accurate prediction and signal refinement.
 Customizable Settings: Includes advanced parameters for dynamic thresholds, sensitivity adjustment, and noise reduction using Kalman and Jurik filters.
 
 How to Use: 
 Interpret the Color Gradient: 
 
 Green Zone: Indicates bullish conditions and potential buy opportunities. Look for upward momentum in the RSI plot.
 Blue Zone: Represents a neutral or consolidation phase. Monitor the market for trend confirmation.
 Red Zone: Indicates bearish conditions and potential sell opportunities. Look for downward momentum in the RSI plot.
 
 Follow Overbought/Oversold Boundaries: 
Use the upper and lower RSI boundaries to identify overbought and oversold conditions.
 Leverage Advanced Filtering: 
The smoothed signals and quantum oscillator provide a robust framework for filtering false signals, making it suitable for volatile markets.
Application: Ideal for traders and analysts seeking high-precision tools for:
 Identifying entry and exit points. 
 
 Detecting market reversals and momentum shifts.
 Enhancing algorithmic trading strategies with cutting-edge analytics.
 
GaussianDistributionLibrary   "GaussianDistribution" 
This library defines a custom type `distr` representing a Gaussian (or other statistical) distribution.
It provides methods to calculate key statistical moments and scores, including mean, median, mode, standard deviation, variance, skewness, kurtosis, and Z-scores.
This library is useful for analyzing probability distributions in financial data.
Disclaimer:
I am not a mathematician, but I have implemented this library to the best of my understanding and capacity. Please be indulgent as I tried to translate statistical concepts into code as accurately as possible. Feedback, suggestions, and corrections are welcome to improve the reliability and robustness of this library.
 mean(source, length) 
  Calculate the mean (average) of the distribution
  Parameters:
     source (float) : Distribution source (typically a price or indicator series)
     length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
  Returns: Mean (μ)
 stdev(source, length) 
  Calculate the standard deviation (σ) of the distribution
  Parameters:
     source (float) : Distribution source (typically a price or indicator series)
     length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
  Returns: Standard deviation (σ)
 skewness(source, length, mean, stdev) 
  Calculate the skewness (γ₁) of the distribution
  Parameters:
     source (float) : Distribution source (typically a price or indicator series)
     length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
     mean (float) : the mean (average) of the distribution
     stdev (float) : the standard deviation (σ) of the distribution
@return Skewness (γ₁)
 skewness(source, length) 
  Overloaded skewness to calculate from source and length
  Parameters:
     source (float) : Distribution source (typically a price or indicator series)
     length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Skewness (γ₁)
 mode(mean, stdev, skewness) 
  Estimate mode - Most frequent value in the distribution (approximation based on skewness)
  Parameters:
     mean (float) : the mean (average) of the distribution
     stdev (float) : the standard deviation (σ) of the distribution
     skewness (float) : the skewness (γ₁) of the distribution
@return Mode
 mode(source, length) 
  Overloaded mode to calculate from source and length
  Parameters:
     source (float) : Distribution source (typically a price or indicator series)
     length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Mode
 median(mean, stdev, skewness) 
  Estimate median - Middle value of the distribution (approximation)
  Parameters:
     mean (float) : the mean (average) of the distribution
     stdev (float) : the standard deviation (σ) of the distribution
     skewness (float) : the skewness (γ₁) of the distribution
@return Median
 median(source, length) 
  Overloaded median to calculate from source and length
  Parameters:
     source (float) : Distribution source (typically a price or indicator series)
     length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Median
 variance(stdev) 
  Calculate variance (σ²) - Square of the standard deviation
  Parameters:
     stdev (float) : the standard deviation (σ) of the distribution
@return Variance (σ²)
 variance(source, length) 
  Overloaded variance to calculate from source and length
  Parameters:
     source (float) : Distribution source (typically a price or indicator series)
     length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Variance (σ²)
 kurtosis(source, length, mean, stdev) 
  Calculate kurtosis (γ₂) - Degree of "tailedness" in the distribution
  Parameters:
     source (float) : Distribution source (typically a price or indicator series)
     length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
     mean (float) : the mean (average) of the distribution
     stdev (float) : the standard deviation (σ) of the distribution
@return Kurtosis (γ₂)
 kurtosis(source, length) 
  Overloaded kurtosis to calculate from source and length
  Parameters:
     source (float) : Distribution source (typically a price or indicator series)
     length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Kurtosis (γ₂)
 normal_score(source, mean, stdev) 
  Calculate Z-score (standard score) assuming a normal distribution
  Parameters:
     source (float) : Distribution source (typically a price or indicator series)
     mean (float) : the mean (average) of the distribution
     stdev (float) : the standard deviation (σ) of the distribution
@return Z-Score
 normal_score(source, length) 
  Overloaded normal_score to calculate from source and length
  Parameters:
     source (float) : Distribution source (typically a price or indicator series)
     length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Z-Score
 non_normal_score(source, mean, stdev, skewness, kurtosis) 
  Calculate adjusted Z-score considering skewness and kurtosis
  Parameters:
     source (float) : Distribution source (typically a price or indicator series)
     mean (float) : the mean (average) of the distribution
     stdev (float) : the standard deviation (σ) of the distribution
     skewness (float) : the skewness (γ₁) of the distribution
     kurtosis (float) : the "tailedness" in the distribution
@return Z-Score
 non_normal_score(source, length) 
  Overloaded non_normal_score to calculate from source and length
  Parameters:
     source (float) : Distribution source (typically a price or indicator series)
     length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Z-Score
 method init(this) 
  Initialize all statistical fields of the `distr` type
  Namespace types: distr
  Parameters:
     this (distr) 
 method init(this, source, length) 
  Overloaded initializer to set source and length
  Namespace types: distr
  Parameters:
     this (distr) 
     source (float) 
     length (int) 
 distr 
  Custom type to represent a Gaussian distribution
  Fields:
     source (series float) : Distribution source (typically a price or indicator series)
     length (series int) : Window length for the distribution (must be >= 30 for meaningful statistics)
     mode (series float) : Most frequent value in the distribution
     median (series float) : Middle value separating the greater and lesser halves of the distribution
     mean (series float) : μ (1st central moment) - Average of the distribution
     stdev (series float) : σ or standard deviation (square root of the variance) - Measure of dispersion
     variance (series float) : σ² (2nd central moment) - Squared standard deviation
     skewness (series float) : γ₁ (3rd central moment) - Asymmetry of the distribution
     kurtosis (series float) : γ₂ (4th central moment) - Degree of "tailedness" relative to a normal distribution
     normal_score (series float) : Z-score assuming normal distribution
     non_normal_score (series float) : Adjusted Z-score considering skewness and kurtosis
PDF Smoothed Moving Average [BackQuant]PDF Smoothed Moving Average  
Introducing BackQuant’s PDF Smoothed Moving Average (PDF-MA) — an innovative trading indicator that applies Probability Density Function (PDF) weighting to moving averages, creating a unique, trend-following tool that offers adaptive smoothing to price movements. This advanced indicator gives traders an edge by blending PDF-weighted values with conventional moving averages, helping to capture trend shifts with enhanced clarity.
 Core Concept: Probability Density Function (PDF) Smoothing 
The Probability Density Function (PDF) provides a mathematical approach to applying adaptive weighting to data points based on a specified variance and mean. In the PDF-MA indicator, the PDF function is used to weight price data, adding a layer of probabilistic smoothing that enhances the detection of trend strength while reducing noise.
 The PDF weights are controlled by two key parameters: 
 Variance:  Determines the spread of the weights, where higher values spread out the weighting effect, providing broader smoothing.
 Mean : Centers the weights around a particular price value, influencing the trend’s directionality and sensitivity.
These PDF weights are applied to each price point over the chosen period, creating an adaptive and smooth moving average that more closely reflects the underlying price trend.
 Blending PDF with Standard Moving Averages 
To further improve the PDF-MA, this indicator combines the PDF-weighted average with a traditional moving average, selected by the user as either an Exponential Moving Average (EMA) or Simple Moving Average (SMA). This blended approach leverages the strengths of each method: the responsiveness of PDF smoothing and the robustness of conventional moving averages.
 Smoothing Method:  Traders can choose between EMA and SMA for the additional moving average layer. The EMA is more responsive to recent prices, while the SMA provides a consistent average across the selected period.
 Smoothing Period:  Controls the length of the lookback period, affecting how sensitive the average is to price changes.
The result is a PDF-MA that provides a reliable trend line, reflecting both the PDF weighting and traditional moving average values, ideal for use in trend-following and momentum-based strategies.
 Trend Detection and Candle Coloring 
The PDF-MA includes a built-in trend detection feature that dynamically colors candles based on the direction of the smoothed moving average:
 Uptrend:  When the PDF-MA value is increasing, the trend is considered bullish, and candles are colored green, indicating potential buying conditions.
 Downtrend:  When the PDF-MA value is decreasing, the trend is considered bearish, and candles are colored red, signaling potential selling or shorting conditions.
These color-coded candles provide a quick visual reference for the trend direction, helping traders make real-time decisions based on the current market trend.
 Customization and Visualization Options 
This indicator offers a range of customization options, allowing traders to tailor it to their specific preferences and trading environment:
 Price Source : Choose the price data for calculation, with options like close, open, high, low, or HLC3.
 Variance and Mean : Fine-tune the PDF weighting parameters to control the indicator’s sensitivity and responsiveness to price data.
 Smoothing Method : Select either EMA or SMA to customize the conventional moving average layer used in conjunction with the PDF.
 Smoothing Period : Set the lookback period for the moving average, with a longer period providing more stability and a shorter period offering greater sensitivity.
 Candle Coloring : Enable or disable candle coloring based on trend direction, providing additional clarity in identifying bullish and bearish phases.
 Trading Applications 
The PDF Smoothed Moving Average can be applied across various trading strategies and timeframes:
 Trend Following : By smoothing price data with PDF weighting, this indicator helps traders identify long-term trends while filtering out short-term noise.
 Reversal Trading : The PDF-MA’s trend coloring feature can help pinpoint potential reversal points by showing shifts in the trend direction, allowing traders to enter or exit positions at optimal moments.
 Swing Trading : The PDF-MA provides a clear trend line that swing traders can use to capture intermediate price moves, following the trend direction until it shifts.
 Final Thoughts 
The PDF Smoothed Moving Average   is a highly adaptable indicator that combines probabilistic smoothing with traditional moving averages, providing a nuanced view of market trends. By integrating PDF-based weighting with the flexibility of EMA or SMA smoothing, this indicator offers traders an advanced tool for trend analysis that adapts to changing market conditions with reduced lag and increased accuracy.
Whether you’re trading trends, reversals, or swings, the PDF-MA offers valuable insights into the direction and strength of price movements, making it a versatile addition to any trading strategy.
HMA Z-Score Probability Indicator by Erika BarkerThis indicator is a modified version of SteverSteves's original work, enhanced by Erika Barker. It visually represents asset price movements in terms of standard deviations from a Hull Moving Average (HMA), commonly known as a Z-Score.
 Key Features: 
 Z-Score Calculation:  Measures how many standard deviations the current price is from its HMA.
Hull Moving Average (HMA): This moving average provides a more responsive baseline for Z-Score calculations.
Flexible Display: Offers both area and candlestick visualization options for the Z-Score.
Probability Zones: Color-coded areas showing the statistical likelihood of prices based on their Z-Score.
Dynamic Price Level Labels: Displays actual price levels corresponding to Z-Score values.
Z-Table: An optional table showing the probability of occurrence for different Z-Score ranges.
Standard Deviation Lines: Horizontal lines at each standard deviation level for easy reference.
 How It Works: 
The indicator calculates the Z-Score by comparing the current price to its HMA and dividing by the standard deviation. This Z-Score is then plotted on a separate pane below the main chart.
Green areas/candles: Indicate prices above the HMA (positive Z-Score)
Red areas/candles: Indicate prices below the HMA (negative Z-Score)
Color-coded zones:
Green: Within 1 standard deviation (high probability)
Yellow: Between 1 and 2 standard deviations (medium probability)
Red: Beyond 2 standard deviations (low probability)
The HMA line (white) shows the trend of the Z-Score itself, offering insight into whether the asset is becoming more or less volatile over time.
Customization Options:
Adjust lookback periods for Z-Score and HMA calculations
Toggle between area and candlestick display
Show/hide probability fills, Z-Table, HMA line, and standard deviation bands
Customize text color and decimal rounding for price levels
 Interpretation: 
This indicator helps traders identify potential overbought or oversold conditions based on statistical probabilities. Extreme Z-Score values (beyond ±2 or ±3) often suggest a higher likelihood of mean reversion, while consistent Z-Scores in one direction may indicate a strong trend.
By combining the Z-Score with the HMA and probability zones, traders can gain a nuanced understanding of price movements relative to recent trends and their statistical significance.
Price Close ProbabilityThe Price Close Probability Indicator is designed to help traders estimate the likelihood of price closing above or below specified levels within a given bar. By placing two levels on your chart, you can quickly gauge the probability of the current price bar closing above or below these levels in real-time.
 Key Features: 
 
 Dynamic Probability Calculation:  The indicator continuously updates the probability of price closing above or below your set levels as the current bar progresses, providing you with timely insights as the bar approaches its close.
 Customizable Standard Deviation : Adjust the length of the Standard Deviation used in the calculations to tailor the probability estimates to your preferred settings.
 User-Friendly Probability Table : A clean, easy-to-read table displays the calculated probabilities, helping you make informed trading decisions at a glance.
 
 Assumptions and Considerations: 
While the indicator assumes that returns are normally distributed, which may not fully reflect reality, it still offers a valuable approximation of the probabilities for price movement within the current bar.
 Future Enhancements (Coming Soon): 
 Multi-Bar Probability:  Calculate probabilities across multiple bars to enhance your forecasting capabilities.
 Additional Levels:  Set more than two levels for a broader analysis of price movements.
 Refined Distribution Modeling:  Improve the accuracy of probability calculations by adjusting for more realistic return distributions.
 Disclaimer 
 Please remember that past performance may not be indicative of future results.
Due to various factors, including changing market conditions, the strategy may no longer perform as well as in historical backtesting.
This post and the script don’t provide any financial advice.
Markov Chain Trend IndicatorOverview 
The Markov Chain Trend Indicator utilizes the principles of Markov Chain processes to analyze stock price movements and predict future trends. By calculating the probabilities of transitioning between different market states (Uptrend, Downtrend, and Sideways), this indicator provides traders with valuable insights into market dynamics.
 Key Features 
 
  State Identification: Differentiates between Uptrend, Downtrend, and Sideways states based on price movements.
  Transition Probability Calculation: Calculates the probability of transitioning from one state to another using historical data.
  Real-time Dashboard: Displays the probabilities of each state on the chart, helping traders make informed decisions.
  Background Color Coding: Visually represents the current market state with background colors for easy interpretation.
 
 Concepts Underlying the Calculations 
 
  Markov Chains: A stochastic process where the probability of moving to the next state depends only on the current state, not on the sequence of events that preceded it.
  Logarithmic Returns: Used to normalize price changes and identify states based on significant movements.
  Transition Matrices: Utilized to store and calculate the probabilities of moving from one state to another.
 
 How It Works 
The indicator first calculates the logarithmic returns of the stock price to identify significant movements. Based on these returns, it determines the current state (Uptrend, Downtrend, or Sideways). It then updates the transition matrices to keep track of how often the price moves from one state to another. Using these matrices, the indicator calculates the probabilities of transitioning to each state and displays this information on the chart.
 How Traders Can Use It 
Traders can use the Markov Chain Trend Indicator to:
 
  Identify Market Trends: Quickly determine if the market is in an uptrend, downtrend, or sideways state.
  Predict Future Movements: Use the transition probabilities to forecast potential market movements and make informed trading decisions.
  Enhance Trading Strategies: Combine with other technical indicators to refine entry and exit points based on predicted trends.
 
 Example Usage Instructions 
 
 Add the Markov Chain Trend Indicator to your TradingView chart.
 Observe the background color to quickly identify the current market state:
Green for Uptrend, Red for Downtrend, Gray for Sideways
 Check the dashboard label to see the probabilities of transitioning to each state.
 Use these probabilities to anticipate market movements and adjust your trading strategy accordingly.
 Combine the indicator with other technical analysis tools for more robust decision-making.
 
Bayesian Trend Indicator [ChartPrime]Bayesian Trend Indicator  
 Overview: 
 In probability theory and statistics,  Bayes' theorem  (alternatively Bayes' law or Bayes' rule), named after Thomas Bayes, describes the probability of an event, based on prior knowledge of conditions that might be related to the event. 
The  "Bayesian Trend Indicator"  is a sophisticated technical analysis tool designed to assess the direction of price trends in financial markets. It combines the principles of Bayesian probability theory with moving average analysis to provide traders with a comprehensive understanding of market sentiment and potential trend reversals.
At its core, the indicator utilizes multiple moving averages, including the  Exponential Moving Average (EMA), Simple Moving Average (SMA), Double Exponential Moving Average (DEMA), and Volume Weighted Moving Average (VWMA) . These moving averages are calculated based on user-defined parameters such as length and gap length, allowing traders to customize the indicator to suit their trading strategies and preferences.
The indicator begins by calculating the trend for both fast and slow moving averages using a Smoothed Gradient Signal Function. This function assigns a numerical value to each data point based on its relationship with historical data, indicating the strength and direction of the trend.
 
// Smoothed Gradient Signal Function 
sig(float src, gap)=>
    ta.ema(source >= src    ? 1   : 
     source >= src  ? 0.9 :
     source >= src  ? 0.8 :
     source >= src  ? 0.7 :
     source >= src  ? 0.6 :
     source >= src  ? 0.5 :
     source >= src  ? 0.4 :
     source >= src  ? 0.3 :
     source >= src  ? 0.2 :
     source >= src  ? 0.1 :
      0, 4)
 
Next, the indicator calculates  prior probabilities  using the trend information from the  slow moving averages  and  likelihood probabilities  using the trend information from the  fast moving averages . These probabilities represent the likelihood of an uptrend or downtrend based on historical data.
 
// Define prior probabilities using moving averages
prior_up = (ema_trend + sma_trend + dema_trend + vwma_trend) / 4
prior_down = 1 - prior_up
// Define likelihoods using faster moving averages
likelihood_up = (ema_trend_fast + sma_trend_fast + dema_trend_fast + vwma_trend_fast) / 4
likelihood_down = 1 - likelihood_up
 
Using  Bayes' theorem , the indicator then combines the prior and likelihood probabilities to calculate posterior probabilities, which reflect the updated probability of an uptrend or downtrend given the current market conditions. These posterior probabilities serve as a key signal for traders, informing them about the prevailing market sentiment and potential trend reversals.
  
 
// Calculate posterior probabilities using Bayes' theorem
posterior_up = prior_up * likelihood_up 
                             / 
               (prior_up * likelihood_up + prior_down * likelihood_down)
                 
 
 Key Features: 
 ◆ The trend direction: 
To  visually represent the trend direction , the indicator colors the bars on the chart based on the posterior probabilities. Bars are colored green to indicate an uptrend when the posterior probability is greater than 0.5 (>50%), while bars are colored red to indicate a downtrend when the posterior probability is less than 0.5 (<50%).
  
 ◆ Dashboard on the chart 
Additionally, the indicator displays a  dashboard on the chart , providing traders with detailed information about the  probability of an uptrend , as well as the trends for each type of moving average. This dashboard serves as a valuable reference for traders to monitor trend strength and make informed trading decisions.
  
 ◆ Probability labels and signals: 
Furthermore, the indicator includes  probability labels and signals , which are displayed near the corresponding bars on the chart. These labels indicate the posterior probability of a trend, while small diamonds above or below bars indicate crossover or crossunder events when the posterior probability crosses the 0.5 threshold (50%).
 The posterior probability of a trend 
  
 Crossover or Crossunder events 
  
 ◆ User Inputs 
 
 Source:
Description: Defines the price source for the indicator's calculations. Users can select between different price values like close, open, high, low, etc.
 MA's Length:
Description: Sets the length for the moving averages used in the trend calculations. A larger length will smooth out the moving averages, making the indicator less sensitive to short-term fluctuations.
 Gap Length Between Fast and Slow MA's:
Description: Determines the difference in lengths between the slow and fast moving averages. A higher gap length will increase the difference, potentially identifying stronger trend signals.
 Gap Signals:
Description: Defines the gap used for the smoothed gradient signal function. This parameter affects the sensitivity of the trend signals by setting the number of bars used in the signal calculations.
 
In summary, the "Bayesian Trend Indicator" is a powerful tool that leverages Bayesian probability theory and moving average analysis to help traders identify trend direction, assess market sentiment, and make informed trading decisions in various financial markets.
Bayesian Bias OscillatorWhat is a Bayes Estimator? 
Bayesian estimation, or Bayesian inference, is a statistical method for estimating unknown parameters of a probability distribution based on observed data and prior knowledge about those parameters. At  first , you will need a prior probability distribution, which is a prior belief about the distribution of the parameter that you are interested in estimating. This distribution represents your initial beliefs or knowledge about the parameter value before observing any data. Second , you need a likelihood function, which represents the probability of observing the data given different values of the parameter. This function quantifies how well different parameter values explain the observed data.  Then , you will need a posterior probability distribution by combining the prior distribution and the likelihood function to obtain the posterior distribution of the parameter. The posterior distribution represents the updated belief about the parameter value after observing the data. 
 Bayesian Bias Oscillator 
This tool calculates the Bayes bias of returns, which are directional probabilities that provide insight on the "trend" of the market or the directional bias of returns. It comes with two outputs: the default one, which is the Z-Score of the Bayes Bias, and the regular raw probability, which can be switched on in the settings of the indicator. 
The Z-Score output value doesn't tell you the probability, but it does tell you how much of a standard deviation the value is from the mean. It uses both probabilities, the probability of a positive return and the probability of a negative return, which is just (1 - probability of a positive return). 
The probability output value shows you the raw probability of a positive return vs. the probability of a negative return. The probability is the value of each line plotted (blue is the probability of a positive return, and purple is the probability of a negative return). 
  























