OPEN-SOURCE SCRIPT

Bernoulli Process: Trend Probability & Entropy [MarkitTick]

175
💡 This technical indicator introduces a rigorous probabilistic framework to the evaluation of market regimes by modeling price fluctuations as a Bernoulli Process. Unlike traditional oscillators that merely measure the magnitude of price movement, this script treats every bar as a discrete "trial" that either succeeds or fails based on specific conditions—such as directional price action, momentum thresholds, or trend alignment. By applying Information Theory and the principles of Maximum Likelihood Estimation (MLE), the script quantifies not just the direction of the market, but the statistical reliability and the "noise" content of the current sequence. This allows traders to distinguish between a structured trend and high-entropy market "chop," providing a level of objective clarity often missing in standard technical analysis.

● ✨ Originality and Utility

The primary innovation of this script lies in its transition from deterministic price tracking to stochastic regime modeling. Most indicators suffer from the "binary trap," where they simply tell a trader if price is above or below a level without assessing the statistical significance of that state.

• Quantifying Market Information
By integrating Shannon’s Binary Entropy, the script measures the uncertainty inherent in a price sequence. When entropy is near 1.0, the market is in a state of maximum uncertainty (effectively a fair coin toss), signaling that a trader should likely avoid the "noise." Conversely, low entropy values indicate a high-information state where one side of the Bernoulli trial is dominating, suggesting a persistent trend.

• Adaptive Definition of Success
The script is not limited to a single logic; it allows the user to define what constitutes a "Success" in the Bernoulli trial. Whether you prioritize raw price action (Close > Open), momentum (RSI > 50), or trend-following (Price > Moving Average), the underlying probabilistic engine remains consistent, making it a versatile tool for various trading styles.

• Z-Score Significance Testing
It applies a Central Limit Theorem (CLT) approximation to calculate a Z-Score. This tells the trader how many standard deviations the current trend is away from a random walk (p=0.5). This provides a mathematical filter to avoid entering "trends" that are actually within the bounds of statistical randomness.

● 🔬 Methodology and Concepts

The script operates through a four-stage mathematical pipeline that converts raw market data into probabilistic metrics.

• Stage 1: The Bernoulli Trial (I)
The foundation is the indicator variable (I). On every bar, the script evaluates a boolean condition. If the condition is met, the trial is a "Success" (1.0); otherwise, it is a "Failure" (0.0). This transforms complex candles into a simple binary sequence: {1, 0, 1, 1, 0...}.

• Stage 2: Probability Estimation (p-hat)
Using a rolling window of length N, the script calculates the Maximum Likelihood Estimate (MLE) of the probability parameter 'p'. This is essentially the sample mean of the successes within the window. A value of 0.7 suggests that in the last N trials, 70% were successful.

• Stage 3: Binary Entropy Calculation
The script calculates Entropy H(p) using the formula:
H(p) = -p * log2(p) - (1-p) * log2(1-p)
This provides a metric for "Trend Quality." If p is 0.5 (random), H(p) is 1.0 (maximum noise). If p is 1.0 or 0.0 (perfect trend), H(p) is 0.0 (maximum order).

• Stage 4: Volatility-Adjusted Z-Score
To determine if a sequence is truly anomalous, the script calculates the standard deviation of a fair process and compares the observed deviations to this baseline. This identifies "Significant Trends" that are mathematically distinct from a 50/50 random distribution.

● 🎨 Visual Guide

The visual interface is designed to communicate complex statistical data through intuitive color-coded cues.

• The Bernoulli Probability Line
The main plot is a continuous line representing the estimated probability (p).
  • A value above 0.5 indicates a bullish bias (p-hat > 0.5).
  • A value below 0.5 indicates a bearish bias (p-hat < 0.5).


• Dynamic Entropy Coloring
The line does not just change color based on direction; it changes based on certainty.
  • Vibrant Green: Strong bullish trend with low entropy (High Certainty).
  • Vibrant Red: Strong bearish trend with low entropy (High Certainty).
  • Gray/Faded Color: High entropy regime (Entropy > 0.9). This signals that the market is "choppy" and the probability of success is too close to random to be reliable.


