Oil ETF VolumeDirexxion Daily has both 'bear' and 'bull' oil ETFs. This tracks the volume in both combined. It also tracks them individually: the bear ETF is the red line, and bull the green.
NOTE: the color of the volume bars is determined by whatever ticker you're currently looking at, and whether current close is gt/lt previous close. It is intended to be used while looking at the USOIL chart. The colors will be inverted if you're looking at the 'bear' ETF! as the higher closes will actually mean price is going down :D
Cari skrip untuk "国泰黄金ETF联接C跟踪指数市盈率百分位及估值水平"
Leveraged ETF Volume Ratio3x/2x Long/short etf pairs for popular tickers, including TSLA, QQQ, META, PLTR... Extreme values indicate bullish/bearish sentiment.
Standardized Leveraged ETF Fund of FlowsThis indicator tracks and standardizes the 3-month fund flows of major leveraged ETFs across different asset classes, including equities, gold, and bonds.
The fund flows are summed over a 3-month period (63 trading days) and then standardized using a 500-day rolling mean and standard deviation.
The resulting normalized fund flow values are plotted in three distinct colors:
Blue for Equities Fund Flows
Yellow for Gold Fund Flows
Green for Bond Fund Flows
CE - 42MACRO Fixed Income and Macro This is Part 2 of 2 from the 42MACRO Recreation Series
However, there will be a bonus Indicator coming soon!
The CE - 42MACRO Fixed Income and Macro Table is a next level Macroeconomic and market analysis indicator.
It aims to provide a probabilistic insight into the market realized GRID Macro regimes,
track a multiplex of important Assets, Indices, Bonds and ETF's to derive extra market insights by showing the most important aggregates and their performance over multiple timeframes... and what that might mean for the whole market direction.
For traders and especially investors, the unique functionalities will be of high value.
Quick guide on how to use it:
docs.google.com
WARNING
By the nature of the macro regimes, the outcomes are more accurate over longer Chart Timeframes (Week to Months).
However, it is also a valuable tool to form an advanced,
market realized, short to medium term bias.
NOTE
This Indicator is intended to be used alongside the 1nd part "CE - 42MACRO Equity Factor"
for a more wholistic approach and higher accuracy.
Methodology:
The Equity Factor Table tracks specifically chosen Assets to identify their performance and add the combined performances together to visualize 42MACRO's GRID Equity Model.
For this it uses the below Assets:
Convertibles ( AMEX:CWB )
Leveraged Loans ( AMEX:BKLN )
High Yield Credit ( AMEX:HYG )
Preferreds ( NASDAQ:PFF )
Emerging Market US$ Bonds ( NASDAQ:EMB )
Long Bond ( NASDAQ:TLT )
5-10yr Treasurys ( NASDAQ:IEF )
5-10yr TIPS ( AMEX:TIP )
0-5yr TIPS ( AMEX:STIP )
EM Local Currency Bonds ( AMEX:EMLC )
BDCs ( AMEX:BIZD )
Barclays Agg ( AMEX:AGG )
Investment Grade Credit ( AMEX:LQD )
MBS ( NASDAQ:MBB )
1-3yr Treasurys ( NASDAQ:SHY )
Bitcoin ( AMEX:BITO )
Industrial Metals ( AMEX:DBB )
Commodities ( AMEX:DBC )
Gold ( AMEX:GLD )
Equity Volatility ( AMEX:VIXM )
Interest Rate Volatility ( AMEX:PFIX )
Energy ( AMEX:USO )
Precious Metals ( AMEX:DBP )
Agriculture ( AMEX:DBA )
US Dollar ( AMEX:UUP )
Inverse US Dollar ( AMEX:UDN )
Functionalities:
Fixed Income and Macro Table
Shows relative market Asset performance
Comes with different Calculation options like RoC,
Sharpe ratio, Sortino ratio, Omega ratio and Normalization
Allows for advanced market (health) performance
Provides the calculated, realized GRID market regimes
Informs about "Risk ON" and "Risk OFF" market states
Visuals - for your best experience only use one (+ BarColoring) at a time:
You can visualize all important metrics:
- GRID regimes of the currently chosen calculation type
- Risk On/Risk Off with background colouring and additional +1/-1 values
- a smoother GRID model
- a smoother Risk On/ Risk Off metric
- Barcoloring for enabled metric of the above
If you have more suggestions, please write me
Fixed Income and Macro:
The visualisation of the relative performance of the different assets provides valuable information about the current market environment and the actual market performance.
It furthermore makes it possible to obtain a deeper understanding of how the interconnected market works and makes it simple to identify the actual market direction,
thus also providing all the information to derive overall market health, market strength or weakness.
Utility:
The Fixed Income and Macro Table is divided in 4 Columns which are the GRID regimes:
Economic Growth:
Goldilocks
Reflation
Economic Contraction:
Inflation
Deflation
Top 5 Fixed Income/ Macro Factors:
Are the values green for a specific Column?
If so then the market reflects the corresponding GRID behavior.
Bottom 5 Fixed Income/ Macro Factors:
Are the values red for a specific Column?
If so then the market reflects the corresponding GRID behavior.
So if we have Goldilocks as current regime we would see green values in the Top 5 Goldilocks Cells and red values in the Bottom 5 Goldilocks Cells.
You will find that Reflation will look similar, as it is also a sign of Economic Growth.
Same is the case for the two Contraction regimes.
******
This Indicator again is based to a majority on 42MACRO's models.
I only brought them into TV and added things on top of it.
If you have questions or need a more in-depth guide DM me.
GM
RSI - S&P Sector ETFsThe script displays RSI of each S&P SPDR Sector ETF
XLB - Materials
XLC - Communications
XLE - Energy
XLF - Financials
XLI - Industrials
XLK - Technology
XLP - Consumer Staples
XLRE - Real Estate
XLU - Utilities
XLV - Healthcare
XLY - Consumer Discretionary
It is meant to identify changes in sector rotation, compare oversold/overbought signals of each sector, and/or any price momentum trading strategy applicable to a trader.
InfoPanel - SeasonalityThis panel will show which is the best month to buy a stock, index or ETF or even a cryptocurrency in the past 5 years.
Script to use only with MONTHLY timeframe.
Thanks to: RicardoSantos for his hard work.
Please use comment section for any feedback.
Market Status PanelMarket Status Panel - Real-Time Trading Dashboard
A clean, minimalist heads-up display that shows critical market conditions at a glance. No chart clutter—just the essential information you need to make informed trading decisions.
What It Does
This indicator creates a compact information panel in the bottom-right corner of your chart, displaying four key metrics that update in real-time:
Relative Volume - Shows if current volume is high or low compared to the 20-bar average, with the exact multiplier
MACD Trend - Displays whether the MACD line is above (bullish) or below (bearish) the signal line
Overall Trend - Identifies market direction based on EMA alignment (9, 21, and 200 periods)
ATR Value - Shows the current Average True Range for volatility assessment
How to Use It
Simply add the indicator to your chart. The panel automatically updates on every bar and provides color-coded status indicators:
Green = Bullish/High (favorable conditions)
Red = Bearish/Low (caution conditions)
Gray = Neutral (no clear trend)
Use this dashboard to quickly assess:
Whether volume supports the current move
If momentum (MACD) aligns with price action
The strength and direction of the overall trend
Current volatility levels for position sizing
Settings
All key parameters are customizable:
Moving Averages:
EMA Fast (default: 9)
EMA Medium (default: 21)
EMA Long (default: 200)
MACD:
Fast length (default: 12)
Slow length (default: 26)
Signal length (default: 9)
Volume:
High volume threshold multiplier (default: 1.5x)
Volume average length (default: 20)
ATR:
ATR calculation period (default: 14)
Best For
Day traders who need quick market condition assessment
Scalpers looking for volume and momentum confirmation
Swing traders checking trend alignment
Anyone who wants critical data without visual chart clutter
Features
✓ Lightweight and non-intrusive
✓ Works on any timeframe
✓ All metrics update in real-time
✓ Fully customizable parameters
✓ Color-coded for instant readability
✓ No alerts or notifications (pure information display)
Ultimate Oscillator (ULTOSC)The Ultimate Oscillator (ULTOSC) is a technical momentum indicator developed by Larry Williams that combines three different time periods to reduce the volatility and false signals common in single-period oscillators. By using a weighted average of three Stochastic-like calculations across short, medium, and long-term periods, the Ultimate Oscillator provides a more comprehensive view of market momentum while maintaining sensitivity to price changes.
The indicator addresses the common problem of oscillators being either too sensitive (generating many false signals) or too slow (missing opportunities). By incorporating multiple timeframes with decreasing weights for longer periods, ULTOSC attempts to capture both short-term momentum shifts and longer-term trend strength, making it particularly valuable for identifying divergences and potential reversal points.
## Core Concepts
* **Multi-timeframe analysis:** Combines three different periods (typically 7, 14, 28) to capture various momentum cycles
* **Weighted averaging:** Assigns higher weights to shorter periods for responsiveness while including longer periods for stability
* **Buying pressure focus:** Measures the relationship between closing price and the true range rather than just high-low range
* **Divergence detection:** Particularly effective at identifying momentum divergences that precede price reversals
* **Normalized scale:** Oscillates between 0 and 100, with clear overbought/oversold levels
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Fast Period | 7 | Short-term momentum calculation | Lower (5-6) for more sensitivity, higher (9-12) for smoother signals |
| Medium Period | 14 | Medium-term momentum calculation | Adjust based on typical swing duration in the market |
| Slow Period | 28 | Long-term momentum calculation | Higher values (35-42) for longer-term position trading |
| Fast Weight | 4.0 | Weight applied to fast period | Higher weight increases short-term sensitivity |
| Medium Weight | 2.0 | Weight applied to medium period | Adjust to balance medium-term influence |
| Slow Weight | 1.0 | Weight applied to slow period | Usually kept at 1.0 as the baseline weight |
**Pro Tip:** The classic 7/14/28 periods with 4/2/1 weights work well for most markets, but consider using 5/10/20 with adjusted weights for faster markets or 14/28/56 for longer-term analysis.
## Calculation and Mathematical Foundation
**Simplified explanation:**
The Ultimate Oscillator calculates three separate "buying pressure" ratios using different time periods, then combines them using weighted averaging. Buying pressure is defined as the close minus the true low, divided by the true range.
**Technical formula:**
```
BP = Close - Min(Low, Previous Close)
TR = Max(High, Previous Close) - Min(Low, Previous Close)
BP_Sum_Fast = Sum(BP, Fast Period)
TR_Sum_Fast = Sum(TR, Fast Period)
Raw_Fast = 100 × (BP_Sum_Fast / TR_Sum_Fast)
BP_Sum_Medium = Sum(BP, Medium Period)
TR_Sum_Medium = Sum(TR, Medium Period)
Raw_Medium = 100 × (BP_Sum_Medium / TR_Sum_Medium)
BP_Sum_Slow = Sum(BP, Slow Period)
TR_Sum_Slow = Sum(TR, Slow Period)
Raw_Slow = 100 × (BP_Sum_Slow / TR_Sum_Slow)
ULTOSC = 100 × / (Fast_Weight + Medium_Weight + Slow_Weight)
```
Where:
- BP = Buying Pressure
- TR = True Range
- Fast Period = 7, Medium Period = 14, Slow Period = 28 (defaults)
- Fast Weight = 4, Medium Weight = 2, Slow Weight = 1 (defaults)
> 🔍 **Technical Note:** The implementation uses efficient circular buffers for all three period calculations, maintaining O(1) time complexity per bar. The algorithm properly handles true range calculations including gaps and ensures accurate buying pressure measurements across all timeframes.
## Interpretation Details
ULTOSC provides several analytical perspectives:
* **Overbought/Oversold conditions:** Values above 70 suggest overbought conditions, below 30 suggest oversold conditions
* **Momentum direction:** Rising ULTOSC indicates increasing buying pressure, falling indicates increasing selling pressure
* **Divergence analysis:** Divergences between ULTOSC and price often precede significant reversals
* **Trend confirmation:** ULTOSC direction can confirm or question the prevailing price trend
* **Signal quality:** Extreme readings (>80 or <20) indicate strong momentum that may be unsustainable
* **Multiple timeframe consensus:** When all three underlying periods agree, signals are typically more reliable
## Trading Applications
**Primary Uses:**
- **Divergence trading:** Identify when momentum diverges from price for reversal signals
- **Overbought/oversold identification:** Find potential entry/exit points at extreme levels
- **Trend confirmation:** Validate breakouts and trend continuations
- **Momentum analysis:** Assess the strength of current price movements
**Advanced Strategies:**
- **Multi-divergence confirmation:** Look for divergences across multiple timeframes
- **Momentum breakouts:** Trade when ULTOSC breaks above/below key levels with volume
- **Swing trading entries:** Use oversold/overbought levels for swing position entries
- **Trend strength assessment:** Evaluate trend quality using momentum consistency
## Signal Combinations
**Strong Bullish Signals:**
- ULTOSC rises from oversold territory (<30) with positive price divergence
- ULTOSC breaks above 50 after forming a base near 30
- All three underlying periods show increasing buying pressure
**Strong Bearish Signals:**
- ULTOSC falls from overbought territory (>70) with negative price divergence
- ULTOSC breaks below 50 after forming a top near 70
- All three underlying periods show decreasing buying pressure
**Divergence Signals:**
- **Bullish divergence:** Price makes lower lows while ULTOSC makes higher lows
- **Bearish divergence:** Price makes higher highs while ULTOSC makes lower highs
- **Hidden bullish divergence:** Price makes higher lows while ULTOSC makes lower lows (trend continuation)
- **Hidden bearish divergence:** Price makes lower highs while ULTOSC makes higher highs (trend continuation)
## Comparison with Related Oscillators
| Indicator | Periods | Focus | Best Use Case |
|-----------|---------|-------|---------------|
| **Ultimate Oscillator** | 3 periods | Buying pressure | Divergence detection |
| **Stochastic** | 1-2 periods | Price position | Overbought/oversold |
| **RSI** | 1 period | Price momentum | Momentum analysis |
| **Williams %R** | 1 period | Price position | Short-term signals |
## Advanced Configurations
**Fast Trading Setup:**
- Fast: 5, Medium: 10, Slow: 20
- Weights: 4/2/1, Thresholds: 75/25
**Standard Setup:**
- Fast: 7, Medium: 14, Slow: 28
- Weights: 4/2/1, Thresholds: 70/30
**Conservative Setup:**
- Fast: 14, Medium: 28, Slow: 56
- Weights: 3/2/1, Thresholds: 65/35
**Divergence Focused:**
- Fast: 7, Medium: 14, Slow: 28
- Weights: 2/2/2, Thresholds: 70/30
## Market-Specific Adjustments
**Volatile Markets:**
- Use longer periods (10/20/40) to reduce noise
- Consider higher threshold levels (75/25)
- Focus on extreme readings for signal quality
**Trending Markets:**
- Emphasize divergence analysis over absolute levels
- Look for momentum confirmation rather than reversal signals
- Use hidden divergences for trend continuation
**Range-Bound Markets:**
- Standard overbought/oversold levels work well
- Trade reversals from extreme levels
- Combine with support/resistance analysis
## Limitations and Considerations
* **Lagging component:** Contains inherent lag due to multiple moving average calculations
* **Complex calculation:** More computationally intensive than single-period oscillators
* **Parameter sensitivity:** Performance varies significantly with different period/weight combinations
* **Market dependency:** Most effective in trending markets with clear momentum patterns
* **False divergences:** Not all divergences lead to significant price reversals
* **Whipsaw potential:** Can generate conflicting signals in choppy markets
## Best Practices
**Effective Usage:**
- Focus on divergences rather than absolute overbought/oversold levels
- Combine with trend analysis for context
- Use multiple timeframe analysis for confirmation
- Pay attention to the speed of momentum changes
**Common Mistakes:**
- Over-relying on overbought/oversold levels in strong trends
- Ignoring the underlying trend direction
- Using inappropriate period settings for the market being analyzed
- Trading every divergence without additional confirmation
**Signal Enhancement:**
- Combine with volume analysis for confirmation
- Use price action context (support/resistance levels)
- Consider market volatility when setting thresholds
- Look for convergence across multiple momentum indicators
## Historical Context and Development
The Ultimate Oscillator was developed by Larry Williams and introduced in his 1985 article "The Ultimate Oscillator" in Technical Analysis of Stocks and Commodities magazine. Williams designed it to address the limitations of single-period oscillators by:
- Reducing false signals through multi-timeframe analysis
- Maintaining sensitivity to short-term momentum changes
- Providing more reliable divergence signals
- Creating a more robust momentum measurement tool
The indicator has become a standard tool in technical analysis, particularly valued for its divergence detection capabilities and its balanced approach to momentum measurement.
## References
* Williams, L. R. (1985). The Ultimate Oscillator. Technical Analysis of Stocks and Commodities, 3(4).
* Williams, L. R. (1999). Long-Term Secrets to Short-Term Trading. Wiley Trading.
Standardization (Z-score)Standardization, often referred to as Z-score normalization, is a data preprocessing technique that rescales data to have a mean of 0 and a standard deviation of 1. The resulting values, known as Z-scores, indicate how many standard deviations an individual data point is from the mean of the dataset (or a rolling sample of it).
This indicator calculates and plots the Z-score for a given input series over a specified lookback period. It is a fundamental tool for statistical analysis, outlier detection, and preparing data for certain machine learning algorithms.
## Core Concepts
* **Standardization:** The process of transforming data to fit a standard normal distribution (or more generally, to have a mean of 0 and standard deviation of 1).
* **Z-score (Standard Score):** A dimensionless quantity that represents the number of standard deviations by which a data point deviates from the mean of its sample.
The formula for a Z-score is:
`Z = (x - μ) / σ`
Where:
* `x` is the individual data point (e.g., current value of the source series).
* `μ` (mu) is the mean of the sample (calculated over the lookback period).
* `σ` (sigma) is the standard deviation of the sample (calculated over the lookback period).
* **Mean (μ):** The average value of the data points in the sample.
* **Standard Deviation (σ):** A measure of the amount of variation or dispersion of a set of values. A low standard deviation indicates that the values tend to be close to the mean, while a high standard deviation indicates that the values are spread out over a wider range.
## Common Settings and Parameters
| Parameter | Type | Default | Function | When to Adjust |
| :-------------- | :----------- | :------ | :------------------------------------------------------------------------------------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Source | series float | close | The input data series (e.g., price, volume, indicator values). | Choose the series you want to standardize. |
| Lookback Period | int | 20 | The number of bars (sample size) used for calculating the mean (μ) and standard deviation (σ). Min 2. | A larger period provides more stable estimates of μ and σ but will be less responsive to recent changes. A shorter period is more reactive. `minval` is 2 because `ta.stdev` requires it. |
**Pro Tip:** Z-scores are excellent for identifying anomalies or extreme values. For instance, applying Standardization to trading volume can help quickly spot days with unusually high or low activity relative to the recent norm (e.g., Z-score > 2 or < -2).
## Calculation and Mathematical Foundation
The Z-score is calculated for each bar as follows, using a rolling window defined by the `Lookback Period`:
1. **Calculate Mean (μ):** The simple moving average (`ta.sma`) of the `Source` data over the specified `Lookback Period` is calculated. This serves as the sample mean `μ`.
`μ = ta.sma(Source, Lookback Period)`
2. **Calculate Standard Deviation (σ):** The standard deviation (`ta.stdev`) of the `Source` data over the same `Lookback Period` is calculated. This serves as the sample standard deviation `σ`.
`σ = ta.stdev(Source, Lookback Period)`
3. **Calculate Z-score:**
* If `σ > 0`: The Z-score is calculated using the formula:
`Z = (Current Source Value - μ) / σ`
* If `σ = 0`: This implies all values in the lookback window are identical (and equal to the mean). In this case, the Z-score is defined as 0, as the current source value is also equal to the mean.
* If `σ` is `na` (e.g., insufficient data in the lookback period), the Z-score is `na`.
> 🔍 **Technical Note:**
> * The `Lookback Period` must be at least 2 for `ta.stdev` to compute a valid standard deviation.
> * The Z-score calculation uses the sample mean and sample standard deviation from the rolling lookback window.
## Interpreting the Z-score
* **Magnitude and Sign:**
* A Z-score of **0** means the data point is identical to the sample mean.
* A **positive Z-score** indicates the data point is above the sample mean. For example, Z = 1 means the point is 1 standard deviation above the mean.
* A **negative Z-score** indicates the data point is below the sample mean. For example, Z = -1 means the point is 1 standard deviation below the mean.
* **Typical Range:** For data that is approximately normally distributed (bell-shaped curve):
* About 68% of Z-scores fall between -1 and +1.
* About 95% of Z-scores fall between -2 and +2.
* About 99.7% of Z-scores fall between -3 and +3.
* **Outlier Detection:** Z-scores significantly outside the -2 to +2 range, and especially outside -3 to +3, are often considered outliers or extreme values relative to the recent historical data in the lookback window.
* **Volatility Indication:** When applied to price, large absolute Z-scores can indicate moments of high volatility or significant deviation from the recent price trend.
The indicator plots horizontal lines at ±1, ±2, and ±3 standard deviations to help visualize these common thresholds.
## Common Applications
1. **Outlier Detection:** Identifying data points that are unusual or extreme compared to the rest of the sample. This is a primary use in financial markets for spotting abnormal price moves, volume spikes, etc.
2. **Comparative Analysis:** Allows for comparison of scores from different distributions that might have different means and standard deviations. For example, comparing the Z-score of returns for two different assets.
3. **Feature Scaling in Machine Learning:** Standardizing features to have a mean of 0 and standard deviation of 1 is a common preprocessing step for many machine learning algorithms (e.g., SVMs, logistic regression, neural networks) to improve performance and convergence.
4. **Creating Normalized Oscillators:** The Z-score itself can be used as a bounded (though not strictly between -1 and +1) oscillator, indicating how far the current price has deviated from its moving average in terms of standard deviations.
5. **Statistical Process Control:** Used in quality control charts to monitor if a process is within expected statistical limits.
## Limitations and Considerations
* **Assumption of Normality for Probabilistic Interpretation:** While Z-scores can always be calculated, the probabilistic interpretations (e.g., "68% of data within ±1σ") strictly apply to normally distributed data. Financial data is often not perfectly normal (e.g., it can have fat tails).
* **Sensitivity of Mean and Standard Deviation to Outliers:** The sample mean (μ) and standard deviation (σ) used in the Z-score calculation can themselves be influenced by extreme outliers within the lookback period. This can sometimes mask or exaggerate the Z-score of other points.
* **Choice of Lookback Period:** The Z-score is highly dependent on the `Lookback Period`. A short period makes it very sensitive to recent fluctuations, while a long period makes it smoother and less responsive. The appropriate period depends on the analytical goal.
* **Stationarity:** For time series data, Z-scores are calculated based on a rolling window. This implicitly assumes some level of local stationarity (i.e., the mean and standard deviation are relatively stable within the window).
Triangular Moving Average (TRIMA)The Triangular Moving Average (TRIMA) is a technical indicator that applies a triangular weighting scheme to price data, providing enhanced smoothing compared to simpler moving averages. Originating in the early 1970s as technical analysts sought more effective noise filtering methods, the TRIMA was first popularized through the work of market technician Arthur Merrill. Its formal mathematical properties were established in the 1980s, and the indicator gained widespread adoption in the 1990s as computerized charting became standard. TRIMA effectively filters out market noise while maintaining important trends through its unique center-weighted calculation method.
## Core Concepts
* **Double-smoothing process:** TRIMA can be viewed as applying a simple moving average twice, creating more effective noise filtering
* **Triangular weighting:** Uses a symmetrical weight distribution that emphasizes central data points and reduces emphasis toward both ends
* **Constant-time implementation:** Two $O(1)$ SMA passes with circular buffers preserve exact triangular weights while keeping update cost constant per bar
* **Market application:** Particularly effective for identifying the underlying trend in noisy market conditions where standard moving averages generate too many false signals
* **Timeframe flexibility:** Works across multiple timeframes, with longer periods providing cleaner trend signals in higher timeframes
The core innovation of TRIMA is its unique triangular weighting scheme, which can be viewed either as a specialized weight distribution or as a twice-applied simple moving average with adjusted period. This creates more effective noise filtering without the excessive lag penalty typically associated with longer-period averages. The symmetrical nature of the weight distribution ensures zero phase distortion, preserving the timing of important market turning points.
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Length | 14 | Controls the lookback period | Increase for smoother signals in volatile markets, decrease for responsiveness |
| Source | close | Price data used for calculation | Consider using hlc3 for a more balanced price representation |
**Pro Tip:** For a good balance between smoothing and responsiveness, try using a TRIMA with period N instead of an SMA with period 2N - you'll get similar smoothing characteristics but with less lag.
## Calculation and Mathematical Foundation
**Simplified explanation:**
TRIMA calculates a weighted average of prices where the weights form a triangle shape. The middle prices get the most weight, and weights gradually decrease toward both the recent and older ends. This creates a smooth filter that effectively removes random price fluctuations while preserving the underlying trend.
**Technical formula:**
TRIMA = Σ(Price × Weight ) / Σ(Weight )
Where the triangular weights form a symmetric pattern:
- Weight = min(i, n-1-i) + 1
- Example for n=5: weights =
- Example for n=4: weights =
Alternatively, TRIMA can be calculated as:
TRIMA(source, p) = SMA(SMA(source, (p+1)/2), (p+1)/2)
> 🔍 **Technical Note:** The double application of SMA explains why TRIMA provides better smoothing than a single SMA or WMA. This approach effectively applies smoothing twice with optimal period adjustment, creating a -18dB/octave roll-off in the frequency domain compared to -6dB/octave for a simple moving average, and the current implementation achieves $O(1)$ complexity through circular buffers and NA-safe warmup compensation.
## Interpretation Details
TRIMA can be used in various trading strategies:
* **Trend identification:** The direction of TRIMA indicates the prevailing trend
* **Signal generation:** Crossovers between price and TRIMA generate trade signals with fewer false alarms than SMA
* **Support/resistance levels:** TRIMA can act as dynamic support during uptrends and resistance during downtrends
* **Trend strength assessment:** Distance between price and TRIMA can indicate trend strength
* **Multiple timeframe analysis:** Using TRIMAs with different periods can confirm trends across different timeframes
## Limitations and Considerations
* **Market conditions:** Like all moving averages, less effective in choppy, sideways markets
* **Lag factor:** More lag than WMA or EMA due to center-weighted emphasis
* **Limited adaptability:** Fixed weighting scheme cannot adapt to changing market volatility
* **Response time:** Takes longer to reflect sudden price changes than directionally-weighted averages
* **Complementary tools:** Best used with momentum oscillators or volume indicators for confirmation
## References
* Ehlers, John F. "Cycle Analytics for Traders." Wiley, 2013
* Kaufman, Perry J. "Trading Systems and Methods." Wiley, 2013
* Colby, Robert W. "The Encyclopedia of Technical Market Indicators." McGraw-Hill, 2002
Savitzky-Golay Filter (SGF)The Savitzky-Golay Filter (SGF) is a digital filter that performs local polynomial regression on a series of values to determine the smoothed value for each point. Developed by Abraham Savitzky and Marcel Golay in 1964, it is particularly effective at preserving higher moments of the data while reducing noise. This implementation provides a practical adaptation for financial time series, offering superior preservation of peaks, valleys, and other important market structures that might be distorted by simpler moving averages.
## Core Concepts
* **Local polynomial fitting:** Fits a polynomial of specified order to a sliding window of data points
* **Moment preservation:** Maintains higher statistical moments (peaks, valleys, inflection points)
* **Optimized coefficients:** Uses pre-computed coefficients for common polynomial orders
* **Adaptive weighting:** Weight distribution varies based on polynomial order and window size
* **Market application:** Particularly effective for preserving significant price movements while filtering noise
The core innovation of the Savitzky-Golay filter is its ability to smooth data while preserving important features that are often flattened by other filtering methods. This makes it especially valuable for technical analysis where maintaining the shape of price patterns is crucial.
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Window Size | 11 | Number of points used in local fitting (must be odd) | Increase for smoother output, decrease for better feature preservation |
| Polynomial Order | 2 | Order of fitting polynomial (2 or 4) | Use 2 for general smoothing, 4 for better peak preservation |
| Source | close | Price data used for calculation | Consider using hlc3 for more stable fitting |
**Pro Tip:** A window size of 11 with polynomial order 2 provides a good balance between smoothing and feature preservation. For sharper peaks and valleys, use order 4 with a smaller window size.
## Calculation and Mathematical Foundation
**Simplified explanation:**
The filter fits a polynomial of specified order to a moving window of price data. The smoothed value at each point is computed from this local fit, effectively removing noise while preserving the underlying shape of the data.
**Technical formula:**
For a window of size N and polynomial order M, the filtered value is:
y = Σ(c_i × x )
Where:
- c_i are the pre-computed filter coefficients
- x are the input values in the window
- Coefficients depend on window size N and polynomial order M
> 🔍 **Technical Note:** The implementation uses optimized coefficient calculations for orders 2 and 4, which cover most practical applications while maintaining computational efficiency.
## Interpretation Details
The Savitzky-Golay filter can be used in various trading strategies:
* **Pattern recognition:** Preserves chart patterns while removing noise
* **Peak detection:** Maintains amplitude and width of significant peaks
* **Trend analysis:** Smooths price movement without distorting important transitions
* **Divergence trading:** Better preservation of local maxima and minima
* **Volatility analysis:** Accurate representation of price movement dynamics
## Limitations and Considerations
* **Computational complexity:** More intensive than simple moving averages
* **Edge effects:** First and last few points may show end effects
* **Parameter sensitivity:** Performance depends on appropriate window size and order selection
* **Data requirements:** Needs sufficient points for polynomial fitting
* **Complementary tools:** Best used with volume analysis and momentum indicators
## References
* Savitzky, A., Golay, M.J.E. "Smoothing and Differentiation of Data by Simplified Least Squares Procedures," Analytical Chemistry, 1964
* Press, W.H. et al. "Numerical Recipes: The Art of Scientific Computing," Chapter 14
* Schafer, R.W. "What Is a Savitzky-Golay Filter?" IEEE Signal Processing Magazine, 2011
Bilateral Filter (BILATERAL)The Bilateral Filter is an edge-preserving smoothing technique that combines spatial filtering with intensity filtering to achieve noise reduction while maintaining significant price structure. Originally developed in computer vision for image processing, this adaptive filter has been adapted for financial time series analysis to provide superior smoothing that preserves important market transitions. The filter intelligently reduces noise in stable price regions while preserving sharp transitions like breakouts, reversals, and other significant market structures that would be blurred by conventional filters.
## Core Concepts
* **Dual-domain filtering:** Combines traditional time-based (spatial) filtering with value-based (range) filtering for adaptive smoothing
* **Edge preservation:** Maintains important price transitions while aggressively smoothing areas of minor fluctuation
* **Adaptive processing:** Automatically adjusts filtering strength based on local price characteristics
The core innovation of the Bilateral Filter is its ability to distinguish between random noise and significant price movements. Unlike conventional filters that smooth everything equally, Bilateral filtering preserves major price transitions by reducing the influence of price points that differ significantly from the current price, effectively preserving market structure while still eliminating noise.
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Length | 14 | Controls the lookback window size | Increase for more context in filtering decisions, decrease for quicker response |
| Sigma_S_Ratio | 0.3 | Controls spatial (time) weighting | Lower values emphasize recent bars, higher values distribute influence more evenly |
| Sigma_R_Mult | 2.0 | Controls range (price) sensitivity | Lower values increase edge preservation, higher values increase smoothing |
| Source | close | Price data used for calculation | Consider using hlc3 for a more balanced price representation |
**Pro Tip:** For breakout trading strategies, try reducing Sigma_R_Mult to 1.0-1.5 to make the filter more sensitive to significant price moves, allowing it to preserve breakout signals while still filtering noise.
## Calculation and Mathematical Foundation
**Simplified explanation:**
The Bilateral Filter calculates a weighted average of nearby prices, where the weights depend on two factors: how far away in time the price point is (spatial weight) and how different the price value is (range weight). Points that are close in time AND similar in value get the highest weight. This means stable price regions get smoothed while significant changes are preserved.
**Technical formula:**
BF = (1 / Wp) × Σ_{q ∈ S} G_s(||p - q||) × G_r(|I - I |) × I
Where:
- G_s is the spatial Gaussian kernel: exp(-||p - q||² / (2 × σ_s²))
- G_r is the range Gaussian kernel: exp(-|I - I |² / (2 × σ_r²))
- Wp is the normalization factor (sum of all weights)
> 🔍 **Technical Note:** The sigma_r parameter is typically calculated dynamically based on local price volatility (standard deviation) to provide adaptive filtering - this automatically adjusts filtering strength based on market conditions.
## Interpretation Details
The Bilateral Filter can be applied in various trading contexts:
* **Trend identification:** Reveals cleaner underlying price direction by removing noise while preserving trend changes
* **Support/resistance identification:** Provides clearer price levels by preserving significant turning points
* **Pattern recognition:** Maintains critical chart patterns while eliminating distracting minor fluctuations
* **Breakout trading:** Preserves sharp price transitions for more reliable breakout signals
* **Pre-processing:** Can be used as an initial filter before applying other technical indicators to reduce false signals
## Limitations and Considerations
* **Computational complexity:** More intensive calculations than traditional linear filters
* **Parameter sensitivity:** Performance highly dependent on proper parameter selection
* **Non-linearity:** Non-linear behavior may produce unexpected results in certain market conditions
* **Interpretation adjustment:** Requires different interpretation than conventional moving averages
* **Complementary tools:** Best used alongside volume analysis and traditional indicators for confirmation
## References
* Tomasi, C. and Manduchi, R. "Bilateral Filtering for Gray and Color Images," Proceedings of IEEE ICCV, 1998
* Paris, S. et al. "A Gentle Introduction to Bilateral Filtering and its Applications," ACM SIGGRAPH, 2008
Double Weighted Moving Average (DWMA)# DWMA: Double Weighted Moving Average
## Overview and Purpose
The Double Weighted Moving Average (DWMA) is a technical indicator that applies weighted averaging twice in sequence to create a smoother signal with enhanced noise reduction. Developed in the late 1990s as an evolution of traditional weighted moving averages, the DWMA was created by quantitative analysts seeking enhanced smoothing without the excessive lag typically associated with longer period averages. By applying a weighted moving average calculation to the results of an initial weighted moving average, DWMA achieves more effective filtering while preserving important trend characteristics.
## Core Concepts
* **Cascaded filtering:** DWMA applies weighted averaging twice in sequence for enhanced smoothing and superior noise reduction
* **Linear weighting:** Uses progressively increasing weights for more recent data in both calculation passes
* **Market application:** Particularly effective for trend following strategies where noise reduction is prioritized over rapid signal response
* **Timeframe flexibility:** Works across multiple timeframes but particularly valuable on daily and weekly charts for identifying significant trends
The core innovation of DWMA is its two-stage approach that creates more effective noise filtering while minimizing the additional lag typically associated with longer-period or higher-order filters. This sequential processing creates a more refined output that balances noise reduction and signal preservation better than simply increasing the length of a standard weighted moving average.
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Length | 14 | Controls the lookback period for both WMA calculations | Increase for smoother signals in volatile markets, decrease for more responsiveness |
| Source | close | Price data used for calculation | Consider using hlc3 for a more balanced price representation |
**Pro Tip:** For trend following, use a length of 10-14 with DWMA instead of a single WMA with double the period - this provides better smoothing with less lag than simply increasing the period of a standard WMA.
## Calculation and Mathematical Foundation
**Simplified explanation:**
DWMA first calculates a weighted moving average where recent prices have more importance than older prices. Then, it applies the same weighted calculation again to the results of the first calculation, creating a smoother line that reduces market noise more effectively.
**Technical formula:**
```
DWMA is calculated by applying WMA twice:
1. First WMA calculation:
WMA₁ = (P₁ × w₁ + P₂ × w₂ + ... + Pₙ × wₙ) / (w₁ + w₂ + ... + wₙ)
2. Second WMA calculation applied to WMA₁:
DWMA = (WMA₁₁ × w₁ + WMA₁₂ × w₂ + ... + WMA₁ₙ × wₙ) / (w₁ + w₂ + ... + wₙ)
```
Where:
- Linear weights: most recent value has weight = n, second most recent has weight = n-1, etc.
- n is the period length
- Sum of weights = n(n+1)/2
**O(1) Optimization - Inline Dual WMA Architecture:**
This implementation uses an advanced O(1) algorithm with two complete inline WMA calculations. Each WMA uses the dual running sums technique:
1. **First WMA (source → wma1)**:
- Maintains buffer1, sum1, weighted_sum1
- Recurrence: `W₁_new = W₁_old - S₁_old + (n × P_new)`
- Cached denominator norm1 after warmup
2. **Second WMA (wma1 → dwma)**:
- Maintains buffer2, sum2, weighted_sum2
- Recurrence: `W₂_new = W₂_old - S₂_old + (n × WMA₁_new)`
- Cached denominator norm2 after warmup
**Implementation details:**
- Both WMAs fully integrated inline (no helper functions)
- Each maintains independent state: buffers, sums, counters, norms
- Both warm up independently from bar 1
- Performance: ~16 operations per bar regardless of period (vs ~10,000 for naive O(n²) implementation)
**Why inline architecture:**
Unlike helper functions, the inline approach makes all state variables and calculations visible in a single scope, eliminating function call overhead and making the dual-pass nature explicit. This is ideal for educational purposes and when debugging complex cascaded filters.
> 🔍 **Technical Note:** The dual-pass O(1) approach creates a filter that effectively increases smoothing without the quadratic increase in computational cost. Original O(n²) implementations required ~10,000 operations for period=100; this optimized version requires only ~16 operations, achieving a 625x speedup while maintaining exact mathematical equivalence.
## Interpretation Details
DWMA can be used in various trading strategies:
* **Trend identification:** The direction of DWMA indicates the prevailing trend
* **Signal generation:** Crossovers between price and DWMA generate trade signals, though they occur later than with single WMA
* **Support/resistance levels:** DWMA can act as dynamic support during uptrends and resistance during downtrends
* **Trend strength assessment:** Distance between price and DWMA can indicate trend strength
* **Noise filtering:** Using DWMA to filter noisy price data before applying other indicators
## Limitations and Considerations
* **Market conditions:** Less effective in choppy, sideways markets where its lag becomes a disadvantage
* **Lag factor:** More lag than single WMA due to double calculation process
* **Initialization requirement:** Requires more data points for full calculation, showing more NA values at chart start
* **Short-term trading:** May miss short-term trading opportunities due to increased smoothing
* **Complementary tools:** Best used with momentum oscillators or volume indicators for confirmation
## References
* Jurik, M. "Double Weighted Moving Averages: Theory and Applications in Algorithmic Trading Systems", Jurik Research Papers, 2004
* Ehlers, J.F. "Cycle Analytics for Traders," Wiley, 2013
Weighted Moving Average (WMA)This implementation uses O(1) algorithm that eliminates the need to loop through all period values on each bar. It also generates valid WMA values from the first bar and is not returning NA when number of bars is less than period.
## Overview and Purpose
The Weighted Moving Average (WMA) is a technical indicator that applies progressively increasing weights to more recent price data. Emerging in the early 1950s during the formative years of technical analysis, WMA gained significant adoption among professional traders through the 1970s as computational methods became more accessible. The approach was formalized in Robert Colby's 1988 "Encyclopedia of Technical Market Indicators," establishing it as a staple in technical analysis software. Unlike the Simple Moving Average (SMA) which gives equal weight to all prices, WMA assigns greater importance to recent prices, creating a more responsive indicator that reacts faster to price changes while still providing effective noise filtering.
## Core Concepts
* **Linear weighting:** WMA applies progressively increasing weights to more recent price data, creating a recency bias that improves responsiveness
* **Market application:** Particularly effective for identifying trend changes earlier than SMA while maintaining better noise filtering than faster-responding averages like EMA
* **Timeframe flexibility:** Works effectively across all timeframes, with appropriate period adjustments for different trading horizons
The core innovation of WMA is its linear weighting scheme, which strikes a balance between the equal-weight approach of SMA and the exponential decay of EMA. This creates an intuitive and effective compromise that prioritizes recent data while maintaining a finite lookback period, making it particularly valuable for traders seeking to reduce lag without excessive sensitivity to price fluctuations.
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Length | 14 | Controls the lookback period | Increase for smoother signals in volatile markets, decrease for responsiveness |
| Source | close | Price data used for calculation | Consider using hlc3 for a more balanced price representation |
**Pro Tip:** For most trading applications, using a WMA with period N provides better responsiveness than an SMA with the same period, while generating fewer whipsaws than an EMA with comparable responsiveness.
## Calculation and Mathematical Foundation
**Simplified explanation:**
WMA calculates a weighted average of prices where the most recent price receives the highest weight, and each progressively older price receives one unit less weight. For example, in a 5-period WMA, the most recent price gets a weight of 5, the next most recent a weight of 4, and so on, with the oldest price getting a weight of 1.
**Technical formula:**
```
WMA = (P₁ × w₁ + P₂ × w₂ + ... + Pₙ × wₙ) / (w₁ + w₂ + ... + wₙ)
```
Where:
- Linear weights: most recent value has weight = n, second most recent has weight = n-1, etc.
- The sum of weights for a period n is calculated as: n(n+1)/2
- For example, for a 5-period WMA, the sum of weights is 5(5+1)/2 = 15
**O(1) Optimization - Dual Running Sums:**
The key insight is maintaining two running sums:
1. **Unweighted sum (S)**: Simple sum of all values in the window
2. **Weighted sum (W)**: Sum of all weighted values
The recurrence relation for a full window is:
```
W_new = W_old - S_old + (n × P_new)
```
This works because when all weights decrement by 1 (as the window slides), it's mathematically equivalent to subtracting the entire unweighted sum. The implementation:
- **During warmup**: Accumulates both sums as the window fills, computing denominator each bar
- **After warmup**: Uses cached denominator (constant at n(n+1)/2), updates both sums in constant time
- **Performance**: ~8 operations per bar regardless of period, vs ~100+ for naive O(n) implementation
> 🔍 **Technical Note:** Unlike EMA which theoretically considers all historical data (with diminishing influence), WMA has a finite memory, completely dropping prices that fall outside its lookback window. This creates a cleaner break from outdated market conditions. The O(1) optimization achieves 12-25x speedup over naive implementations while maintaining exact mathematical equivalence.
## Interpretation Details
WMA can be used in various trading strategies:
* **Trend identification:** The direction of WMA indicates the prevailing trend with greater responsiveness than SMA
* **Signal generation:** Crossovers between price and WMA generate trade signals earlier than with SMA
* **Support/resistance levels:** WMA can act as dynamic support during uptrends and resistance during downtrends
* **Moving average crossovers:** When a shorter-period WMA crosses above a longer-period WMA, it signals a potential uptrend (and vice versa)
* **Trend strength assessment:** Distance between price and WMA can indicate trend strength
## Limitations and Considerations
* **Market conditions:** Still suboptimal in highly volatile or sideways markets where enhanced responsiveness may generate false signals
* **Lag factor:** While less than SMA, still introduces some lag in signal generation
* **Abrupt window exit:** The oldest price suddenly drops out of calculation when leaving the window, potentially causing small jumps
* **Step changes:** Linear weighting creates discrete steps in influence rather than a smooth decay
* **Complementary tools:** Best used with volume indicators and momentum oscillators for confirmation
## References
* Colby, Robert W. "The Encyclopedia of Technical Market Indicators." McGraw-Hill, 2002
* Murphy, John J. "Technical Analysis of the Financial Markets." New York Institute of Finance, 1999
* Kaufman, Perry J. "Trading Systems and Methods." Wiley, 2013
Simple Moving Average (SMA)## Overview and Purpose
The Simple Moving Average (SMA) is one of the most fundamental and widely used technical indicators in financial analysis. It calculates the arithmetic mean of a selected range of prices over a specified number of periods. Developed in the early days of technical analysis, the SMA provides traders with a straightforward method to identify trends by smoothing price data and filtering out short-term fluctuations. Due to its simplicity and effectiveness, it remains a cornerstone indicator that forms the basis for numerous other technical analysis tools.
## What’s Different in this Implementation
- **Constant streaming update:**
On each bar we:
1) subtract the value leaving the window,
2) add the new value,
3) divide by the number of valid samples (early) or by `period` (once full).
- **Deterministic lag, same as textbook SMA:**
Once full, lag is `(period - 1)/2` bars—identical to the classic SMA. You just **don’t lose the first `period-1` bars** to `na`.
- **Large windows without penalty:**
Complexity is constant per tick; memory is bounded by `period`. Very long SMAs stay cheap.
## Behavior on Early Bars
- **Bars < period:** returns the arithmetic mean of **available** samples.
Example (period = 10): bar #3 is the average of the first 3 inputs—not `na`.
- **Bars ≥ period:** behaves exactly like standard SMA over a fixed-length window.
> Implication: Crosses and signals can appear earlier than with `ta.sma()` because you’re not suppressing the first `period-1` bars.
## When to Prefer This
- Backtests needing early bars: You want signals and state from the very first bars.
- High-frequency or very long SMAs: O(1) updates avoid per-bar CPU spikes.
- Memory-tight scripts: Single circular buffer; no large temp arrays per tick.
## Caveats & Tips
Backtest comparability: If you previously relied on na gating from ta.sma(), add your own warm-up guard (e.g., only trade after bar_index >= period-1) for apples-to-apples.
Missing data: The function treats the current bar via nz(source); adjust if you need strict NA propagation.
Window semantics: After warm-up, results match the textbook SMA window; early bars are a partial-window mean by design.
## Math Notes
Running-sum update:
sum_t = sum_{t-1} - oldest + newest
SMA_t = sum_t / k where k = min(#valid_samples, period)
Lag (full window): (period - 1) / 2 bars.
## References
- Edwards & Magee, Technical Analysis of Stock Trends
- Murphy, Technical Analysis of the Financial Markets
Adaptive Trend SelectorThe Adaptive Trend Selector is a comprehensive trend-following tool designed to automatically identify the optimal moving average crossover strategy. It features adjustable parameters and an integrated backtester that delivers institutional-grade insights into the recommended strategy. The model continuously adapts to new data in real time by evaluating multiple moving average combinations, determining the best performing lengths, and presenting the backtest results in a clear, color-coded table that benchmarks performance against the buy-and-hold strategy.
At its core, the model systematically backtests a wide range of moving average combinations to identify the configuration that maximizes the selected optimization metric. Users can choose to optimize for absolute returns or risk-adjusted returns using the Sharpe, Sortino, or Calmar ratios. Alternatively, users can enable manual optimization to test custom fast and slow moving average lengths and view the corresponding backtest results. The label displays the Compounded Annual Growth Rate (CAGR) of the strategy, with the buy-and-hold CAGR in parentheses for comparison. The table presents the backtest results based on the fast and slow lengths displayed at the top:
Sharpe = CAGR per unit of standard deviation.
Sortino = CAGR per unit of downside deviation.
Calmar = CAGR relative to maximum drawdown.
Max DD = Largest peak-to-trough decline in value.
Beta (β) = Return sensitivity relative to buy-and-hold.
Alpha (α) = Excess annualized risk-adjusted returns.
Win Rate = Ratio of profitable trades to total trades.
Profit Factor = Total gross profit per unit of losses.
Expectancy = Average expected return per trade.
Trades/Year = Average number of trades per year.
This indicator is designed with flexibility in mind, enabling users to specify the start date of the backtesting period and the preferred moving average strategy. Supported strategies include the Exponential Moving Average (EMA), Simple Moving Average (SMA), Wilder’s Moving Average (RMA), Weighted Moving Average (WMA), and Volume-Weighted Moving Average (VWMA). To minimize overfitting, users can define constraints such as a minimum and maximum number of trades per year, as well as an optional optimization margin that prioritizes longer, more robust combinations by requiring shorter-length strategies to exceed this threshold. The table follows an intuitive color logic that enables quick performance comparison against buy-and-hold (B&H):
Sharpe = Green indicates better than B&H, while red indicates worse.
Sortino = Green indicates better than B&H, while red indicates worse.
Calmar = Green indicates better than B&H, while red indicates worse.
Max DD = Green indicates better than B&H, while red indicates worse.
Beta (β) = Green indicates better than B&H, while red indicates worse.
Alpha (α) = Green indicates above 0%, while red indicates below 0%.
Win Rate = Green indicates above 50%, while red indicates below 50%.
Profit Factor = Green indicates above 2, while red indicates below 1.
Expectancy = Green indicates above 0%, while red indicates below 0%.
In summary, the Adaptive Trend Selector is a powerful tool designed to help investors make data-driven decisions when selecting moving average crossover strategies. By optimizing for risk-adjusted returns, investors can confidently identify the best lengths using institutional-grade metrics. While results are based on the selected historical period, users should be mindful of potential overfitting, as past results may not persist under future market conditions. Since the model recalibrates to incorporate new data, the recommended lengths may evolve over time.
Lump Sum Favorability (SPX & NDX)This indicator provides a visual dashboard to gauge the statistical favorability of deploying a "Lump Sum" investment into the SPX (S&P 500) or NDX (Nasdaq 100).
The primary goal is not to time the exact market bottom, but to identify zones of significant pessimism or euphoria. Historically, periods of indiscriminate selling have represented high-probability entry points for long-term investors.
The dashboard consists of two parts:
1. The Favorability Gauge: A 12-segment gauge that moves from Red (Unfavorable) to Teal (Favorable).
2. The Summary Text: An optional text box (enabled in settings) that provides a plain-English summary of the current market breadth.
---
The Method: Market Breadth
This indicator is not based on the price of the index itself. Price-based indicators (like an RSI on the SPX) can be misleading. In a market-cap-weighted index, a few mega-cap stocks can hold the index price up while the vast majority of "average" stocks are already in a deep bear market.
This tool uses Market Breadth to measure the true, underlying health and participation of the entire market.
How It Works
1. Data Source: The indicator pulls the daily percentage of companies within the selected index (SPX or NDX) that are trading above their 200-day moving average. (Data tickers: S5TH for SPX, NDTH for NDX).
2. Smoothing: This raw data is volatile. To filter out daily noise and confirm a persistent trend, the indicator calculates a 5-day Simple Moving Average (SMA) of this percentage. This is the value used by the indicator.
3. Interpretation:
High Value (>= 50%): More than half of the stocks are above their long-term average. This signifies the market is "Overheated" or in a risk-on phase. The favorability for a new lump sum investment is considered Low.
Low Value (< 50%): Less than half of the stocks are above their long-term average. This signifies "Oversold" conditions or capitulation. These moments historically offer the best favorability for starting a new long-term investment.
---
How to Use the Indicator
1. The Favorability Gauge
The gauge is designed to be intuitive: Red means "Stop/Caution," and Teal means "Go/Opportunity."
Note: The gauge's logic is inverted from the data value to achieve this simplicity.
Red Zone (Left): UNFAVORABLE
This corresponds to a high percentage of stocks being above their 200d MA (>= 50%). The market is considered Overheated, and the favorability for a new lump sum investment is low.
Teal Zone (Right): FAVORABLE
This corresponds to a low percentage of stocks being above their 200d MA (< 50%). The market is considered Oversold, and the favorability for a new lump sum investment is high.
2. The Summary Text
When "Show Summary Text" is enabled in the settings, a box will appear at the top-center of your chart. This box provides a clear, data-driven summary, such as:
"Currently, only 22% of S&P 500 companies are above their 200-day MA. Market is Oversold."
The color of this text will automatically change to match the market state (Red for Overheated, Teal for Oversold), providing instant confirmation of the gauge's reading.
---
Settings
Market: Choose the index to analyze: SPX (S&P 500) or NDX (Nasdaq 100).
Gauge Position: Select where the gauge dashboard should appear on your chart (default is Bottom Right).
Show Summary Text: Toggle the descriptive text box on or off (default is On).
---
This indicator is a statistical and historical guide, not a financial advice or timing signal. It is designed to measure favorability based on past market behavior, not to provide certainty.
Extreme oversold conditions can persist, and markets can always go lower. This tool should be used as one component of a broader investment and risk-management framework. Past performance is not a guarantee of future results.
Rainbow Moving Averages (v5 safe)Rainbow Moving Averages — plots multiple moving averages of different lengths in a rainbow colour scheme to visualise market trend strength and direction. The spread and alignment of the lines help identify trend changes and momentum shifts.
EMA HeatmapEMA Heatmap — Indicator Description
The EMA Order Heatmap is a visual trend-structure tool designed to show whether the market is currently trending bullish, trending bearish, or moving through a neutral consolidation phase. It evaluates the alignment of multiple exponential moving averages (EMAs) at three different structural layers: short-term daily, medium-term daily, and weekly macro trend. This creates a quick and intuitive picture of how well price movement is organized across timeframes.
Each layer of the heatmap is scored from bearish to bullish based on how the EMAs are stacked relative to each other. When EMAs are in a fully bullish configuration, the row displays a bright green or lime color. Fully bearish alignment is shown in red. Yellow tones appear when the EMAs are mixed or compressing, indicating uncertainty, trend exhaustion, or a change in market character. The three rows combined offer a concise view of whether strength or weakness is isolated to one timeframe or broad across the market.
This indicator is best used as a trend filter before making trading decisions. Traders may find more consistent setups when the majority of the heatmap supports the direction of their trade. Green-dominant conditions suggest a trending bullish environment where long trades can be favored. Red-dominant conditions indicate bearish momentum and stronger potential for short opportunities. When yellow becomes more prominent, the market may be transitioning, ranging, or gearing up for a breakout, making timing more challenging and risk higher.
• Helps quickly identify directional bias
• Highlights when trends strengthen, weaken, or turn
• Provides insight into whether momentum is supported by higher timeframes
• Encourages traders to avoid fighting market structure
It is important to recognize the limitations. EMAs are lagging indicators, so the heatmap may confirm a trend after the initial move is underway, especially during fast reversals. In sideways or low-volume environments, the structure can shift frequently, reducing clarity. This tool does not generate entry or exit signals on its own and should be paired with price action, momentum studies, or support and resistance analysis for precise trade execution.
The EMA Order Heatmap offers a clean and reliable way to stay aligned with the broader market environment and avoid lower-quality trades in indecisive conditions. It supports more disciplined decision-making by helping traders focus on setups that match the prevailing structural trend.
WaveTrend RBF What it does
WT-RBF extracts a “wave” of momentum by subtracting a fast Gaussian-weighted smoother from a slow one, then robust-normalizes that wave with a median/MAD proxy to produce a z-score (z). A short EMA of z forms the signal line. Optional dynamic thresholds use the MAD of z itself so overbought/oversold levels adapt to volatility regimes.
How it’s built:
Radial (Gaussian) smoothers
Causal, exponentially-decaying weights over the last radius bars using σ (sigma) to control spread.
fast = rbf_smooth(src, fastR, fastSig)
slow = rbf_smooth(src, slowR, slowSig)
wave = fast − slow (band-pass)
Robust normalization
A two-stage EMA approximates the median; MAD is estimated from EMA of absolute deviations and scaled by 1.4826 to be stdev-comparable.
z = (wave − center) / MAD
Thresholds
Dynamic OB/OS: ±2.5 × MAD(z) (or fixed levels when disabled)
Reading the indicator
Bull Cross: z crosses above sig → momentum turning up.
Bear Cross: z crosses below sig → momentum turning down.
Exits / Bias flips: zero-line crosses (below 0 → exit long bias; above 0 → exit short bias).
Overbought/Oversold: z > +thrOB or z < thrOS. With dynamics on, the bands widen/narrow with recent noise; with dynamics off, static guides at ±2 / ±2.5 are shown.
Core Inputs
Source: Price series to analyze.
Fast Radius / Fast Sigma (defaults 6 / 2.5): Shorter radius/smaller σ = snappier, higher-freq.
Slow Radius / Slow Sigma (defaults 14 / 5.0): Larger radius/σ = smoother, lower-freq baseline.
Normalization
Robust Z-Score Window (default 200): Lookback for median/MAD proxy (stability vs responsiveness).
Small ε for MAD: Floor to avoid division by zero.
Signal & Thresholds
Dynamic Thresholds (MAD-based) (on by default): Adaptive OB/OS; toggle off to use fixed guides.
Visuals
Shade OB/OS Regions: Background highlights when z is beyond thresholds.
Show Zero Line: Midline reference.
(“Plot Cross Markers” input is present for future use.)
Rolling Performance Metrics TableRolling Performance Metrics Table
A clean, customizable table overlay that displays rolling performance metrics across multiple time periods. Perfect for quickly assessing price momentum and performance trends at a glance.
FEATURES:
- Displays performance across 5 time periods: 1 Week, 3 Month, 6 Month, 1 Year, and 2 Year
- Shows historical price at the start of each period
- Calculates both absolute price change and percentage change
- Color-coded results: Green for positive performance, Red for negative performance
- Fully transparent design with no background or borders - text floats cleanly over your chart
- Customizable table position (9 placement options)
DISPLAY COLUMNS:
1. Period - The lookback timeframe
2. Price - The historical price at the start of the period
3. Change (Value) - Absolute price change from the period start
4. Change (%) - Percentage return over the period
CUSTOMIZATION:
- Adjust the number of bars for each period (default: 1 Week = 5 bars, 3 Month = 63 bars, 6 Month = 126 bars, 1 Year = 252 bars, 2 Year = 504 bars)
- Choose from 9 table positions: Top, Middle, Bottom combined with Left, Center, Right
- Default position: Middle Left
USAGE:
Perfect for traders who want to quickly assess momentum across multiple timeframes. The transparent overlay design ensures minimal obstruction of chart analysis while providing critical performance data at a glance.
NOTE:
- The table only appears on the last bar of your chart
- Customize bar counts in settings to match your specific timeframe needs (e.g., daily vs hourly charts)
- "N/A" appears when historical data is insufficient for the selected period
BullishBuzz ORB – CALL/PUT with Chart Alerts (Final)⚙️ The Bullish BuzzBot System
1️⃣ Data Feeds (Input Layer)
BuzzBot connects to live market data through TradingView’s chart engine (or via API for more advanced builds).
It continuously pulls:
Price data (open, high, low, close per bar)
Volume
RSI, MACD, VWAP, EMA 9/21 values
Timestamps & bar intervals (1m, 5m, 15m)
That’s the raw fuel — the same data you’d use for charting.
2️⃣ Indicator Engine (Signal Layer)
This is where the logic lives — it calculates conditions in real time.
BuzzBot checks for patterns like:
EMA 9/21 Cross: detects momentum shift
VWAP Reclaim or Reject: confirms intraday bias
RSI < 50 or > 70: momentum confirmation
MACD Cross: trend continuation signal
Volume > 2x average: validates conviction






















