OPEN-SOURCE SCRIPT

First Passage Time - Distribution Analysis

274
The 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
  1. Percentile: Shows 10%, 25%, 50%, 75%, 90% levels (recommended for most users)
  2. 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!

Aviso legal

As informações e publicações não devem ser e não constituem conselhos ou recomendações financeiras, de investimento, de negociação ou de qualquer outro tipo, fornecidas ou endossadas pela TradingView. Leia mais em Termos de uso.