Ehlers Even Better Sinewave (EBSW)# EBSW: Ehlers Even Better Sinewave
## Overview and Purpose
The Ehlers Even Better Sinewave (EBSW) indicator, developed by John Ehlers, is an advanced cycle analysis tool. This implementation is based on a common interpretation that uses a cascade of filters: first, a High-Pass Filter (HPF) to detrend price data, followed by a Super Smoother Filter (SSF) to isolate the dominant cycle. The resulting filtered wave is then normalized using an Automatic Gain Control (AGC) mechanism, producing a bounded oscillator that fluctuates between approximately +1 and -1. It aims to provide a clear and responsive measure of market cycles.
## Core Concepts
* **Detrending (High-Pass Filter):** A 1-pole High-Pass Filter removes the longer-term trend component from the price data, allowing the indicator to focus on cyclical movements.
* **Cycle Smoothing (Super Smoother Filter):** Ehlers' Super Smoother Filter is applied to the detrended data to further refine the cycle component, offering effective smoothing with relatively low lag.
* **Wave Generation:** The output of the SSF is averaged over a short period (typically 3 bars) to create the primary "wave".
* **Automatic Gain Control (AGC):** The wave's amplitude is normalized by dividing it by the square root of its recent power (average of squared values). This keeps the oscillator bounded and responsive to changes in volatility.
* **Normalized Oscillator:** The final output is a single sinewave-like oscillator.
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
| ----------- | ------- | --------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| Source | close | Price data used for calculation. | Typically `close`, but `hlc3` or `ohlc4` can be used for a more comprehensive price representation. |
| HP Length | 40 | Lookback period for the 1-pole High-Pass Filter used for detrending. | Shorter periods make the filter more responsive to shorter cycles; longer periods focus on longer-term cycles. Adjust based on observed cycle characteristics. |
| SSF Length | 10 | Lookback period for the Super Smoother Filter used for smoothing the detrended cycle component. | Shorter periods result in a more responsive (but potentially noisier) wave; longer periods provide more smoothing. |
**Pro Tip:** The `HP Length` and `SSF Length` parameters should be tuned based on the typical cycle lengths observed in the market and the desired responsiveness of the indicator.
## Calculation and Mathematical Foundation
**Simplified explanation:**
1. Remove the trend from the price data using a 1-pole High-Pass Filter.
2. Smooth the detrended data using a Super Smoother Filter to get a clean cycle component.
3. Average the output of the Super Smoother Filter over the last 3 bars to create a "Wave".
4. Calculate the average "Power" of the Super Smoother Filter output over the last 3 bars.
5. Normalize the "Wave" by dividing it by the square root of the "Power" to get the final EBSW value.
**Technical formula (conceptual):**
1. **High-Pass Filter (HPF - 1-pole):**
`angle_hp = 2 * PI / hpLength`
`alpha1_hp = (1 - sin(angle_hp)) / cos(angle_hp)`
`HP = (0.5 * (1 + alpha1_hp) * (src - src )) + alpha1_hp * HP `
2. **Super Smoother Filter (SSF):**
`angle_ssf = sqrt(2) * PI / ssfLength`
`alpha2_ssf = exp(-angle_ssf)`
`beta_ssf = 2 * alpha2_ssf * cos(angle_ssf)`
`c2 = beta_ssf`
`c3 = -alpha2_ssf^2`
`c1 = 1 - c2 - c3`
`Filt = c1 * (HP + HP )/2 + c2*Filt + c3*Filt `
3. **Wave Generation:**
`WaveVal = (Filt + Filt + Filt ) / 3`
4. **Power & Automatic Gain Control (AGC):**
`Pwr = (Filt^2 + Filt ^2 + Filt ^2) / 3`
`EBSW_SineWave = WaveVal / sqrt(Pwr)` (with check for Pwr == 0)
> 🔍 **Technical Note:** The combination of HPF and SSF creates a form of band-pass filter. The AGC mechanism ensures the output remains scaled, typically between -1 and +1, making it behave like a normalized oscillator.
## Interpretation Details
* **Cycle Identification:** The EBSW wave shows the current phase and strength of the dominant market cycle as filtered by the indicator. Peaks suggest cycle tops, and troughs suggest cycle bottoms.
* **Trend Reversals/Momentum Shifts:** When the EBSW wave crosses the zero line, it can indicate a potential shift in the short-term cyclical momentum.
* Crossing up through zero: Potential start of a bullish cyclical phase.
* Crossing down through zero: Potential start of a bearish cyclical phase.
* **Overbought/Oversold Levels:** While normalized, traders often establish subjective or statistically derived overbought/oversold levels (e.g., +0.85 and -0.85, or other values like +0.7, +0.9).
* Reaching above the overbought level and turning down may signal a potential cyclical peak.
* Falling below the oversold level and turning up may signal a potential cyclical trough.
## Limitations and Considerations
* **Parameter Sensitivity:** The indicator's performance depends on tuning `hpLength` and `ssfLength` to prevailing market conditions.
* **Non-Stationary Markets:** In strongly trending markets with weak cyclical components, or in very choppy non-cyclical conditions, the EBSW may produce less reliable signals.
* **Lag:** All filtering introduces some lag. The Super Smoother Filter is designed to minimize this for its degree of smoothing, but lag is still present.
* **Whipsaws:** Rapid oscillations around the zero line can occur in volatile or directionless markets.
* **Requires Confirmation:** Signals from EBSW are often best confirmed with other forms of technical analysis (e.g., price action, volume, other non-correlated indicators).
## References
* Ehlers, J. F. (2002). *Rocket Science for Traders: Digital Signal Processing Applications*. John Wiley & Sons.
* Ehlers, J. F. (2013). *Cycle Analytics for Traders: Advanced Technical Trading Concepts*. John Wiley & Sons.
Indicators and strategies
Bollinger Band Spread (Dunk)Bollinger Band Width measures the distance between the upper and lower Bollinger Bands. It reflects market volatility—wider bands mean higher volatility, narrower bands mean lower volatility.
When the width contracts to low levels, it can signal price consolidation and potential breakouts. When the width expands, it indicates active markets or strong trends.
Traders use it to spot volatility squeezes, confirm breakouts, and compare relative volatility across assets or timeframes.
Dow Jones Trading System with PivotsThis TradingView indicator, tailored for the 30-minute Dow Jones (^DJI) chart, supports DIA options trading with a trend-following approach. It features a 30-period SMA (blue) and a 60-period SMA (red), with an optional 90-period SMA (orange) drawn from rauItrades' Dow SMA outfit. A bullish crossover (30 SMA > 60 SMA) displays a green "BUY" triangle below the bar for potential DIA longs, while a bearish crossunder (30 SMA < 60 SMA) shows a red "SELL" triangle above for shorts or exits. The background turns green (bullish) or red (bearish) to indicate trend bias. Pivot points highlight recent highs (orange circles) and lows (purple circles) for support/resistance, using a 5-bar lookback. Alerts notify for crossovers.
Ehlers Ultrasmooth Filter (USF)# USF: Ultrasmooth Filter
## Overview and Purpose
The Ultrasmooth Filter (USF) is an advanced signal processing tool that represents the pinnacle of noise reduction technology for financial time series. Developed by John Ehlers, this filter implements a complex algorithm that provides exceptional smoothing capabilities while minimizing the lag typically associated with heavy filtering. USF builds upon the Super Smooth Filter (SSF) with enhanced noise suppression characteristics, making it particularly valuable for identifying clear trends in extremely noisy market conditions where even traditional smoothing techniques struggle to produce clean signals.
## Core Concepts
* **Maximum noise suppression:** Provides the highest level of noise reduction among Ehlers' filter designs
* **Optimized coefficient structure:** Uses carefully designed mathematical relationships to achieve superior filtering performance
* **Market application:** Particularly effective for long-term trend identification and minimizing false signals in highly volatile market conditions
The core innovation of USF is its second-order filter structure with optimized coefficients that create an exceptionally smooth frequency response. By careful mathematical design, USF achieves near-optimal noise suppression characteristics while minimizing the lag and waveform distortion that typically accompany such heavy filtering. This makes it especially valuable for identifying major market trends amid significant short-term volatility.
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Length | 20 | Controls the cutoff period | Increase for smoother signals, decrease for more responsiveness |
| Source | close | Price data used for calculation | Consider using hlc3 for a more balanced price representation |
**Pro Tip:** USF is ideal for defining major market trends - try using it with a length of 40-60 on daily charts to identify dominant market direction and ignoring shorter-term noise completely.
## Calculation and Mathematical Foundation
**Simplified explanation:**
The Ultrasmooth Filter creates an extremely clean price representation by combining current and past price data with previous filter outputs using precisely calculated mathematical relationships. This creates a highly effective "averaging" process that removes virtually all market noise while still maintaining the essential trend information.
**Technical formula:**
USF = (1-c1)X + (2c1-c2)X₁ - (c1+c3)X₂ + c2×USF₁ + c3×USF₂
Where coefficients are calculated as:
- a1 = exp(-1.414π/length)
- b1 = 2a1 × cos(1.414 × 180/length)
- c1 = (1 + c2 - c3)/4
- c2 = b1
- c3 = -a1²
> 🔍 **Technical Note:** The filter combines both feed-forward (X terms) and feedback (USF terms) components in a second-order structure, creating a response with exceptional roll-off characteristics and minimal passband ripple.
## Interpretation Details
The Ultrasmooth Filter can be used in various trading strategies:
* **Major trend identification:** The direction of USF indicates the dominant market trend with minimal noise interference
* **Signal generation:** Crossovers between price and USF generate high-reliability trade signals with minimal false positives
* **Support/resistance levels:** USF can act as strong dynamic support during uptrends and resistance during downtrends
* **Market regime identification:** The slope of USF helps identify whether markets are in trending or consolidation phases
* **Multiple timeframe analysis:** Using USF across different chart timeframes creates a cohesive picture of nested trend structures
## Limitations and Considerations
* **Significant lag:** The extreme smoothing comes with increased lag compared to lighter filters
* **Initialization period:** Requires more bars than simpler filters to stabilize at the start of data
* **Less suitable for short-term trading:** Generally too slow-responding for short-term strategies
* **Parameter sensitivity:** Performance depends on appropriate length selection for the timeframe
* **Complementary tools:** Best used alongside faster-responding indicators for timing signals
## References
* Ehlers, J.F. "Cycle Analytics for Traders," Wiley, 2013
* Ehlers, J.F. "Rocket Science for Traders," Wiley, 2001
Ehlers Autocorrelation Periodogram (EACP)# EACP: Ehlers Autocorrelation Periodogram
## Overview and Purpose
Developed by John F. Ehlers (Technical Analysis of Stocks & Commodities, Sep 2016), the Ehlers Autocorrelation Periodogram (EACP) estimates the dominant market cycle by projecting normalized autocorrelation coefficients onto Fourier basis functions. The indicator blends a roofing filter (high-pass + Super Smoother) with a compact periodogram, yielding low-latency dominant cycle detection suitable for adaptive trading systems. Compared with Hilbert-based methods, the autocorrelation approach resists aliasing and maintains stability in noisy price data.
EACP answers a central question in cycle analysis: “What period currently dominates the market?” It prioritizes spectral power concentration, enabling downstream tools (adaptive moving averages, oscillators) to adjust responsively without the lag present in sliding-window techniques.
## Core Concepts
* **Roofing Filter:** High-pass plus Super Smoother combination removes low-frequency drift while limiting aliasing.
* **Pearson Autocorrelation:** Computes normalized lag correlation to remove amplitude bias.
* **Fourier Projection:** Sums cosine and sine terms of autocorrelation to approximate spectral energy.
* **Gain Normalization:** Automatic gain control prevents stale peaks from dominating power estimates.
* **Warmup Compensation:** Exponential correction guarantees valid output from the very first bar.
## Implementation Notes
**This is not a strict implementation of the TASC September 2016 specification.** It is a more advanced evolution combining the core 2016 concept with techniques Ehlers introduced later. The fundamental Wiener-Khinchin theorem (power spectral density = Fourier transform of autocorrelation) is correctly implemented, but key implementation details differ:
### Differences from Original 2016 TASC Article
1. **Dominant Cycle Calculation:**
- **2016 TASC:** Uses peak-finding to identify the period with maximum power
- **This Implementation:** Uses Center of Gravity (COG) weighted average over bins where power ≥ 0.5
- **Rationale:** COG provides smoother transitions and reduces susceptibility to noise spikes
2. **Roofing Filter:**
- **2016 TASC:** Simple first-order high-pass filter
- **This Implementation:** Canonical 2-pole high-pass with √2 factor followed by Super Smoother bandpass
- **Formula:** `hp := (1-α/2)²·(p-2p +p ) + 2(1-α)·hp - (1-α)²·hp `
- **Rationale:** Evolved filtering provides better attenuation and phase characteristics
3. **Normalized Power Reporting:**
- **2016 TASC:** Reports peak power across all periods
- **This Implementation:** Reports power specifically at the dominant period
- **Rationale:** Provides more meaningful correlation between dominant cycle strength and normalized power
4. **Automatic Gain Control (AGC):**
- Uses decay factor `K = 10^(-0.15/diff)` where `diff = maxPeriod - minPeriod`
- Ensures K < 1 for proper exponential decay of historical peaks
- Prevents stale peaks from dominating current power estimates
### Performance Characteristics
- **Complexity:** O(N²) where N = (maxPeriod - minPeriod)
- **Implementation:** Uses `var` arrays with native PineScript historical operator ` `
- **Warmup:** Exponential compensation (§2 pattern) ensures valid output from bar 1
### Related Implementations
This refined approach aligns with:
- TradingView TASC 2025.02 implementation by blackcat1402
- Modern Ehlers cycle analysis techniques post-2016
- Evolved filtering methods from *Cycle Analytics for Traders*
The code is mathematically sound and production-ready, representing a refined version of the autocorrelation periodogram concept rather than a literal translation of the 2016 article.
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Min Period | 8 | Lower bound of candidate cycles | Increase to ignore microstructure noise; decrease for scalping. |
| Max Period | 48 | Upper bound of candidate cycles | Increase for swing analysis; decrease for intraday focus. |
| Autocorrelation Length | 3 | Averaging window for Pearson correlation | Set to 0 to match lag, or enlarge for smoother spectra. |
| Enhance Resolution | true | Cubic emphasis to highlight peaks | Disable when a flatter spectrum is desired for diagnostics. |
**Pro Tip:** Keep `(maxPeriod - minPeriod)` ≤ 64 to control $O(n^2)$ inner loops and maintain responsiveness on lower timeframes.
## Calculation and Mathematical Foundation
**Explanation:**
1. Apply roofing filter to `source` using coefficients $\alpha_1$, $a_1$, $b_1$, $c_1$, $c_2$, $c_3$.
2. For each lag $L$ compute Pearson correlation $r_L$ over window $M$ (default $L$).
3. For each period $p$, project onto Fourier basis:
$C_p=\sum_{n=2}^{N} r_n \cos\left(\frac{2\pi n}{p}\right)$ and $S_p=\sum_{n=2}^{N} r_n \sin\left(\frac{2\pi n}{p}\right)$.
4. Power $P_p=C_p^2+S_p^2$, smoothed then normalized via adaptive peak tracking.
5. Dominant cycle $D=\frac{\sum p\,\tilde P_p}{\sum \tilde P_p}$ over bins where $\tilde P_p≥0.5$, warmup-compensated.
**Technical formula:**
```
Step 1: hp_t = ((1-α₁)/2)(src_t - src_{t-1}) + α₁ hp_{t-1}
Step 2: filt_t = c₁(hp_t + hp_{t-1})/2 + c₂ filt_{t-1} + c₃ filt_{t-2}
Step 3: r_L = (M Σxy - Σx Σy) / √
Step 4: P_p = (Σ_{n=2}^{N} r_n cos(2πn/p))² + (Σ_{n=2}^{N} r_n sin(2πn/p))²
Step 5: D = Σ_{p∈Ω} p · ĤP_p / Σ_{p∈Ω} ĤP_p with warmup compensation
```
> 🔍 **Technical Note:** Warmup uses $c = 1 / (1 - (1 - \alpha)^{k})$ to scale early-cycle estimates, preventing low values during initial bars.
## Interpretation Details
- **Primary Dominant Cycle:**
- High $D$ (e.g., > 30) implies slow regime; adaptive MAs should lengthen.
- Low $D$ (e.g., < 15) signals rapid oscillations; shorten lookback windows.
- **Normalized Power:**
- Values > 0.8 indicate strong cycle confidence; consider cyclical strategies.
- Values < 0.3 warn of flat spectra; favor trend or volatility approaches.
- **Regime Shifts:**
- Rapid drop in $D$ alongside rising power often precedes volatility expansion.
- Divergence between $D$ and price swings may highlight upcoming breakouts.
## Limitations and Considerations
- **Spectral Leakage:** Limited lag range can smear peaks during abrupt volatility shifts.
- **O(n²) Segment:** Although constrained (≤ 60 loops), wide period spans increase computation.
- **Stationarity Assumption:** Autocorrelation presumes quasi-stationary cycles; regime changes reduce accuracy.
- **Latency in Noise:** Even with roofing, extremely noisy assets may require higher `avgLength`.
- **Downtrend Bias:** Negative trends may clip high-pass output; ensure preprocessing retains signal.
## References
* Ehlers, J. F. (2016). “Past Market Cycles.” *Technical Analysis of Stocks & Commodities*, 34(9), 52-55.
* Thinkorswim Learning Center. “Ehlers Autocorrelation Periodogram.”
* Fab MacCallini. “autocorrPeriodogram.R.” GitHub repository.
* QuantStrat TradeR Blog. “Autocorrelation Periodogram for Adaptive Lookbacks.”
* TradingView Script by blackcat1402. “Ehlers Autocorrelation Periodogram (Updated).”
F & W SMC Alerthis script is a custom TradingView indicator designed to combine elements of a trend‑following VWAP approach (inspired by the “Fabio” strategy) with a smart‑money‑concepts framework (inspired by Waqar Asim). Here’s what it does:
* **Directional bias:** It calculates a 15‑minute VWAP and compares the current 15‑minute close to it. When price is above the 15‑minute VWAP, the script assumes a long bias; when below, a short bias. This reflects the trend‑following aspect of the Fabio strategy.
* **Liquidity sweeps:** Using recent pivot highs and lows on the current timeframe, it identifies when price takes out a recent high (for potential longs) or low (for potential shorts). This represents a “liquidity sweep” — a fake breakout that collects stops and signals a possible reversal or continuation.
* **Break of structure (BOS):** After a sweep, the script confirms that price is breaking away from the swept level (i.e., higher than recent highs for longs or lower than recent lows for shorts). This BOS confirmation helps avoid false signals.
* **Entry filters:** For a long setup, the bias must be long, there must be a liquidity sweep followed by a BOS, and price must reclaim the current‑timeframe VWAP. For a short setup, the opposite conditions apply (short bias, sweep + BOS to the downside, and price rejecting the VWAP).
* **Alerts and plot:** It provides two alert conditions (“Fabio‑Waqar Long Setup” and “Fabio‑Waqar Short Setup”) that you can attach to notifications. It also plots the intraday VWAP on your chart for visual reference.
In short, this script watches for a confluence of trend direction, liquidity sweeps, structural shifts, and VWAP reclaim/rejection, and then notifies you when those conditions align. You can use it as an alerting tool to identify high‑probability setups based on these combined strategies.
Fabio + Waqar SMC AlertThis script is a custom TradingView indicator designed to combine elements of a trend‑following VWAP approach (inspired by the “Fabio” strategy) with a smart‑money‑concepts framework (inspired by Waqar Asim). Here’s what it does:
* **Directional bias:** It calculates a 15‑minute VWAP and compares the current 15‑minute close to it. When price is above the 15‑minute VWAP, the script assumes a long bias; when below, a short bias. This reflects the trend‑following aspect of the Fabio strategy.
* **Liquidity sweeps:** Using recent pivot highs and lows on the current timeframe, it identifies when price takes out a recent high (for potential longs) or low (for potential shorts). This represents a “liquidity sweep” — a fake breakout that collects stops and signals a possible reversal or continuation.
* **Break of structure (BOS):** After a sweep, the script confirms that price is breaking away from the swept level (i.e., higher than recent highs for longs or lower than recent lows for shorts). This BOS confirmation helps avoid false signals.
* **Entry filters:** For a long setup, the bias must be long, there must be a liquidity sweep followed by a BOS, and price must reclaim the current‑timeframe VWAP. For a short setup, the opposite conditions apply (short bias, sweep + BOS to the downside, and price rejecting the VWAP).
* **Alerts and plot:** It provides two alert conditions (“Fabio‑Waqar Long Setup” and “Fabio‑Waqar Short Setup”) that you can attach to notifications. It also plots the intraday VWAP on your chart for visual reference.
In short, this script watches for a confluence of trend direction, liquidity sweeps, structural shifts, and VWAP reclaim/rejection, and then notifies you when those conditions align. You can use it as an alerting tool to identify high‑probability setups based on these combined strategies.
Futures Gann MonthBuilds a a continuous chart of the same month for a futures contract (e.g. ZSH2026).
This means such a chart consists of March '22, March '23, March '24, March '25, March '26...
The script goes back 20 years at most (depending on the current ticker selected in TradingView).
Up vs Down Volume Compared to PriceHi team,
I’ve put together a simple TradingView indicator that breaks down the last N candles into up-moves and down-moves, showing how much volume supported each side. It helps you quickly see whether the market is rallying on strong participation or just drifting higher on weak volume.
The tool tracks total up-volume versus down-volume, compares their ratios, and flags when pullbacks are happening with noticeably lower volume than the prior push up — a setup that often signals a healthy continuation rather than a reversal.
It also shows key metrics like total volume, price change, and up/down ratios directly on the chart for quick assessment. You’ll instantly know if you’re looking at a light-volume pullback or a heavy-volume sell-off.
Let’s test it out across a few symbols and discuss any tweaks we’d like — maybe layering an EMA or VWAP filter for cleaner trend confirmation.
Supertrend with Coppock Curve and Dynamic Time WindowOverview
This indicator combines the **Supertrend** trend-following system with the **Coppock Curve** momentum oscillator to generate high-probability buy and sell signals. An additional **dynamic time window filter** ensures trades only occur during your specified trading hours, making it ideal for intraday traders who want to avoid low-liquidity periods.
How It Works
**Signal Generation:**
- **BUY Signal** (Green label below bar): Triggered when the Coppock Curve crosses above zero, the Supertrend confirms an uptrend, and the current time is within your specified trading window
- **SELL Signal** (Purple label above bar): Triggered when the Coppock Curve crosses below zero, the Supertrend confirms a downtrend, and the current time is within your specified trading window
**Triple Confirmation System:**
1. **Coppock Curve** - Identifies momentum shifts using rate-of-change calculations
2. **Supertrend** - Confirms the prevailing trend direction to filter false signals
3. **Time Window** - Ensures trades only occur during high-liquidity hours
Input Parameters
**Supertrend Settings:**
- **ATR Length** (Default: 19) - Period for calculating the Average True Range
- **Factor** (Default: 3.0) - Multiplier for ATR to determine Supertrend sensitivity
**Time Window Settings (Tehran Time UTC+3:30):**
- **Start Hour/Minute** (Default: 10:30) - Beginning of active trading window
- **End Hour/Minute** (Default: 22:30) - End of active trading window
Best Practices
- Works best on **trending markets** due to the Supertrend filter
- Recommended timeframes: **15min, 30min, 1H, 4H**
- Lower the Factor value (2.0-2.5) for more signals in volatile markets
- Increase the Factor value (3.5-4.0) for fewer, higher-quality signals in ranging markets
- Adjust the time window to match your market's peak liquidity hours
Risk Disclaimer
This indicator is for educational purposes only. Always use proper risk management, position sizing, and combine with your own analysis before making trading decisions.
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
ADX and DI deltaJust a small adjustment to a well known indicator, the ADX with +DI and -DI.
I've always been annoyed of how cluttered this indicator is, specially do to the increasing gap between +DI and -DI, so I changed it up a bit.
ADX line has not been adjusted
+DI and -DI have now merged into deltaDI
deltaDI changes color depending on which value is higher (+DI > -DI = green line, else red line)
Plots a dashed 0 line (not editable)
Plots a two dotted lines at value 20 and 25 (editable)
Plots a label above/below price on the chart if the trend is exhausted and might end. (can be disabled)
Now you only have the ADX line together with a delta line.
The delta line is the gap between +DI and -DI and will change color depending on which one is highest and controlling the trend.
+DI = green line
-DI = red line
I've also added both a 20 and 25 horizontal dotted line.
Normally ADX should be 25 or higher to start a trend, but I do know a lot of people like to be greedy and jump in early in the trend build-up.
A dashed 0 line has been added, just because I felt like it. If either the ADX or delta ever cross below it without you editing the script yourself, just delete the script as it clearly doesn't do its job.
A red label_down will be plotted above the price when the ADX starts curling down and +DI > -DI. This indicates at best a breather for a bullish up trend or a possible reversal.
A red label_down will be plotted above the price if the ADX is above 25 and starts curling down while +DI > -DI. This indicates at best a breather for a bullish up trend or a possible reversal.
A green label_up will be plotted below the price if the ADX is above 25 and starts curling down while -DI > +DI. This indicates at best a breather for a bearish down trend or a possible reversal.
Enjoy my take on the indicator.
Loss Alarm (multi-TF)Loss Alarm (multi-TF)
This script triggers an alert once the price candel body stays fully under a chosen line for a predefined period of time.
Select your own ticker, timeframe, and price level.
The alert is triggered only once per session.
A line is plotted on the chart with a label showing the selected timeframe, so you know which alert is active.
⚠️ Note: you must manually create a separate TradingView alert using the condition provided by the script.
Gain Alarm (multi-TF )369
Gain Alarm (multi-TF)
This script triggers an alert once the price candel body stays fully above a chosen line for a predefined period of time.
Select your own ticker, timeframe, and price level.
The alert is triggered only once per session.
A line is plotted on the chart with a label showing the selected timeframe, so you know which alert is active.
⚠️ Note: you must manually create a separate TradingView alert using the condition provided by the script.
CCI [Hash Adaptive]Adaptive CCI Pro: Professional Technical Analysis Indicator
The Commodity Channel Index is a momentum oscillator developed by Donald Lambert in 1980. CCI measures the relationship between an asset's price and its statistical average, identifying cyclical turns and overbought/oversold conditions. The indicator oscillates around zero, with values above +100 indicating overbought conditions and values below -100 suggesting oversold conditions.
Standard CCI Formula: (Typical Price - Moving Average) / (0.015 × Mean Deviation)
This indicator transforms the traditional CCI into a sophisticated visual analysis tool through several key enhancements:
Implements dual exponential moving average smoothing to eliminate market noise
Preserves signal integrity while reducing false signals
Adaptive smoothing responds to market volatility conditions
Dynamic Color Visualization System
Continuous gradient transitions from red (bearish momentum) to green (bullish momentum)
Real-time color intensity reflects momentum strength
Eliminates discrete color jumps for fluid visual interpretation
Adaptive Intelligence Features
Dynamic overbought/oversold thresholds adapt to market conditions
Reduces false signals during high volatility periods
Maintains sensitivity during low volatility environments
Momentum Vector Analysis
Incorporates velocity calculations for early trend identification
Crossover detection with momentum confirmation
Advanced signal filtering reduces market noise
Extreme Level Analysis
Values above +100: Strong overbought conditions, potential reversal zones
Values below -100: Strong oversold conditions, potential buying opportunities
Zero-line crossovers: Momentum shift confirmation
Optimization Parameters
CCI Period (Default: 14)
Shorter periods (10-12): Increased sensitivity, more signals
Standard periods (14-20): Balanced responsiveness and reliability
Longer periods (21-30): Reduced noise, stronger signal confirmation
Smoothing Factor (Default: 5)
Lower values (1-3): Maximum responsiveness, suitable for scalping
Medium values (4-6): Balanced approach for swing trading
Higher values (7-10): Institutional-grade smoothness for position trading
Signal Sensitivity (Default: 6)
Conservative (7-10): High-probability signals, reduced frequency
Balanced (5-6): Optimal risk-reward ratio
Aggressive (1-4): Maximum signal generation, requires additional confirmation
Strategic Implementation
Oversold reversals in red zones with momentum confirmation
Zero-line breaks with sustained color transitions
Extreme readings followed by momentum divergence
Risk Management
Use extreme levels (+100/-100) for position sizing decisions
Monitor color intensity for momentum strength assessment
Combine with price action analysis for comprehensive market view
Market Context Application
Trending markets: Focus on momentum direction and extreme readings
Range-bound markets: Utilize overbought/oversold levels for mean reversion
Volatile markets: Increase smoothing parameters and signal sensitivity
Professional Advantages
Instantaneous momentum assessment through color visualization
Reduced cognitive load compared to traditional oscillators
Professional presentation suitable for client reporting
Adaptive Technology
Self-adjusting parameters reduce manual optimization requirements
Consistent performance across varying market conditions
Advanced mathematics eliminate common CCI limitations
The Adaptive CCI Pro represents the evolution of momentum analysis, combining Lambert's foundational CCI concept with modern computational techniques to deliver institutional-grade market intelligence through an intuitive visual interface.
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
ATR Money Line Bands V2The "ATR Money Line Bands V2" is a clever TradingView overlay designed for trend identification with volatility-aware bands, evolving from basic ATR envelopes.
Reasoning Behind Construction: The core idea is to blend a smoothed trend line with dynamic volatility bands for reliable signals in varying markets. The "Money Line" uses linear regression (ta.linreg) on closes over a length (default 16) instead of a moving average, as it fits data via least-squares for a cleaner, forward-projected trend without lag artifacts. ATR (default 12-period) powers the bands because it measures true range volatility better than std dev in gappy assets like crypto/stocks—bands offset from the Money Line by ATR * multiplier (default 1.5). A dynamic multiplier (boosts by ~33% on spikes > prior ATR * 1.3) prevents tight bands from false breakouts during surges. Trend detection checks slope against an ATR-scaled tolerance (default 0.15) to ignore noise, labeling bull/bear/neutral—avoiding whipsaws in flats.
Properties: It's an overlay with a colored Money Line (green bull, red bear, yellow neutral) and invisible bands (toggle to show gray lines) filled semi-transparently matching trend for visual pop. Dynamic adaptation makes bands widen/contract intelligently. An info table (positionable, e.g., top_right) displays real-time values: Money Line, bands, ATR, trend—great for quick scans. Limits history (2000 bars) and labels (500) for efficiency.
Tips for Usage: Apply to any timeframe/asset; defaults suit medium-term (e.g., daily stocks). Watch color flips: green for longs (enter on pullbacks to lower band), red for shorts (vice versa), yellow to sit out. Use bands as S/R—breakouts signal momentum, squeezes impending vol. Tweak length for sensitivity (shorter for intraday), multiplier for width (higher for trends), tolerance for fewer neutrals. Pair with volume/RSI for confirmation; backtest to optimize. In choppy markets, disable dynamic mult to avoid over-expansion. Overall, it's adaptive and visual—helps trend-follow without overcomplicating.
QQQ overlay over NQ/NDXThis enhanced version of the QQQ overlay script builds on the original by © PtGambler, adding smoothing via stepped ratios updated on candle close to eliminate oscillation, optimizing performance by reusing lines/labels, restricting visibility to relevant symbols (NDX, NQ1!, NAS100USD), and improving visuals with rounded levels, adjustable level counts (default 5 total), extended lines, and label styles matching "Key Levels" indicator for better readability (gray text, transparent background). Removed unnecessary table and floating labels for a cleaner chart. Thanks to © PtGambler for the foundational work!
ATRThis script displays the Average True Range (ATR) value and the ATR as a percentage of the current closing price directly on the main chart as a clean table, with no lines or plots. It allows users to easily monitor both absolute volatility and its relative magnitude, making comparisons across different assets intuitive. The display position is customizable, offering flexibility for personal chart layouts. Ideal for traders seeking quick volatility insights, risk management guidance, or portfolio-wide comparisons.
Todays Session Open LN,NYWhen are the Asian, London and New York open for each session simple stuff trading view made me right more stuff so i can publish this what to do c'est la vie
Quantum Portfolio vs S&P 500 (Base: May 2, 2021)This script compares the performance of a custom Quantum Portfolio — a weighted basket of quantum computing, semiconductor, and cybersecurity stocks — against the S&P 500 Index, with both series rebased to 100 on May 2 2021.
It provides a clear, normalized view of cumulative returns, allowing you to visualize portfolio outperformance or underperformance relative to the broader market benchmark.






