• Background Entropy Zones
The chart background highlights areas of "Max Entropy" in a subtle gray color. When you see these zones, it suggests the current Bernoulli definition is failing to find a directional edge, signaling a period of market consolidation.

• Real-Time Metrics Dashboard
A table in the top-right corner displays:
  • Probability (p): The exact decimal value of the current trend probability.
  • Entropy (Bits): The current level of uncertainty in the sequence.
  • Regime: A text-based label identifying the market state (Bull Trend, Bear Trend, or Noise/Chop).


• Execution Signals
Small triangles appear on the chart to mark high-probability transition points. A Triangle Up (Green) marks a bullish breakout from a low-entropy state, while a Triangle Down (Red) marks a bearish breakdown.

● 📖 How to Use

• Identifying Low-Noise Entries
Traders should look for instances where the Probability Line crosses the 0.5 threshold while Entropy is low (vibrant colors). If the line is gray, the "trend" lacks statistical significance, and the risk of a whip-saw is high.

• Regime Filtering
Use the indicator as a "Mode Filter." If the Dashboard displays "NOISE / CHOP," it is a signal to stay flat or use mean-reversion strategies. If it displays a "TREND" regime, trend-following strategies can be deployed with higher confidence.

• Interpreting the Z-Score
While not directly plotted, the Z-Score logic powers the signal generation. A signal is only produced when the deviation from the "Fair Coin" (0.5) is substantial enough to suggest a non-random event.

● ⚙️ Inputs and Settings

• Bernoulli Trial Definition
Choose between three calculation modes:
  • Price Action: Uses the relationship between Close and Open (Directional bars).
  • Momentum: Uses RSI relative to the 50-level (Standard momentum).
  • Trend: Uses Price relative to a Simple Moving Average (Long-term regime).


• Sample Window (N)
Determines the "lookback" for the probability calculation. Smaller values (e.g., 10-15) are more responsive but noisier; larger values (e.g., 30-50) provide a smoother, more institutional view of the regime.

• Risk Management (Alerts)
  • Target R:R Ratio: Used to calculate the Take Profit level in the JSON alerts.
  • Stop ATR Multiplier: Uses Average True Range to calculate a volatility-adjusted stop loss for signals.


● 🔍 Deconstruction of the Underlying Scientific and Academic Framework

The "Bernoulli Process: Trend Probability & Entropy" script is built upon the pillars of Discrete Stochastic Processes and Information Theory.

• The Law of Large Numbers (LLN)
The script relies on the LLN, which states that as a sample size grows, its mean gets closer to the average of the whole population. By using a "Sample Window," we are performing a rolling MLE of the true underlying probability parameter of the market at that moment.

• Shannon Entropy and Information Theory
Claude Shannon’s 1948 work on information entropy is the bedrock of the "Noise" detection in this script. In the context of trading, entropy represents the "surprise" or "uncertainty" in the price sequence. A low-entropy market is one where the next bar's success/failure is highly predictable based on the recent past, which is the mathematical definition of a trend.

• Bernoulli vs. Gaussian Distributions
Most indicators assume a Normal (Gaussian) distribution of price returns. However, market states are often better modeled as discrete outcomes (Up/Down). By treating the market as a Bernoulli Process, we bypass the "fat-tail" problem of Gaussian distributions and focus purely on the frequency of successful outcomes, making the tool more robust against outliers.

• The Z-Test for Proportions
By applying a Z-score calculation to a Bernoulli distribution, the script treats the market like a "biased coin" experiment. It tests the Null Hypothesis ($H_0$): "The market is a fair coin (p=0.5)." When the Z-score is high, we reject $H_0$ in favor of the Alternative Hypothesis ($H_1$): "The market is trending (p != 0.5)."

⚠️ Disclaimer

All provided scripts and indicators are strictly for educational exploration and must not be interpreted as financial advice or a recommendation to execute trades. I expressly disclaim all liability for any financial losses or damages that may result, directly or indirectly, from the reliance on or application of these tools. Market participation carries inherent risk where past performance never guarantees future returns, leaving all investment decisions and due diligence solely at your own discretion.

免責聲明

這些資訊和出版物並非旨在提供,也不構成TradingView提供或認可的任何形式的財務、投資、交易或其他類型的建議或推薦。請閱讀使用條款以了解更多資訊。