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
Göstergeler ve stratejiler
Symbol GuardSymbol Guard (configurable, v6) — a tiny “chart bouncer” to prevent accidental symbol swaps. Two modes only: exact full ticker (tickerid) or base currency.
Usage: add the indicator, choose Compare by, then set Expected ticker (tickerid) or Expected base currency. Leaving the selected field empty means “no restriction.” Simple, focused, and just bossy enough to save your setup.
RSI MT5-Style RSI Zones (20/30/70/80) with Signals & Alerts
Description (English first)
What it does
This script reproduces an MT5-style RSI with four-level zones (20/30/70/80) to better distinguish early/late overbought-oversold conditions. It highlights zone transitions, plots optional background shading, and triggers entry/exit alerts on precise crossings.
How it works (high-level logic)
Core is Wilder’s RSI on close (length = ).
Two oversold bands at 20 and 30; two overbought bands at 70 and 80.
Optional smoothing (), and MTF confirmation (optional) compares current RSI vs a higher timeframe RSI.
Signals:
Long setup: RSI crosses above 20 (early) or 30 (conservative); confirmation if higher-TF RSI is rising.
Take-profit / exit: RSI fails to hold above 70 or crosses below 70 after being >80.
Short setup: mirror logic with 70/80 → 30/20.
Inputs
RSI Length (<14>), Source (close)
Upper Bands (70, 80), Lower Bands (30, 20)
Smoothing ( on RSI, optional)
Higher Timeframe (), Confirm with HTF (on/off)
Background Zones (on/off), Alerts (on/off)
How to use
Choose your market/timeframe. For FX/indices, M5–H1 works well; for swing, H1–H4.
Pick your aggressiveness: use 20/80 for early reversals, 30/70 for conservative trend pullbacks.
With MTF confirmation on, prioritize entries aligned with the higher timeframe RSI slope.
Combine with structure (S/R) or a simple MA filter for trend direction.
Originality & usefulness
Unlike generic RSI scripts, this version provides dual-zone logic (20/30/70/80) with clear visual states, optional HTF confirmation, and ready-made alerts designed to match MetaTrader-like RSI workflows. It is not a direct clone of public open-source scripts; zone handling and alert conditions are purpose-built for timing pullbacks vs. extremes.
Best markets & limitations
Works on FX, gold (XAUUSD), and indices (US30/NAS100).
In strong trends, overbought/oversold can persist—use bands as context, not standalone signals.
Spikes around news can cause false triggers—consider widening bands or disabling trades near events.
Alerts included
RSI Crosses Above 20, RSI Crosses Above 30
RSI Crosses Below 70, RSI Crosses Below 80
MTF Confirmed Long/Short (optional)
User interface translations (if your UI is in Spanish)
RSI Length → Periodo RSI
Upper Bands → Bandas Superiores
Lower Bands → Bandas Inferiores
Smoothing → Suavizado
Higher Timeframe → Marco Temporal Superior
Confirm with HTF → Confirmar con MTS
Background Zones → Zonas de Fondo
Alerts → Alertas
Disclaimer
This tool is for educational purposes. Not financial advice.
Cyberbikes Adjustable 4x EMA + 4x SMAProbably the best EMA + SMA because you can choose the lenght of 8 different EMA and SMA.
By standard 9,21,80,200 EMA and SMA. Great for tradingview free users, many EMA and SMA in one indicator!
KANNADI MOHANRAJA SCALPINGEach 3minute time frame up direction movement background color goes to green
iFVG Strategie by Futures.RobbyiFVG Strategy Checklist by Futures.Robby
Updated: October 27, 2025
Description
This script is a manual checklist designed to help traders evaluate their setups based on the iFVG (Fair Value Gap) strategy. It serves solely as a visual aid and does not perform automatic analysis, signal generation, or trade execution.
How It Works
The script creates an interactive checklist directly on the chart. Traders manually select which criteria are met, and the script calculates a percentage score, displaying it with color coding:
Green (≥ 60%): Good fulfillment of criteria
Orange (40–59%): Partial fulfillment
Red (< 40%): Poor fulfillment
Checklist Criteria
The checklist is divided into two main sections:
1. Trade Criteria (8 Points)
Eight manually selectable criteria to assess setup quality:
Trade im Bias → Trade in Bias: Trade follows the higher timeframe trend (H1/H4/Daily).
BE Level → BE Level: Swing point between entry and target.
Sweep → Sweep: Price hits a key swing before reversing.
Displacement → Displacement: iFVG broken by strong candles.
Leg FVG geschlossen → Leg FVG Closed: No open m1 to m5 FVGs to target.
FVG Reaktion → FVG Reaction: Reaction at FVG during sweep (HTF).
FVG Größe → FVG Size: 6 to 10 points.
Anzahl Kerzen → Number of Candles: Maximum of 6 candles.
2. Goals (1 Point)
Six optional goal conditions, counted together as 1 point:
Equal H / L → Equal High/Low
Session H / L → Session High/Low
News H / L → News High/Low
HTF Swing Point → HTF Swing Point
HTF OB → HTF Order Block
HTF FVG → HTF FVG
Settings and Customization
The script’s settings are translated as follows:
Group: Trade Criteria
Trade im Bias → Trade in Bias
Tooltip: Trendrichtung folgt HTF (H1/H4/Täglich) – Trend follows HTF direction
BE Level → BE Level
Tooltip: Swingpunkt zwischen Einstieg und Ziel – Swing point between entry and target
Sweep → Sweep
Tooltip: Kurs erreicht markanten Swing – Price hits key swing before inverse
Displacement → Displacement
Tooltip: iFVG durch starke Kerzen gebrochen – iFVG broken by strong candles
Leg FVG geschlossen → Leg FVG Closed
Tooltip: Keine offenen m1 bis m5 FVGs bis Ziel – No open m1 to m5 FVGs to target
FVG Reaktion → FVG Reaction
Tooltip: Reaktion an FVG beim Sweep (HTF) – Reaction at FVG during sweep (HTF)
FVG Größe → FVG Size
Tooltip: 6 bis 10 Punkte – 6 to 10 points
Anzahl Kerzen → Number of Candles
Tooltip: Maximal 6 Kerzen – Maximum of 6 candles
Group: Goals
Equal H / L → Equal High/Low
Session H / L → Session High/Low
News H / L → News High/Low
HTF Swing Point → HTF Swing Point
HTF OB → HTF Order Block
HTF FVG → HTF FVG
ℹ️ Ziele zählen gemeinsam als 1 Punkt → ℹ️ Goals count together as 1 point
Window Position & Size
Fensterposition → Window Position
oben rechts → top right
oben links → top left
unten rechts → bottom right
unten links → bottom left
Tabellengröße → Table Size
normal → normal
small → small
tiny → tiny
Translation of Chart Table Contents
The table headers and entries on the chart are translated as follows:
Table Headers:
Trade Checkliste → Trade Checklist
Ziele → Goals
Status Symbols:
✅ → ✅ (Fulfilled)
❌ → ❌ (Not fulfilled)
Individual Criteria (Trade Criteria):
Trade im Bias → Trade in Bias
BE Level → BE Level
Sweep → Sweep
Displacement → Displacement
Leg FVG geschlossen → Leg FVG Closed
FVG Reaktion → FVG Reaction
FVG Größe → FVG Size
Anzahl Kerzen → Number of Candles
Individual Criteria (Goals):
Equal H / L → Equal High/Low
Session H / L → Session High/Low
News H / L → News High/Low
HTF Swing Point → HTF Swing Point
HTF OB → HTF Order Block
HTF FVG → HTF FVG
Note Line:
Ziele zählen gemeinsam als 1 Punkt → Goals count together as 1 point
Important Note
This tool is not an automated indicator, but a visual decision aid for traders who want to apply their strategy in a structured and conscious way.
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
Liquidity & SMT Detector//@version=5
indicator("Liquidity & SMT Detector", overlay=true, max_lines_count=500, max_labels_count=500)
// ============================================
// INPUT SETTINGS
// ============================================
// Group 1: Liquidity Detection
swing_length = input.int(15, "Swing Length", minval=5, maxval=50, group="Liquidity Detection")
swing_strength = input.int(3, "Swing Strength (bars clear)", minval=1, maxval=10, group="Liquidity Detection")
max_lines = input.int(10, "Max Lines Displayed", minval=3, maxval=50, group="Liquidity Detection")
line_color_high = input.color(color.red, "High Line Color", group="Liquidity Detection")
line_color_low = input.color(color.green, "Low Line Color", group="Liquidity Detection")
line_width = input.int(2, "Line Width", minval=1, maxval=5, group="Liquidity Detection")
show_labels = input.bool(true, "Show H/L Labels", group="Liquidity Detection")
// Group 2: Displacement Detection
enable_displacement = input.bool(true, "Enable Displacement Detection", group="Displacement")
displacement_min_points = input.float(10.0, "Min Points Move", minval=1.0, maxval=100.0, step=1.0, group="Displacement")
displacement_multiplier = input.float(3.0, "Size Multiplier", minval=2.0, maxval=10.0, step=0.5, group="Displacement")
displacement_period = input.int(30, "Average Period", minval=10, maxval=100, group="Displacement")
displacement_color_bull = input.color(color.new(color.aqua, 70), "Bullish Color", group="Displacement")
displacement_color_bear = input.color(color.new(color.orange, 70), "Bearish Color", group="Displacement")
show_displacement_label = input.bool(true, "Show Labels", group="Displacement")
// Group 3: SMT Detection
enable_smt = input.bool(true, "Enable SMT Detection", group="SMT Divergence")
nq_symbol = input.string("NQ1!", "Nasdaq Symbol", group="SMT Divergence")
es_symbol = input.string("ES1!", "S&P500 Symbol", group="SMT Divergence")
smt_lookback = input.int(20, "Lookback Period", minval=5, maxval=100, group="SMT Divergence")
smt_line_color = input.color(color.yellow, "SMT Line Color", group="SMT Divergence")
smt_text_color = input.color(color.yellow, "SMT Text Color", group="SMT Divergence")
// Group 4: Consolidation Zone
enable_consolidation = input.bool(true, "Enable Consolidation Zone", group="Consolidation")
consol_lookback = input.int(10, "Lookback Period", minval=5, maxval=50, group="Consolidation")
consol_range_percent = input.float(0.5, "Max Range %", minval=0.1, maxval=2.0, step=0.1, group="Consolidation")
consol_vol_threshold = input.float(0.7, "Volume Threshold", minval=0.3, maxval=1.0, step=0.1, group="Consolidation")
consol_color = input.color(color.new(color.red, 85), "Zone Color", group="Consolidation")
// ============================================
// ARRAYS FOR LINE/LABEL MANAGEMENT
// ============================================
var line high_lines = array.new_line()
var line low_lines = array.new_line()
var label high_labels = array.new_label()
var label low_labels = array.new_label()
var float high_levels = array.new_float()
var float low_levels = array.new_float()
var line smt_lines = array.new_line()
var label smt_labels = array.new_label()
var float smt_nq_levels = array.new_float()
var float smt_es_levels = array.new_float()
var bool smt_nq_lower = array.new_bool()
// ============================================
// FUNCTION: DETECT SWING HIGHS (STRONGER)
// ============================================
isSwingHigh(len, strength) =>
is_pivot = true
pivot_high = high
for i = 1 to strength
if high >= pivot_high or high >= pivot_high
is_pivot := false
break
if is_pivot
for i = strength + 1 to len
if high > pivot_high or high > pivot_high
is_pivot := false
break
is_pivot
// ============================================
// FUNCTION: DETECT SWING LOWS (STRONGER)
// ============================================
isSwingLow(len, strength) =>
is_pivot = true
pivot_low = low
for i = 1 to strength
if low <= pivot_low or low <= pivot_low
is_pivot := false
break
if is_pivot
for i = strength + 1 to len
if low < pivot_low or low < pivot_low
is_pivot := false
break
is_pivot
// ============================================
// SWING HIGH DETECTION & LINE DRAWING
// ============================================
if isSwingHigh(swing_length, swing_strength)
swing_high = high
new_line = line.new(bar_index - swing_length, swing_high, bar_index, swing_high, color=line_color_high, width=line_width, style=line.style_dashed)
array.push(high_lines, new_line)
array.push(high_levels, swing_high)
if show_labels
new_label = label.new(bar_index - swing_length, swing_high, "H", color=color.new(line_color_high, 80), textcolor=line_color_high, style=label.style_label_down, size=size.small)
array.push(high_labels, new_label)
if array.size(high_lines) > max_lines
line.delete(array.shift(high_lines))
array.shift(high_levels)
if show_labels and array.size(high_labels) > 0
label.delete(array.shift(high_labels))
// ============================================
// SWING LOW DETECTION & LINE DRAWING
// ============================================
if isSwingLow(swing_length, swing_strength)
swing_low = low
new_line = line.new(bar_index - swing_length, swing_low, bar_index, swing_low, color=line_color_low, width=line_width, style=line.style_dashed)
array.push(low_lines, new_line)
array.push(low_levels, swing_low)
if show_labels
new_label = label.new(bar_index - swing_length, swing_low, "L", color=color.new(line_color_low, 80), textcolor=line_color_low, style=label.style_label_up, size=size.small)
array.push(low_labels, new_label)
if array.size(low_lines) > max_lines
line.delete(array.shift(low_lines))
array.shift(low_levels)
if show_labels and array.size(low_labels) > 0
label.delete(array.shift(low_labels))
// ============================================
// UPDATE EXISTING LINES & CHECK FOR SWEEPS
// ============================================
if array.size(high_lines) > 0
for i = array.size(high_lines) - 1 to 0
current_line = array.get(high_lines, i)
current_level = array.get(high_levels, i)
if close > current_level
line.delete(current_line)
array.remove(high_lines, i)
array.remove(high_levels, i)
if show_labels and i < array.size(high_labels)
label.delete(array.get(high_labels, i))
array.remove(high_labels, i)
else
line.set_x2(current_line, bar_index)
if array.size(low_lines) > 0
for i = array.size(low_lines) - 1 to 0
current_line = array.get(low_lines, i)
current_level = array.get(low_levels, i)
if close < current_level
line.delete(current_line)
array.remove(low_lines, i)
array.remove(low_levels, i)
if show_labels and i < array.size(low_labels)
label.delete(array.get(low_labels, i))
array.remove(low_labels, i)
else
line.set_x2(current_line, bar_index)
// ============================================
// DISPLACEMENT CANDLE DETECTION
// ============================================
body_size = math.abs(close - open)
avg_body = ta.sma(math.abs(close - open), displacement_period)
candle_range = high - low
points_moved = body_size
is_min_points = points_moved >= displacement_min_points
is_strong_body = body_size > (avg_body * displacement_multiplier)
is_impulsive = body_size > (candle_range * 0.6)
is_displacement = enable_displacement and is_min_points and is_strong_body and is_impulsive
is_bullish = close > open
bgcolor(is_displacement ? (is_bullish ? displacement_color_bull : displacement_color_bear) : na)
if is_displacement and show_displacement_label
label.new(bar_index, is_bullish ? low : low, "D", color=color.new(is_bullish ? color.aqua : color.orange, 50), textcolor=is_bullish ? color.aqua : color.orange, style=label.style_label_down, size=size.small, yloc=yloc.belowbar)
// ============================================
// CONSOLIDATION ZONE DETECTION
// ============================================
consol_highest = ta.highest(high, consol_lookback)
consol_lowest = ta.lowest(low, consol_lookback)
consol_range = consol_highest - consol_lowest
consol_range_pct = (consol_range / close) * 100
consol_avg_volume = ta.sma(volume, consol_lookback)
consol_current_vol = ta.sma(volume, math.min(consol_lookback, bar_index + 1))
consol_low_volume = consol_current_vol < (consol_avg_volume * consol_vol_threshold)
consol_body_sizes = array.new_float()
for i = 0 to math.min(consol_lookback - 1, bar_index)
array.push(consol_body_sizes, math.abs(close - open ))
consol_avg_body = array.avg(consol_body_sizes)
consol_overall_avg = ta.sma(math.abs(close - open), 50)
consol_small_candles = consol_avg_body < (consol_overall_avg * 0.7)
consol_tight_range = consol_range_pct <= consol_range_percent
is_consolidation = enable_consolidation and consol_tight_range and consol_low_volume and consol_small_candles
bgcolor(is_consolidation ? consol_color : na, title="Consolidation Zone")
// ============================================
// SMT DIVERGENCE DETECTION
// ============================================
current_symbol = syminfo.ticker
comparison_symbol = str.contains(current_symbol, "NQ") ? es_symbol : nq_symbol
comparison_high = request.security(comparison_symbol, timeframe.period, high, lookahead=barmerge.lookahead_off)
comparison_low = request.security(comparison_symbol, timeframe.period, low, lookahead=barmerge.lookahead_off)
var float prev_current_low = na
var float prev_comparison_low = na
var int prev_swing_bar = na
current_is_swing_low = isSwingLow(swing_length, swing_strength)
comparison_is_swing_low = ta.lowestbars(comparison_low, swing_length * 2 + 1) == -swing_length
if enable_smt and current_is_swing_low
current_swing_low = low
comparison_swing_low = comparison_low
if not na(prev_current_low) and not na(prev_comparison_low)
current_lower = current_swing_low < prev_current_low
comparison_lower = comparison_swing_low < prev_comparison_low
is_smt = (current_lower and not comparison_lower) or (not current_lower and comparison_lower)
if is_smt
smt_line = line.new(prev_swing_bar, prev_current_low, bar_index - swing_length, current_swing_low, color=smt_line_color, width=2, style=line.style_solid)
mid_bar = math.round((prev_swing_bar + bar_index - swing_length) / 2)
mid_price = (prev_current_low + current_swing_low) / 2
smt_label = label.new(mid_bar, mid_price, "SMT", color=color.new(smt_line_color, 80), textcolor=smt_text_color, style=label.style_label_center, size=size.normal)
array.push(smt_lines, smt_line)
array.push(smt_labels, smt_label)
array.push(smt_nq_levels, str.contains(current_symbol, "NQ") ? current_swing_low : comparison_swing_low)
array.push(smt_es_levels, str.contains(current_symbol, "NQ") ? comparison_swing_low : current_swing_low)
array.push(smt_nq_lower, str.contains(current_symbol, "NQ") ? current_lower : comparison_lower)
prev_current_low := current_swing_low
prev_comparison_low := comparison_swing_low
prev_swing_bar := bar_index - swing_length
if enable_smt and array.size(smt_lines) > 0
for i = array.size(smt_lines) - 1 to 0
nq_level = array.get(smt_nq_levels, i)
es_level = array.get(smt_es_levels, i)
nq_was_lower = array.get(smt_nq_lower, i)
current_nq_low = str.contains(current_symbol, "NQ") ? low : comparison_low
current_es_low = str.contains(current_symbol, "NQ") ? comparison_low : low
es_now_lower = current_es_low < es_level
nq_now_lower = current_nq_low < nq_level
smt_invalidated = (nq_was_lower and es_now_lower) or (not nq_was_lower and nq_now_lower)
if smt_invalidated
line.delete(array.get(smt_lines, i))
label.delete(array.get(smt_labels, i))
array.remove(smt_lines, i)
array.remove(smt_labels, i)
array.remove(smt_nq_levels, i)
array.remove(smt_es_levels, i)
array.remove(smt_nq_lower, i)
// ============================================
// ALERTS
// ============================================
alertcondition(array.size(high_lines) < array.size(high_lines) , title="Liquidity Sweep High", message="High liquidity swept at {{close}}")
alertcondition(array.size(low_lines) < array.size(low_lines) , title="Liquidity Sweep Low", message="Low liquidity swept at {{close}}")
alertcondition(is_displacement, title="Displacement Candle", message="Displacement candle detected at {{close}}")
alertcondition(is_consolidation, title="Consolidation Zone", message="Market entering consolidation at {{close}}")
SMC Minimal Setup//@version=5
indicator("SMC Minimal Setup", overlay=true)
// === INPUTS ===
swingLeft = input.int(5, "Swing Left")
swingRight = input.int(5, "Swing Right")
structureLookback = input.int(20, "Structure Lookback")
// === MARKET STRUCTURE ===
var string structure = "neutral"
if high > ta.highest(high , structureLookback)
structure := "bullish"
if low < ta.lowest(low , structureLookback)
structure := "bearish"
// === SWING LEVELS ===
relevantHigh = ta.pivothigh(high, swingLeft, swingRight)
relevantLow = ta.pivotlow(low, swingLeft, swingRight)
// === LIQUIDITY SWEEPS ===
sweepHigh = not na(relevantHigh) and high > relevantHigh and close < relevantHigh
sweepLow = not na(relevantLow) and low < relevantLow and close > relevantLow
// === DISPLACEMENT CANDLES ===
bodySize = math.abs(close - open)
candleRange = high - low
avgRange = ta.sma(candleRange, 10)
displacementUp = close > open and bodySize > candleRange*0.6 and candleRange > avgRange
displacementDown = open > close and bodySize > candleRange*0.6 and candleRange > avgRange
// === SETUP ===
bullishSetup = sweepLow and displacementUp
bearishSetup = sweepHigh and displacementDown
plotshape(bullishSetup, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)
plotshape(bearishSetup, style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small)
// === FVG ===
bullishFVG = low > high
bearishFVG = high < low
if bullishFVG
box.new(left=bar_index-2, right=bar_index, top=low , bottom=high , bgcolor=color.new(color.green,85))
if bearishFVG
box.new(left=bar_index-2, right=bar_index, top=high , bottom=low , bgcolor=color.new(color.red,85))
// === BACKGROUND ===
bgcolor(structure=="bullish" ? color.new(color.green,80) : structure=="bearish" ? color.new(color.red,80) : na)
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
5x Relative Volume vs 30-Day AverageRelative Volume.
If today's volume is more than average of last 30 days volume by 5x.
Aquantprice: Institutional Structure Matrix
Why This is the Final Dashboard You’ll Ever Need:
Multi-Timeframe Trend Validators (1min to Monthly): 15 buy / 13 sell conditions using CPR pivots, weighted closes, and Camarilla logic — signals "BUY"/"SELL" only when threshold met.
Dip Buying & Sell Validators (Daily/Weekly/Monthly): 15-condition engine with ✔/✖ breakdown for long-term swing precision.
Two-Day Pivot Dashboard: Tracks CPR, POC, VAH/VAL, H3/L3 + exclusive two-day value shift ("Higher/Lower/Unchanged Value") — Pivot Boss on steroids.
Mind Over Markets Bias Engine: Detects "Initiative Buy/Sell," "Neutral," or "Rising Pivot, Weak Open" using rolling POC and neutral zone — pure institutional psychology.
Wick Reversal & Pattern Detection: Identifies Bull/Bear Wicks, Dojis, Outside Bars, and Extreme candles near pivot touches.
Risk-Reward & Target Projection: Auto-calculates RR ratios (min 2.0), next pivot targets, and entry zones (S1, R1, POC, etc.).
Quant Bias Summary: Weighted multi-TF aggregation delivers final verdict: Strong Buy → Buy → Neutral → Sell → Strong Sell.
Customizable Everything: Thresholds, timeframes, decimals, font size, table positions, novice mode — built for your style.
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
XAUUSD 5m — CET 13:00→01:00 Supertrend + RSI (1:2 RR) — $240KThis strategy is designed for XAUUSD (Gold) on the 5-minute chart, optimized for trading during the most active hours (13:00–01:00 CET).
It combines a Supertrend direction filter with RSI crossovers for precise entries, and applies a 1:2 risk–reward ratio for consistent risk management.
🧠 Logic Overview:
Buy Signal: RSI crosses above 55 while Supertrend is bullish
Sell Signal: RSI crosses below 45 while Supertrend is bearish
Trading Hours: 13:00 → 01:00 CET (corresponding to 07:00 → 19:00 New York time)
Risk Management: Fixed 1:2 RR (TP = 2× SL distance from Supertrend line)
Session Management: Automatically closes all trades after 01:00 CET
Order Size: $240,000 notional exposure per position
💡 Best used for:
Scalping or intraday trading on XAUUSD during high-volatility hours.
The setup works best when combined with strong price action or volume confirmation.
⚠️ Disclaimer:
This script is for educational and testing purposes only.
Past performance does not guarantee future results.
Always test on demo before using live funds.
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.
Pitchfork-Trading Friendsuses the pitchfork to give entry and exit zones, and gives a net overall summary for a beginner trader to enter into.
Risk Leverage ToolRisk Leverage Tool – Calculate Position Size and Required Leverage
This script automatically calculates the optimal position size and the leverage needed based on the amount of capital you are willing to risk on a trade. It is designed for traders who want precise control over their risk management.
The script determines the distance between the entry and stop-loss price, calculates the maximum position size that fits within the defined risk, and derives the notional value of the trade. Based on the available margin, it then calculates the required leverage. It also displays the percentage of margin at risk if the stop-loss is hit.
All results are displayed in a table in the top-right corner of the chart. Additionally, a label appears at the entry price level showing the same data.
To use the tool, simply input your planned entry price, stop-loss price, the maximum risk amount in dollars, and the available margin in the settings menu. The script will update all values automatically in real time.
This tool works with any market where capital risk is expressed in absolute terms (such as USD), including futures, CFDs, and leveraged spot positions. For inverse contracts or percentage-based stops, manual adjustment is required.
FVG_Liquidity_SignalFVGs: classic 3-bar gaps (bullish when low > high , bearish when high < low ). Zones are drawn and auto-pruned.
Liquidity sweep: price takes out the last swing low/high (pivot) and then reclaims it on the close.
Signals:
BUY when we get a bull sweep and the bar taps a recent bull FVG and closes back above its upper edge.
SELL is the mirror image.
SL/TP guides: SL at swept swing; TP = RR × risk (visual only).
Triple EMA (5, 8, 13) + Confirmed Alerts with SoundThis indicator uses three Exponential Moving Averages (EMA 5, 8, and 13) to generate buy and sell signals when the EMAs are properly aligned and not touching. Signals are confirmed on candle close and can trigger customizable sound alerts directly from the TradingView alert panel.
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.
Trendline Breakout Strategy Strategy should place entries & exits so that it can be backtested (use strategy.entry and strategy.exit with explicit stop and limit prices). Include an option for fixed percent position sizing and an option for fixed contract size. Draw the trendline on the chart (with option to hide/show) and add labels that show: bias (Bull/Bear), trendline slope, entry price, SL, TP and the reason (e.g., "Trendline Breakout"). Provide user inputs for: EMA length (default 200), lookback for pivot detection, pivot sensitivity (left/right bars), quantity mode (percent / contracts), risk percent or fixed size, enable/disable backtest prints, and enable alerts. Avoid repainting: use confirmed pivot logic (pivot detection must use completed bars) and only take entry after breakout confirmed on close. Document any limitations (for example, trendline using two highest/highest bars inside lookback is approximate). Add clear comments, helpful variable names, and include example alertcondition lines for entry and exit signals.






















