MACD Forecast Colorful [DiFlip]MACD Forecast Colorful
The Future of Predictive MACD — is one of the most advanced and customizable MACD indicators ever published on TradingView. Built on the classic MACD foundation, this upgraded version integrates statistical forecasting through linear regression to anticipate future movements — not just react to the past.
With a total of 22 fully configurable long and short entry conditions, visual enhancements, and full automation support, this indicator is designed for serious traders seeking an analytical edge.
⯁ Real-Time MACD Forecasting
For the first time, a public MACD script combines the classic structure of MACD with predictive analytics powered by linear regression. Instead of simply responding to current values, this tool projects the MACD line, signal line, and histogram n bars into the future, allowing you to trade with foresight rather than hindsight.
⯁ Fully Customizable
This indicator is built for flexibility. It includes 22 entry conditions, all of which are fully configurable. Each condition can be turned on/off, chained using AND/OR logic, and adapted to your trading model.
Whether you're building a rules-based quant system, automating alerts, or refining discretionary signals, MACD Forecast Colorful gives you full control over how signals are generated, displayed, and triggered.
⯁ With MACD Forecast Colorful, you can:
• Detect MACD crossovers before they happen.
• Anticipate trend reversals with greater precision.
• React earlier than traditional indicators.
• Gain a powerful edge in both discretionary and automated strategies.
• This isn’t just smarter MACD — it’s predictive momentum intelligence.
⯁ Scientifically Powered by Linear Regression
MACD Forecast Colorful is the first public MACD indicator to apply least-squares predictive modeling to MACD behavior — effectively introducing machine learning logic into a time-tested tool.
It uses statistical regression to analyze historical behavior of the MACD and project future trajectories. The result is a forward-shifted MACD forecast that can detect upcoming crossovers and divergences before they appear on the chart.
⯁ Linear Regression: Technical Foundation
Linear regression is a statistical method that models the relationship between a dependent variable (y) and one or more independent variables (x). The basic formula for simple linear regression is:
y = β₀ + β₁x + ε
Where:
y = predicted variable (e.g., future MACD value)
x = independent variable (e.g., bar index)
β₀ = intercept
β₁ = slope
ε = random error (residual)
The regression model calculates β₀ and β₁ using the least squares method, minimizing the sum of squared prediction errors to produce the best-fit line through historical values. This line is then extended forward, generating a forecast based on recent price momentum.
⯁ Least Squares Estimation
The regression coefficients are computed with the following formulas:
β₁ = Σ((xᵢ - x̄)(yᵢ - ȳ)) / Σ((xᵢ - x̄)²)
β₀ = ȳ - β₁x̄
Where:
Σ denotes summation; x̄ and ȳ are the means of x and y; and i ranges from 1 to n (number of observations). These equations produce the best linear unbiased estimator under the Gauss–Markov assumptions — constant variance (homoscedasticity) and a linear relationship between variables.
⯁ Regression in Machine Learning
Linear regression is a foundational model in supervised learning. Its ability to provide precise, explainable, and fast forecasts makes it critical in AI systems and quantitative analysis.
Applying linear regression to MACD forecasting is the equivalent of injecting artificial intelligence into one of the most widely used momentum tools in trading.
⯁ Visual Interpretation
Picture the MACD values over time like this:
Time →
MACD →
A regression line is fitted to recent MACD values, then projected forward n periods. The result is a predictive trajectory that can cross over the real MACD or signal line — offering an early-warning system for trend shifts and momentum changes.
The indicator plots both current MACD and forecasted MACD, allowing you to visually compare short-term future behavior against historical movement.
⯁ Scientific Concepts Used
Linear Regression: models the relationship between variables using a straight line.
Least Squares Method: minimizes squared prediction errors for best-fit.
Time-Series Forecasting: projects future data based on past patterns.
Supervised Learning: predictive modeling using labeled inputs.
Statistical Smoothing: filters noise to highlight trends.
⯁ Why This Indicator Is Revolutionary
First open-source MACD with real-time predictive modeling.
Scientifically grounded with linear regression logic.
Automatable through TradingView alerts and bots.
Smart signal generation using forecasted crossovers.
Highly customizable with 22 buy/sell conditions.
Enhanced visuals with background (bgcolor) and area fill (fill) support.
This isn’t just an update — it’s the next evolution of MACD forecasting.
⯁ Example of simple linear regression with one independent variable
This example demonstrates how a basic linear regression works when there is only one independent variable influencing the dependent variable. This type of model is used to identify a direct relationship between two variables.
⯁ In linear regression, observations (red) are considered the result of random deviations (green) from an underlying relationship (blue) between a dependent variable (y) and an independent variable (x)
This concept illustrates that sampled data points rarely align perfectly with the true trend line. Instead, each observed point represents the combination of the true underlying relationship and a random error component.
⯁ Visualizing heteroscedasticity in a scatterplot with 100 random fitted values using Matlab
Heteroscedasticity occurs when the variance of the errors is not constant across the range of fitted values. This visualization highlights how the spread of data can change unpredictably, which is an important factor in evaluating the validity of regression models.
⯁ The datasets in Anscombe’s quartet were designed to have nearly the same linear regression line (as well as nearly identical means, standard deviations, and correlations) but look very different when plotted
This classic example shows that summary statistics alone can be misleading. Even with identical numerical metrics, the datasets display completely different patterns, emphasizing the importance of visual inspection when interpreting a model.
⯁ Result of fitting a set of data points with a quadratic function
This example illustrates how a second-degree polynomial model can better fit certain datasets that do not follow a linear trend. The resulting curve reflects the true shape of the data more accurately than a straight line.
⯁ What is the MACD?
The Moving Average Convergence Divergence (MACD) is a technical analysis indicator developed by Gerald Appel. It measures the relationship between two moving averages of a security’s price to identify changes in momentum, direction, and strength of a trend. The MACD is composed of three components: the MACD line, the signal line, and the histogram.
⯁ How to use the MACD?
The MACD is calculated by subtracting the 26-period Exponential Moving Average (EMA) from the 12-period EMA. A 9-period EMA of the MACD line, called the signal line, is then plotted on top of the MACD line. The MACD histogram represents the difference between the MACD line and the signal line.
Here are the primary signals generated by the MACD:
• Bullish Crossover: When the MACD line crosses above the signal line, indicating a potential buy signal.
• Bearish Crossover: When the MACD line crosses below the signal line, indicating a potential sell signal.
• Divergence: When the price of the security diverges from the MACD, suggesting a potential reversal.
• Overbought/Oversold Conditions: Indicated by the MACD line moving far away from the signal line, though this is less common than in oscillators like the RSI.
⯁ How to use MACD forecast?
The MACD Forecast is built on the same foundation as the classic MACD, but with predictive capabilities.
Step 1 — Spot Predicted Crossovers:
Watch for forecasted bullish or bearish crossovers. These signals anticipate when the MACD line will cross the signal line in the future, letting you prepare trades before the move.
Step 2 — Confirm with Histogram Projection:
Use the projected histogram to validate momentum direction. A rising histogram signals strengthening bullish momentum, while a falling projection points to weakening or bearish conditions.
Step 3 — Combine with Multi-Timeframe Analysis:
Use forecasts across multiple timeframes to confirm signal strength (e.g., a 1h forecast aligned with a 4h forecast).
Step 4 — Set Entry Conditions & Automation:
Customize your buy/sell rules with the 20 forecast-based conditions and enable automation for bots or alerts.
Step 5 — Trade Ahead of the Market:
By preparing for future momentum shifts instead of reacting to the past, you’ll always stay one step ahead of lagging traders.
📈 BUY
🍟 Signal Validity: The signal will remain valid for X bars.
🍟 Signal Sequence: Configurable as AND or OR.
🍟 MACD > Signal Smoothing
🍟 MACD < Signal Smoothing
🍟 Histogram > 0
🍟 Histogram < 0
🍟 Histogram Positive
🍟 Histogram Negative
🍟 MACD > 0
🍟 MACD < 0
🍟 Signal > 0
🍟 Signal < 0
🍟 MACD > Histogram
🍟 MACD < Histogram
🍟 Signal > Histogram
🍟 Signal < Histogram
🍟 MACD (Crossover) Signal
🍟 MACD (Crossunder) Signal
🍟 MACD (Crossover) 0
🍟 MACD (Crossunder) 0
🍟 Signal (Crossover) 0
🍟 Signal (Crossunder) 0
🔮 MACD (Crossover) Signal Forecast
🔮 MACD (Crossunder) Signal Forecast
📉 SELL
🍟 Signal Validity: The signal will remain valid for X bars.
🍟 Signal Sequence: Configurable as AND or OR.
🍟 MACD > Signal Smoothing
🍟 MACD < Signal Smoothing
🍟 Histogram > 0
🍟 Histogram < 0
🍟 Histogram Positive
🍟 Histogram Negative
🍟 MACD > 0
🍟 MACD < 0
🍟 Signal > 0
🍟 Signal < 0
🍟 MACD > Histogram
🍟 MACD < Histogram
🍟 Signal > Histogram
🍟 Signal < Histogram
🍟 MACD (Crossover) Signal
🍟 MACD (Crossunder) Signal
🍟 MACD (Crossover) 0
🍟 MACD (Crossunder) 0
🍟 Signal (Crossover) 0
🍟 Signal (Crossunder) 0
🔮 MACD (Crossover) Signal Forecast
🔮 MACD (Crossunder) Signal Forecast
🤖 Automation
All BUY and SELL conditions can be automated using TradingView alerts. Every configurable condition can trigger alerts suitable for fully automated or semi-automated strategies.
⯁ Unique Features
Linear Regression: (Forecast)
Signal Validity: The signal will remain valid for X bars
Signal Sequence: Configurable as AND/OR
Table of Conditions: BUY/SELL
Conditions Label: BUY/SELL
Plot Labels in the graph above: BUY/SELL
Automate & Monitor Signals/Alerts: BUY/SELL
Background Colors: "bgcolor"
Background Colors: "fill"
Linear Regression (Forecast)
Signal Validity: The signal will remain valid for X bars
Signal Sequence: Configurable as AND/OR
Table of Conditions: BUY/SELL
Conditions Label: BUY/SELL
Plot Labels in the graph above: BUY/SELL
Automate & Monitor Signals/Alerts: BUY/SELL
Background Colors: "bgcolor"
Background Colors: "fill"
אינדיקטורים ואסטרטגיות
Simple GapsSimple gaps indicator that shows gap downs or gap up.
It contains two filter
atr filter
To filter out small gaps from bigger gaps.
This is an extra option and is best left false.
Session filter
To remove gaps from lower time frames (outside of regular hours).
6/20 EMA Crossover MarksPuts a green arrow or red arrow at the bottom of the chart when the 6 period EMA crosses above (or below) the 20 period EMA.
In settings you can move the arrow marks to be at the bar etc.
This is a simplified way to see moving average convergence/divergence crossovers.
FRAN CRASH PLAY RULESPurpose
It creates a fixed information panel in the top right corner of your chart that shows the "FRAN CRASH PLAY RULES" - a checklist of criteria for identifying potential crash play setups.
Key Features
Display Panel:
Shows 5 trading rules as bullet points
Permanently visible in the top right corner
Stays fixed while you scroll or zoom the chart
Current Rules Displayed:
DYNAMIC 3 TO 5 LEG RUN
NEAR VERTICAL ACCELERATION
FINAL BAR OF THE RUN UP MUST BE THE BIGGEST
3 FINGER SPREAD / DUAL SPACE
ATLEAST 2 OF 5 CRITERIA NEEDS TO HIT
Customization Options:
Editable Text - Change any of the 5 rules through the settings
Text Color - Adjust the color of the text
Text Size - Choose from tiny, small, normal, large, or huge
Background Color - Customize the panel background and transparency
Frame Color - Change the border color
Show/Hide Frame - Toggle the border on or off
Use Case
This indicator serves as a constant visual reminder of your trading strategy criteria, helping you stay disciplined and only take trades that meet your specific crash play requirements. It's essentially a "cheat sheet" that lives on your chart so you don't have to memorize or look elsewhere for your trading rules.
IBIT premium(vs NAV)This Pine Script calculates and plots the real-time trading premium or discount of the IBIT ETF relative to its official Net Asset Value (NAV).
It shows whether IBIT is trading above NAV (premium) or below NAV (discount) in percentage terms.
This version is accurate because it uses TradingView’s built-in ETF NAV financial data, rather than estimating BTC per share.
⸻
Key Data Sources Used
• Market Price:
The script pulls the live IBIT market price from NASDAQ:IBIT.
• Official NAV:
It retrieves the daily Net Asset Value (NAV) using TradingView’s financial data function and expands it across all intraday timeframes so it can be compared with real-time prices.
• Platform used: TradingView
⸻
How the Premium Is Calculated
The script uses the standard ETF premium formula:
\text{Premium (\%)} = \frac{\text{Market Price} - \text{NAV}}{\text{NAV}} \times 100
• Positive value → IBIT is trading at a premium
• Negative value → IBIT is trading at a discount
• Zero → IBIT is trading exactly at NAV
⸻
What the Chart Displays
• A real-time premium (%) line in a separate indicator panel
• A 0% reference line showing fair value
• ±1% and ±2% guide lines for abnormal deviation detection
• A live value label on the latest bar showing the exact current premium
⸻
Why This Script Is Accurate
• Uses official ETF NAV, not a BTC-per-share estimate
• NAV updates once per day, exactly as reported by the issuer
• Works on all timeframes (1-minute to daily)
• Shows true market mispricing, not synthetic BTC tracking error
⸻
How Traders Typically Use It
• Detect temporary dislocations between IBIT price and NAV
• Monitor liquidity stress during high volatility
• Validate whether IBIT is trading efficiently versus BTC
• Support ETF–BTC–Futures arbitrage analysis
⸻
Important Limitation
• NAV is only updated once per trading day
• During fast BTC moves, the premium may widen temporarily and normalize later via authorized participant (AP) arbitrage
DH EMA 28/72/200 Unified Ribbon (Scaled HTF)Unified EMA Ribbon (28/72/200)
This indicator merges two popular EMA systems — 21/55/200 and 34/89/200 — into a single, smoother trend-tracking ribbon.
Each pair of EMAs is averaged to create:
EMA 28 (average of 21 & 34)
EMA 72 (average of 55 & 89)
EMA 200 retained as long-term trend filter
The unified ribbon reduces noise, improves trend clarity, and provides clean pullback zones for high-probability entries, especially on the H1 timeframe.
Expected Move BandsExpected move is the amount that an asset is predicted to increase or decrease from its current price, based on the current levels of volatility.
In this model, we assume asset price follows a log-normal distribution and the log return follows a normal distribution.
Note: Normal distribution is just an assumption, it's not the real distribution of return
Settings:
"Estimation Period Selection" is for selecting the period we want to construct the prediction interval.
For "Current Bar", the interval is calculated based on the data of the previous bar close. Therefore changes in the current price will have little effect on the range. What current bar means is that the estimated range is for when this bar close. E.g., If the Timeframe on 4 hours and 1 hour has passed, the interval is for how much time this bar has left, in this case, 3 hours.
For "Future Bars", the interval is calculated based on the current close. Therefore the range will be very much affected by the change in the current price. If the current price moves up, the range will also move up, vice versa. Future Bars is estimating the range for the period at least one bar ahead.
There are also other source selections based on high low.
Time setting is used when "Future Bars" is chosen for the period. The value in time means how many bars ahead of the current bar the range is estimating. When time = 1, it means the interval is constructing for 1 bar head. E.g., If the timeframe is on 4 hours, then it's estimating the next 4 hours range no matter how much time has passed in the current bar.
Note: It's probably better to use "probability cone" for visual presentation when time > 1
Volatility Models :
Sample SD: traditional sample standard deviation, most commonly used, use (n-1) period to adjust the bias
Parkinson: Uses High/ Low to estimate volatility, assumes continuous no gap, zero mean no drift, 5 times more efficient than Close to Close
Garman Klass: Uses OHLC volatility, zero drift, no jumps, about 7 times more efficient
Yangzhang Garman Klass Extension: Added jump calculation in Garman Klass, has the same value as Garman Klass on markets with no gaps.
about 8 x efficient
Rogers: Uses OHLC, Assume non-zero mean volatility, handles drift, does not handle jump 8 x efficient
EWMA: Exponentially Weighted Volatility. Weight recently volatility more, more reactive volatility better in taking account of volatility autocorrelation and cluster.
YangZhang: Uses OHLC, combines Rogers and Garmand Klass, handles both drift and jump, 14 times efficient, alpha is the constant to weight rogers volatility to minimize variance.
Median absolute deviation: It's a more direct way of measuring volatility. It measures volatility without using Standard deviation. The MAD used here is adjusted to be an unbiased estimator.
Volatility Period is the sample size for variance estimation. A longer period makes the estimation range more stable less reactive to recent price. Distribution is more significant on a larger sample size. A short period makes the range more responsive to recent price. Might be better for high volatility clusters.
Standard deviations:
Standard Deviation One shows the estimated range where the closing price will be about 68% of the time.
Standard Deviation two shows the estimated range where the closing price will be about 95% of the time.
Standard Deviation three shows the estimated range where the closing price will be about 99.7% of the time.
Note: All these probabilities are based on the normal distribution assumption for returns. It's the estimated probability, not the actual probability.
Manually Entered Standard Deviation shows the range of any entered standard deviation. The probability of that range will be presented on the panel.
People usually assume the mean of returns to be zero. To be more accurate, we can consider the drift in price from calculating the geometric mean of returns. Drift happens in the long run, so short lookback periods are not recommended. Assuming zero mean is recommended when time is not greater than 1.
When we are estimating the future range for time > 1, we typically assume constant volatility and the returns to be independent and identically distributed. We scale the volatility in term of time to get future range. However, when there's autocorrelation in returns( when returns are not independent), the assumption fails to take account of this effect. Volatility scaled with autocorrelation is required when returns are not iid. We use an AR(1) model to scale the first-order autocorrelation to adjust the effect. Returns typically don't have significant autocorrelation. Adjustment for autocorrelation is not usually needed. A long length is recommended in Autocorrelation calculation.
Note: The significance of autocorrelation can be checked on an ACF indicator.
ACF
The multimeframe option enables people to use higher period expected move on the lower time frame. People should only use time frame higher than the current time frame for the input. An error warning will appear when input Tf is lower. The input format is multiplier * time unit. E.g. : 1D
Unit: M for months, W for Weeks, D for Days, integers with no unit for minutes (E.g. 240 = 240 minutes). S for Seconds.
Smoothing option is using a filter to smooth out the range. The filter used here is John Ehler's supersmoother. It's an advance smoothing technique that gets rid of aliasing noise. It affects is similar to a simple moving average with half the lookback length but smoother and has less lag.
Note: The range here after smooth no long represent the probability
Panel positions can be adjusted in the settings.
X position adjusts the horizontal position of the panel. Higher X moves panel to the right and lower X moves panel to the left.
Y position adjusts the vertical position of the panel. Higher Y moves panel up and lower Y moves panel down.
Step line display changes the style of the bands from line to step line. Step line is recommended because it gets rid of the directional bias of slope of expected move when displaying the bands.
Warnings:
People should not blindly trust the probability. They should be aware of the risk evolves by using the normal distribution assumption. The real return has skewness and high kurtosis. While skewness is not very significant, the high kurtosis should be noticed. The Real returns have much fatter tails than the normal distribution, which also makes the peak higher. This property makes the tail ranges such as range more than 2SD highly underestimate the actual range and the body such as 1 SD slightly overestimate the actual range. For ranges more than 2SD, people shouldn't trust them. They should beware of extreme events in the tails.
Different volatility models provide different properties if people are interested in the accuracy and the fit of expected move, they can try expected move occurrence indicator. (The result also demonstrate the previous point about the drawback of using normal distribution assumption).
Expected move Occurrence Test
The prediction interval is only for the closing price, not wicks. It only estimates the probability of the price closing at this level, not in between. E.g., If 1 SD range is 100 - 200, the price can go to 80 or 230 intrabar, but if the bar close within 100 - 200 in the end. It's still considered a 68% one standard deviation move.
XAU Macro Regime + Mispricing OscillatorThis indicator is designed to measure the true macro environment behind gold (XAUUSD) and identify when price is aligned with macro flows or mispriced relative to them.
It combines a macro composite index, a mispricing spread oscillator, and automatic divergence detection into one tool.
1. Macro Composite Index (Regime Filter)
The top layer of the indicator constructs a macro regime score derived from:
A basket of gold FX pairs (XAUJPY, XAUAUD, XAUCHF, XAUNZD, XAUSGD)
The inverted DXY (to represent USD pressure on gold)
US30 (to capture global risk appetite and macro sentiment)
Each component is normalized and weighted, then combined into a composite macro index.
A smoothed baseline (SMA) is subtracted from this composite to form the Regime Line.
Interpretation
Regime > 0 (Green background):
Macro environment is supportive for gold.
XAUUSD is more likely to rise, consolidate, or mean revert upward.
Regime < 0 (Red background):
Macro environment is hostile for gold.
XAUUSD is more likely to fall, struggle, or mean revert downward.
This creates a macro trend filter that tells you when it is safer to prefer longs, shorts, or stay out.
2. Mispricing Spread Oscillator (Spread MACD)
The second layer measures the difference between XAUUSD and the macro composite index:
Spread = (Macro Composite) – (Normalized XAUUSD)
This spread is then smoothed into a signal line, and a histogram is plotted from their difference (MACD-style).
Interpretation
Spread > 0:
Gold is undervalued relative to macro conditions.
Macro strength > price strength.
Spread < 0:
Gold is overvalued relative to macro conditions.
Price strength > macro strength.
Spread crossing above signal:
Macro momentum turning bullish relative to price.
Spread crossing below signal:
Macro momentum turning bearish relative to price.
Green histogram: acceleration upward
Red histogram: acceleration downward
This oscillator captures mispricing, momentum shifts, and macro-pressure reversals.
3. Automatic Divergence Detection
The indicator automatically detects:
-Bullish Divergence-
XAUUSD makes a lower low
Spread makes a higher low
→ Price is weaker than macro reality → potential bullish reversal or mispricing reversion.
-Bearish Divergence-
XAUUSD makes a higher high
Spread makes a lower high
→ Price is stronger than macro reality → potential bearish reversal or exhaustion.
Labels (“Bull div” / “Bear div”) appear directly on the oscillator for clarity.
4. What The Indicator Seeks To Do
This indicator aims to answer the question:
“Is gold moving with the true macro pressure behind it, or diverging from it?”
Most gold indicators only watch XAUUSD price.
This one watches:
-gold cross-currency flows
-USD strength
-global risk sentiment
-gold’s relative position vs macro
-mispricing momentum
-divergence between price and macro reality
This creates a unique tool that:
-Detects when gold is overextended
-Detects when gold is undervalued
-Reveals hidden macro strength or weakness
-Highlights turning points and exhaustion
-Shows when a pullback is likely to end
-Shows when a rally is likely to fail
-Gives regime-aware trade direction (long vs short bias)
-Adds divergence labels for precision entries
EMA 9/20/50/100/200This script plots the five most commonly used Exponential Moving Averages (EMAs): 9, 20, 50, 100, and 200. These EMAs help traders quickly identify short-term momentum, medium-term trends, and long-term market direction.
It is useful for:
Trend identification
Momentum confirmation
Pullback entries
Reversal detection
Multi-timeframe confluence trading
What’s Included
EMA 9 → short-term momentum
EMA 20 → near-term trend guide
EMA 50 → medium-term trend
EMA 100 → broad trend structure
EMA 200 → long-term direction
Each EMA is color-coded for clarity, making it easy to read and visually track trend shifts.
How to Use
When shorter EMAs cross above longer EMAs → bullish trend strengthening
When shorter EMAs cross below longer EMAs → bearish trend strengthening
Wide spacing between EMAs indicates a strong trend
Compression or clustering often signals potential reversals or breakout conditions
This indicator is simple, clean, and effective for all timeframes and asset classes.
SPY Overlay on ES/SPXEnhanced version of @ptgambler's for drawing SPY levels over ES/SPX.
lines/labels are configurable. The levels updates only when ES/SPX price moves by two dollars. That reduces jitter, and makes the code efficient.
NYSE CME Market Session Clock This indicator can only work on short-term timeframes, since the time before the opening and before the closing of the session is updated only with the appearance of a new candle.
Sugarol Strategythis strategy is only use for friends indicator purposes. it is not recommended to use for trading as it has a small winning percentage
Price Volume Trend to buyThis indicator use PVT (price volume tendency) as background whith colors and labels to smart indicate if you are on buyer or seller scenario
MGC1! - TPO & Volume Profile (High Precision)The official TPO takes into account the entire height of the candle (High to Low). If a candle goes from 4270 to 4280, the TPO adds a “mark” on all intermediate prices, not just at the close. That's why your VAH was too low: the script was “missing” the entire upper area of the wicks and bodies.
I rewrote the script engine so that it scans the inside of the candles (High to Low).
Here is the “High Precision” script. It is more computationally intensive (because it loops on each tick), but it will stick much closer to the official TPO values.
Corrective Script: MGC1! TPO Precision (High-Low Scan)
Copy this, replace the old one, and read the settings below carefully.
Translated with DeepL.com (free version)
EMA Crossover + Angle + Candle Pattern + Breakout (Clean)+mrit uses 9 15 ema startegy with angle and candle also candle used are pin bar , hammer, full body
Hurst Exponent - Detrended Fluctuation AnalysisIn stochastic processes, chaos theory and time series analysis, detrended fluctuation analysis (DFA) is a method for determining the statistical self-affinity of a signal. It is useful for analyzing time series that appear to be long-memory processes and noise.
█ OVERVIEW
We have introduced the concept of Hurst Exponent in our previous open indicator Hurst Exponent (Simple). It is an indicator that measures market state from autocorrelation. However, we apply a more advanced and accurate way to calculate Hurst Exponent rather than simple approximation. Therefore, we recommend using this version of Hurst Exponent over our previous publication going forward. The method we used here is called detrended fluctuation analysis. (For folks that are not interested in the math behind the calculation, feel free to skip to "features" and "how to use" section. However, it is recommended that you read it all to gain a better understanding of the mathematical reasoning).
█ Detrend Fluctuation Analysis
Detrended Fluctuation Analysis was first introduced by by Peng, C.K. (Original Paper) in order to measure the long-range power-law correlations in DNA sequences . DFA measures the scaling-behavior of the second moment-fluctuations, the scaling exponent is a generalization of Hurst exponent.
The traditional way of measuring Hurst exponent is the rescaled range method. However DFA provides the following benefits over the traditional rescaled range method (RS) method:
• Can be applied to non-stationary time series. While asset returns are generally stationary, DFA can measure Hurst more accurately in the instances where they are non-stationary.
• According the the asymptotic distribution value of DFA and RS, the latter usually overestimates Hurst exponent (even after Anis- Llyod correction) resulting in the expected value of RS Hurst being close to 0.54, instead of the 0.5 that it should be. Therefore it's harder to determine the autocorrelation based on the expected value. The expected value is significantly closer to 0.5 making that threshold much more useful, using the DFA method on the Hurst Exponent (HE).
• Lastly, DFA requires lower sample size relative to the RS method. While the RS method generally requires thousands of observations to reduce the variance of HE, DFA only needs a sample size greater than a hundred to accomplish the above mentioned.
█ Calculation
DFA is a modified root-mean-squares (RMS) analysis of a random walk. In short, DFA computes the RMS error of linear fits over progressively larger bins (non-overlapped “boxes” of similar size) of an integrated time series.
Our signal time series is the log returns. First we subtract the mean from the log return to calculate the demeaned returns. Then, we calculate the cumulative sum of demeaned returns resulting in the cumulative sum being mean centered and we can use the DFA method on this. The subtraction of the mean eliminates the “global trend” of the signal. The advantage of applying scaling analysis to the signal profile instead of the signal, allows the original signal to be non-stationary when needed. (For example, this process converts an i.i.d. white noise process into a random walk.)
We slice the cumulative sum into windows of equal space and run linear regression on each window to measure the linear trend. After we conduct each linear regression. We detrend the series by deducting the linear regression line from the cumulative sum in each windows. The fluctuation is the difference between cumulative sum and regression.
We use different windows sizes on the same cumulative sum series. The window sizes scales are log spaced. Eg: powers of 2, 2,4,8,16... This is where the scale free measurements come in, how we measure the fractal nature and self similarity of the time series, as well as how the well smaller scale represent the larger scale.
As the window size decreases, we uses more regression lines to measure the trend. Therefore, the fitness of regression should be better with smaller fluctuation. It allows one to zoom into the “picture” to see the details. The linear regression is like rulers. If you use more rulers to measure the smaller scale details you will get a more precise measurement.
The exponent we are measuring here is to determine the relationship between the window size and fitness of regression (the rate of change). The more complex the time series are the more it will depend on decreasing window sizes (using more linear regression lines to measure). The less complex or the more trend in the time series, it will depend less. The fitness is calculated by the average of root mean square errors (RMS) of regression from each window.
Root mean Square error is calculated by square root of the sum of the difference between cumulative sum and regression. The following chart displays average RMS of different window sizes. As the chart shows, values for smaller window sizes shows more details due to higher complexity of measurements.
The last step is to measure the exponent. In order to measure the power law exponent. We measure the slope on the log-log plot chart. The x axis is the log of the size of windows, the y axis is the log of the average RMS. We run a linear regression through the plotted points. The slope of regression is the exponent. It's easy to see the relationship between RMS and window size on the chart. Larger RMS equals less fitness of the regression. We know the RMS will increase (fitness will decrease) as we increases window size (use less regressions to measure), we focus on the rate of RMS increasing (how fast) as window size increases.
If the slope is < 0.5, It means the rate of of increase in RMS is small when window size increases. Therefore the fit is much better when it's measured by a large number of linear regression lines. So the series is more complex. (Mean reversion, negative autocorrelation).
If the slope is > 0.5, It means the rate of increase in RMS is larger when window sizes increases. Therefore even when window size is large, the larger trend can be measured well by a small number of regression lines. Therefore the series has a trend with positive autocorrelation.
If the slope = 0.5, It means the series follows a random walk.
█ FEATURES
• Sample Size is the lookback period for calculation. Even though DFA requires a lower sample size than RS, a sample size larger > 50 is recommended for accurate measurement.
• When a larger sample size is used (for example = 1000 lookback length), the loading speed may be slower due to a longer calculation. Date Range is used to limit numbers of historical calculation bars. When loading speed is too slow, change the data range "all" into numbers of weeks/days/hours to reduce loading time. (Credit to allanster)
• “show filter” option applies a smoothing moving average to smooth the exponent.
• Log scale is my work around for dynamic log space scaling. Traditionally the smallest log space for bars is power of 2. It requires at least 10 points for an accurate regression, resulting in the minimum lookback to be 1024. I made some changes to round the fractional log space into integer bars requiring the said log space to be less than 2.
• For a more accurate calculation a larger "Base Scale" and "Max Scale" should be selected. However, when the sample size is small, a larger value would cause issues. Therefore, a general rule to be followed is: A larger "Base Scale" and "Max Scale" should be selected for a larger the sample size. It is recommended for the user to try and choose a larger scale if increasing the value doesn't cause issues.
The following chart shows the change in value using various scales. As shown, sometimes increasing the value makes the value itself messy and overshoot.
When using the lowest scale (4,2), the value seems stable. When we increase the scale to (8,2), the value is still alright. However, when we increase it to (8,4), it begins to look messy. And when we increase it to (16,4), it starts overshooting. Therefore, (8,2) seems to be optimal for our use.
█ How to Use
Similar to Hurst Exponent (Simple). 0.5 is a level for determine long term memory.
• In the efficient market hypothesis, market follows a random walk and Hurst exponent should be 0.5. When Hurst Exponent is significantly different from 0.5, the market is inefficient.
• When Hurst Exponent is > 0.5. Positive Autocorrelation. Market is Trending. Positive returns tend to be followed by positive returns and vice versa.
• Hurst Exponent is < 0.5. Negative Autocorrelation. Market is Mean reverting. Positive returns trends to follow by negative return and vice versa.
However, we can't really tell if the Hurst exponent value is generated by random chance by only looking at the 0.5 level. Even if we measure a pure random walk, the Hurst Exponent will never be exactly 0.5, it will be close like 0.506 but not equal to 0.5. That's why we need a level to tell us if Hurst Exponent is significant.
So we also computed the 95% confidence interval according to Monte Carlo simulation. The confidence level adjusts itself by sample size. When Hurst Exponent is above the top or below the bottom confidence level, the value of Hurst exponent has statistical significance. The efficient market hypothesis is rejected and market has significant inefficiency.
The state of market is painted in different color as the following chart shows. The users can also tell the state from the table displayed on the right.
An important point is that Hurst Value only represents the market state according to the past value measurement. Which means it only tells you the market state now and in the past. If Hurst Exponent on sample size 100 shows significant trend, it means according to the past 100 bars, the market is trending significantly. It doesn't mean the market will continue to trend. It's not forecasting market state in the future.
However, this is also another way to use it. The market is not always random and it is not always inefficient, the state switches around from time to time. But there's one pattern, when the market stays inefficient for too long, the market participants see this and will try to take advantage of it. Therefore, the inefficiency will be traded away. That's why Hurst exponent won't stay in significant trend or mean reversion too long. When it's significant the market participants see that as well and the market adjusts itself back to normal.
The Hurst Exponent can be used as a mean reverting oscillator itself. In a liquid market, the value tends to return back inside the confidence interval after significant moves(In smaller markets, it could stay inefficient for a long time). So when Hurst Exponent shows significant values, the market has just entered significant trend or mean reversion state. However, when it stays outside of confidence interval for too long, it would suggest the market might be closer to the end of trend or mean reversion instead.
Larger sample size makes the Hurst Exponent Statistics more reliable. Therefore, if the user want to know if long term memory exist in general on the selected ticker, they can use a large sample size and maximize the log scale. Eg: 1024 sample size, scale (16,4).
Following Chart is Bitcoin on Daily timeframe with 1024 lookback. It suggests the market for bitcoin tends to have long term memory in general. It generally has significant trend and is more inefficient at it's early stage.
PST Bread Checklist v4Uses 50/200 EMA for higher-timeframe trend
Uses RSI zones + cross for entry
Adds volatility filter (ATR vs its own average)
Optional session filter (RTH 09:30–16:00)
Has a cooldown so you don’t get 10 labels in a row
Shows a checklist box + last signal
Goal Setting Strategies Viprasol# 🎯 Goal Setting Strategies Viprasol
A powerful goal tracking tool designed for disciplined traders who want to monitor their trading objectives, milestones, and progress directly on their charts.
## ✨ KEY FEATURES
### 📊 Flexible Goal Management
- Track anywhere from 1 to 20 trading goals simultaneously
- Adjustable goal count via simple input slider
- Each goal has its own unique emoji identifier
- Real-time progress counter
### ✅ Visual Tracking System
- Interactive checkbox system for goal completion
- Clear visual indicators (✅ completed, ⬜️ pending)
- Customizable goal names and descriptions
- Dynamic progress display
### 🎨 Full Customization
- **4 Position Options**: Top Left, Top Right, Bottom Left, Bottom Right
- **5 Font Sizes**: Tiny, Small, Normal, Large, Huge (optimized for all screen sizes)
- **Custom Colors**: Header, labels, background, achievement text
- **Premium Styling**: Modern cyber-themed design with professional appearance
### 💡 Perfect For:
- Daily/Weekly trading goal tracking
- Risk management milestones
- Profit target monitoring
- Trading plan compliance
- Personal development objectives
- Learning milestones
## 🔧 HOW TO USE
1. **Set Your Primary Goal**: Enter your main objective in "Primary Goal" field
2. **Choose Goal Count**: Select how many goals you want (1-20)
3. **Name Your Goals**: Customize each goal name in the "Goal Definitions" section
4. **Track Progress**: Check off goals as you complete them
5. **Customize Display**: Adjust colors, sizes, and position to match your chart setup
## 📐 INPUT GROUPS
### 🎯 Viprasol Goal Configuration
- Primary Goal Name
- Number of Goals (1-20)
### 📋 Goal Definitions
- All 20 goals with individual names and checkboxes
- Only enabled goals (based on count) will display
### 🌈 Premium Styling
- Goal Header Color
- Label Color
- Panel Background Color
- Achievement Color
- Header Font Size
- Milestone Font Size (Tiny/Small optimized for space)
### 📍 Elite Display
- Dashboard Position selector
## 💎 UNIQUE FEATURES
- **Space Efficient**: Tiny and Small font options for compact displays
- **Scalable**: Grow from 1 goal to 20 as your needs evolve
- **Non-Intrusive**: Overlay indicator that doesn't interfere with price action
- **Professional Design**: Clean, modern interface with cyber aesthetic
## 🎓 USE CASES
**Day Traders**: Track daily profit targets, trade count limits, max loss thresholds
**Swing Traders**: Monitor weekly/monthly goals, position management rules
**New Traders**: Learning milestones, strategy development checkpoints
**Experienced Traders**: Advanced risk management, portfolio objectives
## ⚙️ TECHNICAL DETAILS
- Version: Pine Script v5
- Type: Overlay Indicator
- Max Labels: 500
- Table-based display system
- No repainting
- Lightweight performance
## 🚀 GETTING STARTED
1. Add indicator to your chart
2. Set "Number of Goals" to your desired count (start small, scale up)
3. Customize goal names
4. Check boxes as you achieve goals
5. Watch your progress build!
## 📊 DISPLAY OPTIMIZATION
- Use "Tiny" or "Small" for maximum goals on small screens
- Use "Normal" or "Large" for standard monitors
- Use "Huge" for presentation or large displays
- Adjust position to avoid chart overlap
## 🎯 TRADING DISCIPLINE
This tool helps reinforce:
- Goal-oriented trading mindset
- Progress tracking accountability
- Milestone celebration
- Structured approach to trading development
---
**© viprasol**
*Designed for traders who take their goals seriously.*
Kịch bản của tôi//@version=6
indicator(title="Relative Strength Index", shorttitle="Gấu Trọc RSI", format=format.price, precision=2, timeframe="", timeframe_gaps=true)
rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="RSI Settings")
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
calculateDivergence = input.bool(false, title="Calculate Divergence", group="RSI Settings", display = display.data_window, tooltip = "Calculating divergences is needed in order for divergence alerts to fire.")
change = ta.change(rsiSourceInput)
up = ta.rma(math.max(change, 0), rsiLengthInput)
down = ta.rma(-math.min(change, 0), rsiLengthInput)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
rsiPlot = plot(rsi, "RSI", color=#7E57C2)
rsiUpperBand1 = hline(98, "RSI Upper Band1", color=#787B86)
rsiUpperBand = hline(70, "RSI Upper Band", color=#787B86)
midline = hline(50, "RSI Middle Band", color=color.new(#787B86, 50))
rsiLowerBand = hline(30, "RSI Lower Band", color=#787B86)
rsiLowerBand2 = hline(14, "RSI Lower Band2", color=#787B86)
fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")
midLinePlot = plot(50, color = na, editable = false, display = display.none)
fill(rsiPlot, midLinePlot, 100, 70, top_color = color.new(color.green, 0), bottom_color = color.new(color.green, 100), title = "Overbought Gradient Fill")
fill(rsiPlot, midLinePlot, 30, 0, top_color = color.new(color.red, 100), bottom_color = color.new(color.red, 0), title = "Oversold Gradient Fill")
// Smoothing MA inputs
GRP = "Smoothing"
TT_BB = "Only applies when 'SMA + Bollinger Bands' is selected. Determines the distance between the SMA and the bands."
maTypeInput = input.string("SMA", "Type", options = , group = GRP, display = display.data_window)
var isBB = maTypeInput == "SMA + Bollinger Bands"
maLengthInput = input.int(14, "Length", group = GRP, display = display.data_window, active = maTypeInput != "None")
bbMultInput = input.float(2.0, "BB StdDev", minval = 0.001, maxval = 50, step = 0.5, tooltip = TT_BB, group = GRP, display = display.data_window, active = isBB)
var enableMA = maTypeInput != "None"
// Smoothing MA Calculation
ma(source, length, MAtype) =>
switch MAtype
"SMA" => ta.sma(source, length)
"SMA + Bollinger Bands" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
// Smoothing MA plots
smoothingMA = enableMA ? ma(rsi, maLengthInput, maTypeInput) : na
smoothingStDev = isBB ? ta.stdev(rsi, maLengthInput) * bbMultInput : na
plot(smoothingMA, "RSI-based MA", color=color.yellow, display = enableMA ? display.all : display.none, editable = enableMA)
bbUpperBand = plot(smoothingMA + smoothingStDev, title = "Upper Bollinger Band", color=color.green, display = isBB ? display.all : display.none, editable = isBB)
bbLowerBand = plot(smoothingMA - smoothingStDev, title = "Lower Bollinger Band", color=color.green, display = isBB ? display.all : display.none, editable = isBB)
fill(bbUpperBand, bbLowerBand, color= isBB ? color.new(color.green, 90) : na, title="Bollinger Bands Background Fill", display = isBB ? display.all : display.none, editable = isBB)
// Divergence
lookbackRight = 5
lookbackLeft = 5
rangeUpper = 60
rangeLower = 5
bearColor = color.red
bullColor = color.green
textColor = color.white
noneColor = color.new(color.white, 100)
_inRange(bool cond) =>
bars = ta.barssince(cond)
rangeLower <= bars and bars <= rangeUpper
plFound = false
phFound = false
bullCond = false
bearCond = false
rsiLBR = rsi
if calculateDivergence
//------------------------------------------------------------------------------
// Regular Bullish
// rsi: Higher Low
plFound := not na(ta.pivotlow(rsi, lookbackLeft, lookbackRight))
rsiHL = rsiLBR > ta.valuewhen(plFound, rsiLBR, 1) and _inRange(plFound )
// Price: Lower Low
lowLBR = low
priceLL = lowLBR < ta.valuewhen(plFound, lowLBR, 1)
bullCond := priceLL and rsiHL and plFound
//------------------------------------------------------------------------------
// Regular Bearish
// rsi: Lower High
phFound := not na(ta.pivothigh(rsi, lookbackLeft, lookbackRight))
rsiLH = rsiLBR < ta.valuewhen(phFound, rsiLBR, 1) and _inRange(phFound )
// Price: Higher High
highLBR = high
priceHH = highLBR > ta.valuewhen(phFound, highLBR, 1)
bearCond := priceHH and rsiLH and phFound
plot(
plFound ? rsiLBR : na,
offset = -lookbackRight,
title = "Regular Bullish",
linewidth = 2,
color = (bullCond ? bullColor : noneColor),
display = display.pane,
editable = calculateDivergence)
plotshape(
bullCond ? rsiLBR : na,
offset = -lookbackRight,
title = "Regular Bullish Label",
text = " Bull ",
style = shape.labelup,
location = location.absolute,
color = bullColor,
textcolor = textColor,
display = display.pane,
editable = calculateDivergence)
plot(
phFound ? rsiLBR : na,
offset = -lookbackRight,
title = "Regular Bearish",
linewidth = 2,
color = (bearCond ? bearColor : noneColor),
display = display.pane,
editable = calculateDivergence)
plotshape(
bearCond ? rsiLBR : na,
offset = -lookbackRight,
title = "Regular Bearish Label",
text = " Bear ",
style = shape.labeldown,
location = location.absolute,
color = bearColor,
textcolor = textColor,
display = display.pane,
editable = calculateDivergence)
alertcondition(bullCond, title='Regular Bullish Divergence', message="Found a new Regular Bullish Divergence, `Pivot Lookback Right` number of bars to the left of the current bar.")
alertcondition(bearCond, title='Regular Bearish Divergence', message='Found a new Regular Bearish Divergence, `Pivot Lookback Right` number of bars to the left of the current bar.')
Penny Stock Golden Cross ScannerPenny Stock Golden Cross Scanner
Scan and track potential breakout opportunities in penny stocks with this Golden Cross Scanner. Designed for traders looking at low-priced, high-volume stocks, this indicator identifies bullish setups using 50, 100, and 200-period moving averages.
Key Features:
✅ Monitors up to 10 user-defined tickers.
✅ Filters penny stocks by maximum price and minimum volume.
✅ Detects proximity to 100 MA and 200 MA for potential golden cross or support/resistance signals.
✅ Assigns signal tiers for each stock (Tier 1 🔥, Tier 2 ⚡, Tier 3 📊) based on price action relative to moving averages.
✅ Customizable scanner table with position options on the chart.
✅ Real-time plotting of 50, 100, and 200 moving averages for context.
✅ Option to display only stocks currently generating signals.
Current Candle Vertical LineDescription
The Current Candle Vertical Line indicator draws a fully customizable vertical line on the most recent candle (live bar). This provides a clear visual anchor for active traders, especially during fast-moving markets or multi-chart setups.
The line extends from the top of the chart to the bottom, ensuring maximum visibility—regardless of zoom level or price scale.
Features
✔ Fully customizable line color
✔ Adjustable opacity (0–100%)
✔ Custom line thickness
✔ Three selectable line styles: Solid, Dashed, or Dotted
✔ Automatically deletes old line and redraws on the newest bar
✔ Works on any timeframe, chart type, and asset
Use Cases
Highlight the current candle during live trading
Keep visual focus when scalping or trading futures
Align entries with indicators on lower or higher timeframes
Improve visibility during high volatility
Support multi-monitor or multi-chart layouts
Notes
The indicator draws the line only on the last active bar.
Since overlay=true, the line appears in the main chart panel.
This script does not generate alerts (visual marker only).






















