NR4/NR7 + Refined Trend FilterThis version allows the candle to pull toward the 10 EMA without disqualifying the trend—but keeps things on a bullish leash.
Volatility
Machine Learning | Adaptive Trend Signals [Bitwardex]⚙️🧠Machine Learning | Adaptive Trend Signals
🔷Overview
Machine Learning | Adaptive Trend Signals is a Pine Script™ v6 indicator designed to visualize market trends and generate signals through a combination of volatility clustering, Gaussian smoothing, and adaptive trend calculations. Built as an overlay indicator, it integrates advanced techniques inspired by machine learning concepts, such as K-Means clustering, to adapt to changing market conditions. The script is highly customizable, includes a backtesting module, and supports alert conditions, making it suitable for traders exploring trend-based strategies and developers studying volatility-driven indicator design.
🔷Functionality
The indicator performs the following core functions:
• Volatility Clustering: Uses K-Means clustering to categorize market volatility into high, medium, and low states, adjusting trend sensitivity accordingly.
• Trend Calculation: Computes adaptive trend lines (SmartTrend) based on volatility-adjusted standard deviation, smoothed RSI, and ADX filters.
• Signal Generation: Identifies potential buy and sell points through trend line crossovers and directional confirmation.
• Backtesting Module: Tracks trade outcomes based on the SmartTrend3 value, displaying win rate and total trades.
• Visualization: Plots trend lines with gradient colors and optional signal markers (bullish 🐮 and bearish 🐻).
• Alerts: Provides configurable alerts for trend shifts and volatility state changes.
🔷Technical Methodology
Volatility Clustering with K-Means
The indicator employs a K-Means clustering algorithm to classify market volatility, measured via the Average True Range (ATR), into three distinct clusters:
• Data Collection: Gathers ATR values over a user-defined training period (default: 100 bars).
• Centroid Initialization: Sets initial centroids at the highest, lowest, and midpoint ATR values within the training period.
• Iterative Clustering: Assigns ATR data points to the nearest centroid, recalculates centroid means, and repeats until convergence.
• Dynamic Adjustment: Assigns a volatility state (high, medium, or low) based on the closest centroid, adjusting the trend factor (e.g., tighter for high volatility, wider for low volatility).
This approach allows the indicator to adapt its sensitivity to varying market conditions, providing a data-driven foundation for trend calculations.
🔷Gaussian Smoothing
To enhance signal clarity and reduce noise, the indicator applies Gaussian kernel smoothing to:
• RSI: Smooths the Relative Strength Index (calculated from OHLC4) to filter short-term fluctuations.
• SmartTrend: Smooths the primary trend line for a more stable output.
The Gaussian kernel uses a sigma value derived from the user-defined smoothing length, ensuring mathematically consistent noise reduction.
🔷SmartTrend Calculation
The pineSmartTrend function is the core of the indicator, producing three trend lines:
• SmartTrend: The primary trend line, calculated using a volatility-adjusted standard deviation, smoothed RSI, and ADX conditions.
• SmartTrend2: A secondary trend line with a wider factor (base factor * 1.382) for signal confirmation.
SmartTrend3: The average of SmartTrend and SmartTrend2, used for plotting and backtesting.
Key components of the calculation include:
• Dynamic Standard Deviation: Scales based on ATR relative to its 50-period smoothed average, with multipliers (1.0 to 1.4) applied according to volatility thresholds.
• RSI and ADX Filters: Requires RSI > 50 for bullish trends or < 50 for bearish trends, alongside ADX > 15 and rising to confirm trend strength.
Volatility-Adjusted Bands: Constructs upper and lower bands around price action, adjusted by the volatility cluster’s dynamic factor.
🔷Signal Generation
The generate_signals function generates signals as follows:
• Buy Signal: Triggered when SmartTrend crosses above SmartTrend2 and the price is above SmartTrend, with directional confirmation.
• Sell Signal: Triggered when SmartTrend crosses below SmartTrend2 and the price is below SmartTrend, with directional confirmation.
Directional Logic: Tracks trend direction to filter out conflicting signals, ensuring alignment with the broader market context.
Signals are visualized as small circles with bullish (🐮) or bearish (🐻) emojis, with an option to toggle visibility.
🔷Backtesting
The get_backtest function evaluates signal outcomes using the SmartTrend3 value (rather than closing prices) to align with the trend-based methodology.
It tracks:
• Total Trades: Counts completed long and short trades.
• Win Rate: Calculates the percentage of trades where SmartTrend3 moves favorably (higher for longs, lower for shorts).
Position Management: Closes opposite positions before opening new ones, simulating a single-position trading system.
Results are displayed in a table at the top-right of the chart, showing win rate and total trades. Note that backtest results reflect the indicator’s internal logic and should not be interpreted as predictive of real-world performance.
🔷Visualization and Alerts
• Trend Lines: SmartTrend3 is plotted with gradient colors reflecting trend direction and volatility cluster, accompanied by a secondary line for visual clarity.
• Signal Markers: Optional buy/sell signals are plotted as small circles with customizable colors.
• Alerts: Supports alerts for:
• Bullish and bearish trend shifts (confirmed on bar close).
Transitions to high, medium, or low volatility states.
🔷Input Parameters
• ATR Length (default: 14): Period for ATR calculation, used in volatility clustering.
• Period (default: 21): Common period for RSI, ADX, and standard deviation calculations.
• Base SmartTrend Factor (default: 2.0): Base multiplier for volatility-adjusted bands.
• SmartTrend Smoothing Length (default: 10): Length for Gaussian smoothing of the trend line.
• Show Buy/Sell Signals? (default: true): Enables/disables signal markers.
• Bullish/Bearish Color: Customizable colors for trend lines and signals.
🔷Usage Instructions
• Apply to Chart: Add the indicator to any TradingView chart.
• Configure Inputs: Adjust parameters to align with your trading style or market conditions (e.g., shorter ATR length for faster markets).
• Interpret Output:
• Trend Lines: Use SmartTrend3’s direction and color to gauge market bias.
• Signals: Monitor bullish (🐮) and bearish (🐻) markers for potential entry/exit points.
• Backtest Table: Review win rate and total trades to understand the indicator’s behavior in historical data.
• Set Alerts: Configure alerts for trend shifts or volatility changes to support manual or automated trading workflows.
• Combine with Analysis: Use the indicator alongside other tools or market context, as it is designed to complement, not replace, comprehensive analysis.
🔷Technical Notes
• Data Requirements: Requires at least 100 bars for accurate volatility clustering. Ensure sufficient historical data is loaded.
• Market Suitability: The indicator is designed for trend detection and may perform differently in ranging or volatile markets due to its reliance on RSI and ADX filters.
• Backtesting Scope: The backtest module uses SmartTrend3 values, which may differ from price-based outcomes. Results are for informational purposes only.
• Computational Intensity: The K-Means clustering and Gaussian smoothing may increase processing time on lower timeframes or with large datasets.
🔷For Developers
The script is modular, well-commented, encouraging reuse and modification with proper attribution.
Key functions include:
• gaussianSmooth: Applies Gaussian kernel smoothing to any data series.
• pineSmartTrend: Computes adaptive trend lines with volatility and momentum filters.
• getDynamicFactor: Adjusts trend sensitivity based on volatility clusters.
• get_backtest: Evaluates signal performance using SmartTrend3.
Developers can extend these functions for custom indicators or strategies, leveraging the volatility clustering and smoothing methodologies. The K-Means implementation is particularly useful for adaptive volatility analysis.
🔷Limitations
• The indicator is not predictive and should be used as part of a broader trading strategy.
• Performance varies by market, timeframe, and parameter settings, requiring user experimentation.
• Backtest results are based on historical data and internal logic, not real-world trading conditions.
• Volatility clustering assumes sufficient historical data; incomplete data may affect accuracy.
🔷Acknowledgments
Developed by Bitwardex, inspired by machine learning concepts and adaptive trading methodologies. Community feedback is welcome via TradingView’s platform.
🔷 Risk Disclaimer
Trading involves significant risks, and most traders may incur losses. Bitwardex AI Algo is provided for informational and educational purposes only and does not constitute financial advice or a recommendation to buy or sell any financial instrument . The signals, metrics, and features are tools for analysis and do not guarantee profits or specific outcomes. Past performance is not indicative of future results. Always conduct your own due diligence and consult a financial advisor before making trading decisions.
Heikin Ashi Reversal AlertHeikin ashi reverseal bullish after three or more bearish heikin ashi candles
NR4/NR7 + Strong Uptrend FilterNR4/NR7 Tight Range Breakout Scanner with Trend Confirmation
This script identifies explosive breakout candidates by scanning for NR4 (Narrowest Range in 4 days) and NR7 (Narrowest Range in 7 days) setups, only when the underlying stock is showing strong bullish alignment.
Why This Matters
Narrow range candles often precede volatility. When you combine that compression with a strong uptrend, you’re essentially spotting a coiled spring—just before the snap. Most traders chase moves. This one waits—quiet, deliberate, prepared.
Trend Filter Criteria
To ensure quality and avoid weak setups, the scanner only signals when:
The closing price is above the 10 EMA
The 10 EMA is above the 20 EMA
This confirms strong short-term momentum and trend alignment—what some call a “momentum staircase.” It keeps you on the frontside of the move and filters out chop, fakeouts, and death-by-a-thousand-wick scenarios.
Visuals
Orange Label → NR4 in a strong trend
Purple Label → NR7 in a strong trend
Background also highlights to give subtle visual cues
Best Use Case
Scan end-of-day or intraday on your watchlist. Combine it with:
MACD expansion
Low float + news catalysts
Volume surges
Breakout-ready chart structure
Result?
You don’t chase.
You don’t guess.
You stalk high-probability trades like a nobleman with a sniper rifle.
NR4/NR7 + 10 EMA Trend Filter📝 Description:
This script spots NR4 and NR7 days—those deceptively quiet candles where price volatility contracts... right before a potential breakout.
But here’s the twist:
It only highlights setups when the stock is above the 10 EMA, filtering for bullish trends with real momentum behind them.
We’re not interested in weak sauce. We want spring-loaded coils in strong uptrends.
🧠 What It Does:
🔍 NR4 (Narrow Range 4): Today's range is the smallest of the last 4 days
🧨 NR7 (Narrow Range 7): Today's range is the smallest of the last 7 days
🧭 Trend Filter: Highlights only when price is above the 10-period EMA
🎯 Visual Cues: Orange background and label for NR4, purple for NR7
Whale Psychology Insights
### 🧠 Whale Psychology Insights – Unmasking Smart Money Moves
**Understand the mind games behind every candle.**
This advanced indicator is designed to reveal the psychological warfare played by whales and market manipulators in the crypto space. Stop trading blind—start trading with the insights of the smart money.
#### 🔍 What It Does:
- **Liquidity Zone Detection** – Automatically identifies key **swing highs/lows** where stop hunts are likely.
- **Volume Spike Alerts** – Spot **suspicious activity** where big players enter or exit.
- **Order Block Zones** – Highlights **bullish/bearish engulfing patterns** used by institutions.
- **Fair Value Gaps (FVG)** – Marks price inefficiencies where price may return.
- **Fakeout Detection** – Finds **manipulative wicks** designed to trap retail traders.
#### 💡 Use Cases:
- Avoid getting stopped out by **liquidity grabs**
- Enter after the **whales have made their move**
- Identify **high-probability reversal zones**
- Trade **with smart money**, not against it
Perfect for scalpers, intraday traders, and swing traders looking to understand *why* price moves—not just *where*.
> 🧠 **Trade the psychology, not just the chart.**
MAD Trend Detector ~ C H I P AMAD Trend Detector ~ C H I P A is a custom trend detection tool designed to identify meaningful price deviations using Median Absolute Deviation (MAD) logic layered over a smoothed price baseline.
It uses:
A user-selectable source (Close, High, Low, etc.)
A configurable EMA or SMA as the core smoothing layer
Median Absolute Deviation (MAD) to measure typical price dispersion
A user-adjustable MAD multiplier to fine-tune trend sensitivity
Trend bands that expand dynamically based on local volatility
This setup highlights breakout conditions when price detaches meaningfully from its typical behavior — helping traders detect trend acceleration, volatility breakouts, and directional shifts with minimal lag and reduced noise.
Candle coloring responds directly to trend status, with electric blue and red visuals for clear on-chart recognition.
Alpha Beta Gamma with Volume CandleAlpha Beta Gamma with Volume Candle
This Pine Script indicator analyzes price dynamics and volume activity to assist traders in identifying momentum, reversals, and key price levels. It calculates three proprietary metrics—Alpha, Beta, and Gamma—based on a user-selected price type (e.g., Open, Close, HL2) and timeframe, using a lookback period (default 37 bars). These metrics normalize price movements relative to the range of highs and lows, helping traders gauge market strength and positioning.
How It Works:
Alpha: Measures the distance of the selected price from the lowest price over the lookback period, normalized by the period length.
Beta: Represents the full price range (high minus low) over the lookback period, scaled by the period length.
Gamma: Normalizes the price’s position within the high-low range, providing a 0–1 scale for relative positioning.
Volume Analysis: The script classifies candles based on volume thresholds relative to a simple moving average (SMA, default 400 bars). High volume (≥ 2x SMA), low volume (≤ 0.5x SMA), and strong signal volume (≥ 1.5x SMA) trigger distinct candle colors to highlight bullish (e.g., deep blue, violet) or bearish (e.g., aqua, pink) conditions.
Custom Bands: Nine horizontal levels (0 to 1, divided into eight equal parts) act as dynamic support/resistance zones, useful for grid-based trading or breakout strategies.
How to Use:
Inputs:
Chart Timeframe: Select the timeframe for price data (e.g., 1H, 1D).
Price Type: Choose the price metric (e.g., Close, HL2) for calculations.
ABG Length: Adjust the lookback period (default 37) for sensitivity.
Volume MA Length: Set the SMA period for volume analysis (default 400).
Volume Thresholds: Customize high, low, and strong volume multipliers.
Visual Settings: Toggle labels, custom bands, and table display; adjust line styles, label sizes, and table positions.
Interpretation:
Use Alpha, Beta, and Gamma plots to assess price momentum and range dynamics.
Monitor colored candles for volume-driven signals (e.g., violet for strong bullish volume).
Leverage custom bands for support/resistance or breakout trading.
Check the table for real-time ABG values and percentage changes.
Settings Tips:
For scalping, reduce the ABG Length (e.g., 20) and use a shorter timeframe (e.g., 5M).
For swing trading, increase the Volume MA Length (e.g., 600) for more stable volume signals.
Enable labels and custom bands for visual clarity on key levels.
This indicator is versatile for various trading styles, combining price-based metrics with volume analysis to enhance decision-making.
Trailing STOP based on ATR with Offset, SMA, and RMATrailing STOP based on Average True Range (ATR)
Start with Multiplier = 2 and Offset = 1
Smart Market Matrix Smart Market Matrix
This indicator is designed for intraday, scalping, providing automated detection of price pivots, liquidity traps, and breakout confirmations, along with a context dashboard featuring volatility, trend, and volume.
## Summary Description
### Menu Settings & Their Roles
- **Swing Pivot Strength**: Controls the sensitivity for detecting High/Low pivots.
- **Show Pivot Points**: Toggles the display of HH/LL markers on the chart.
- **VWMA Length for Trap Volume** & **Volume Spike Multiplier**: Identify concentrated volume spikes for liquidity traps.
- **Wick Ratio Threshold** & **Max Body Size Ratio**: Detect candles with disproportionate wicks and small bodies (doji-ish) for traps.
- **ATR Length for Trap**: Measures volatility specific to trap detection.
- **VWMA Length for Breakout Volume**, **ATR Multiplier for Breakout**, **ATR Length for Breakout**, **Min Body/Range Ratio**: Set adaptive breakout thresholds based on volatility and volume.
- **OBV Smooth Length**: Smooths OBV momentum for breakout confirmation.
- **Enable VWAP Filter for Confirmations**: Optionally validate breakouts against the VWAP.
- **Enable Higher-TF Trend Filter** & **Trend Filter Timeframe**: Align breakout signals with the 1h/4h/Daily trend.
- **ADX Length**, **EMA Fast/Slow Length for Context**: Parameters for the context dashboard (Volatility, Trend, Volume).
- **Show Intraday VWAP Line**, **VWAP Line Color/Width**: Display the intraday VWAP line with custom style.
### Signal Interpretation Map
| Signal | Description | Recommended Action |
|--------------------------------|-----------------------------------------------------------|-------------------------------------------|
| 📌 **HH / LL (pivot)** | Market structure (support/resistance) | Note key levels |
| **Bull Trap(green diamond)** | Sweep down + volume spike + wick + rejection | Go long with trend filter
| **Bear Trap(red diamond)** | Sweep up + volume spike + wick + rejection | Go short with trend filter
| 🔵⬆️ **Breakout Confirmed Up** | Close > ATR‑scaled high + volume + OBV↑ | Go long with trend filter |
| 🔵⬇️ **Breakout Confirmed Down** | Close < ATR‑scaled low + volume + OBV↓ | Go short with trend filter |
| 📊 **VWAP Line** | Intraday reference to guide price | Use as dynamic support/resistance |
| ⚡ **Volatility** | ATR ratio High/Med/Low | Adjust position size |
| 📈 **Trend Context** | ADX+EMA Strong/Moderate/Weak | Confirm trend direction |
| 🔍 **Volume Context** | Breakout / Rising / Falling / Calm | Check volume momentum |
*This summary gives you a quick overview of the key settings and how to interpret signals for efficient intraday scalping.*
### Suggested Settings
- **Intraday Scalping (5m–15m)**
- `Swing Pivot Strength = 5`
- `VWMA Length for Trap Volume = 10`, `Volume Spike Multiplier = 1.6`
- `ATR Length for Trap = 7`
- `VWMA Length for Breakout Volume = 12`, `ATR Length for Breakout = 9`, `ATR Multiplier for Breakout = 0.5`
- `Min Body/Range Ratio for Breakout = 0.5`, `OBV Smooth Length = 7`
- `Enable Higher-TF Trend Filter = true` (TF = 60)
- `Show Intraday VWAP Line = true` (Color = orange, Width = 2)
- **Swing Trading (4h–Daily)**
- `Swing Pivot Strength = 10`
- `VWMA Length for Trap Volume = 20`, `Volume Spike Multiplier = 2.0`
- `ATR Length for Trap = 14`
- `VWMA Length for Breakout Volume = 30`, `ATR Length for Breakout = 14`, `ATR Multiplier for Breakout = 0.8`
- `Min Body/Range Ratio for Breakout = 0.7`, `OBV Smooth Length = 14`
- `Enable Higher-TF Trend Filter = true` (TF = D)
- `Show Intraday VWAP Line = false`
*Adjust these values based on the symbol and market volatility for optimal performance.*
Average Daily Price Movement (14 Days)Computes the daily high-low range
Averages it over 14 candles
Displays a label on the most recent candle with the average range in text
Fair Value Area at Swing ZonesIts as the name says. It combines volume profile important areas (70% of trading taking place in whats called a Fair value zone) and area between a swing high and a swing low which is also considered a fair value zone.
You can use it to trade breakout trades as well as range trades.
Freedom LR Price Action PublicThis is a script using multiple types of linear regression with channels, LSMAs, signal lines based on LSMAs, and ATR based on linear regression.
Ultimate Scalping DashboardWhat This Dashboard Includes (Visually Compact):
Trend: EMA 9/21/50 alignment
Momentum: MACD + Stochastic RSI direction
Bias: VWAP position (above/below)
Volume: Spike status
Squeeze: Bollinger Band squeeze
SuperTrend: Bullish/Bearish
Divergence: RSI/MACD signal
Buy/Sell Signal Summary
It gives you a clean table-style display at the top or bottom of the screen — super useful for 15m scalping.
Real-time dashboard at the bottom-right of your chart
Color-coded cells for instant visual clarity
Final signal to tell you: BUY, SELL, or WAIT
RSI Divergence Strategy - AliferCryptoStrategy Overview
The RSI Divergence Strategy is designed to identify potential reversals by detecting regular bullish and bearish divergences between price action and the Relative Strength Index (RSI). It automatically enters positions when a divergence is confirmed and manages risk with configurable stop-loss and take-profit levels.
Key Features
Automatic Divergence Detection: Scans for RSI pivot lows/highs vs. price pivots using user-defined lookback windows and bar ranges.
Dual SL/TP Methods:
- Swing-based: Stops placed a configurable percentage beyond the most recent swing high/low.
- ATR-based: Stops placed at a multiple of Average True Range, with a separate risk/reward multiplier.
Long and Short Entries: Buys on bullish divergences; sells short on bearish divergences.
Fully Customizable: Input groups for RSI, divergence, swing, ATR, and general SL/TP settings.
Visual Plotting: Marks divergences on chart and plots stop-loss (red) and take-profit (green) lines for active trades.
Alerts: Built-in alert conditions for both bullish and bearish RSI divergences.
Detailed Logic
RSI Calculation: Computes RSI of chosen source over a specified period.
Pivot Detection:
- Identifies RSI pivot lows/highs by scanning a lookback window to the left and right.
- Uses ta.barssince to ensure pivots are separated by a minimum/maximum number of bars.
Divergence Confirmation:
- Bullish: Price makes a lower low while RSI makes a higher low.
- Bearish: Price makes a higher high while RSI makes a lower high.
Entry:
- Opens a Long position when bullish divergence is true.
- Opens a Short position when bearish divergence is true.
Stop-Loss & Take-Profit:
- Swing Method: Computes the recent swing high/low then adjusts by a percentage margin.
- ATR Method: Uses the current ATR × multiplier applied to the entry price.
- Take-Profit: Calculated as entry price ± (risk × R/R ratio).
Exit Orders: Uses strategy.exit to place bracket orders (stop + limit) for both long and short positions.
Inputs and Configuration
RSI Settings: Length & price source for the RSI.
Divergence Settings: Pivot lookback parameters and valid bar ranges.
SL/TP Settings: Choice between Swing or ATR method.
Swing Settings: Swing lookback length, margin (%), and risk/reward ratio.
ATR Settings: ATR length, stop multiplier, and risk/reward ratio.
Usage Notes
Adjust the Pivot Lookback and Range values to suit the volatility and timeframe of your market.
Use higher ATR multipliers for wider stops in choppy conditions, or tighten swing margins in trending markets.
Backtest different R/R ratios to find the balance between win rate and reward.
Disclaimer
This script is for educational purposes only and does not constitute financial advice. Trading carries significant risk and you may lose more than your initial investment. Always conduct your own research and consider consulting a professional before making any trading decisions.
💥 Early Breakout Detector (Penny Stocks)Early Breakout Detector – Penny Stocks Edition"
This script is designed to detect early breakout signals in low-priced stocks (penny stocks) before the actual breakout happens. It combines multiple technical indicators to spot high-probability setups where a price explosion may be imminent.
🔍 Included logic:
– Unusual relative volume (volume > 2x 20-period average)
– RSI momentum turning bullish (RSI > 50)
– Price trading above the 20-period moving average
– Price approaching recent resistance (within 3%) but not yet breaking it
📈 When all conditions align, a "PRE" label appears on the chart, and an alert can be triggered to catch the move before it happens.
💡 Ideal for traders looking to enter positions before breakouts occur, especially in momentum-driven penny stocks.
🚨 Alerts included. Works on any timeframe. Best results observed on 5min–1H for intraday setups.
🛠 You can modify volume thresholds, RSI period, or resistance distance to suit your strategy.
— Built by AI
Highest/Lowest Range in TimeframeThis script helps traders visually identify the highest high and lowest low within a customizable range of recent bars.
🔍 Key Features
Scans the last 100 to 1000 bars (user-defined)
Automatically detects:
The highest wick (high) and lowest wick (low)
Draws dotted green horizontal lines at both levels
Shows a label indicating the percentage range between high and low
Displays real-time high and low price labels directly on the chart
⚙️ Use Cases
Quickly spot price extremes over your desired time window
Visually measure market range and volatility
Identify breakout potential or reversal zones
✅ How to Use
Add the script to your chart.
Set the “Bars to Scan” input to your desired lookback period (between 100–1000).
Use the displayed lines and labels to identify key high/low price levels and range metrics.
Polygot Moving AveragesDescription
This is essentially a source merger of Bollinger Bands by Trading View and Simple Moving Averages by stoxxinbox. My additions and subtractions are minimal. There is the BB MA, which I default at 5d, and the other 4 averages are the standard 21, 50, 100, 200, day moving averages. I default the averaging method to WMA (Weighted Moving Average). The method of averaging can be changed as also can the lengths of the inputs to match user preferences. This is what I wanted for an indicator and didn't find.
Usage
The same as you would use any other BB or MA indicator. The benefit of this one is that it has 4 MAs, one MA with the Bollinger Bands attached, and the colours adjusted to be easy on the eyes when using high contrast themes, to be discernible yet sit quietly in the background with lines and candle sticks everywhere shouting for attention. I use it as a base first indicator which I can hide easily (imagine hiding five MA indicators individually constantly) when the more serious indicators come into play.
Uptrick: Dynamic Z-Score DeviationOverview
Uptrick: Dynamic Z‑Score Deviation is a trading indicator built in Pine Script that combines statistical filters and adaptive smoothing to highlight potential reversal points in price action. It combines a hybrid moving average, dual Z‑Score analysis on both price and RSI, and visual enhancements like slope‑based coloring, ATR‑based shadow bands, and dynamically scaled reversal signals.
Introduction
Statistical indicators like Z‑Scores measure how far a value deviates from its average relative to the typical variation (standard deviation). Standard deviation quantifies how dispersed a set of values is around its mean. A Z‑Score of +2 indicates a value two standard deviations above the mean, while -2 is two below. Traders use Z‑Scores to spot unusually high or low readings that may signal overbought or oversold conditions.
Moving averages smooth out price data to reveal trends. The Arnaud Legoux Moving Average (ALMA) reduces lag and noise through weighted averaging. A Zero‑Lag EMA (approximated here using a time‑shifted EMA) seeks to further minimize delay in following price. The RSI (Relative Strength Index) is a momentum oscillator that measures recent gains against losses over a set period.
ATR (Average True Range) gauges market volatility by averaging the range between high and low over a lookback period. Shadow bands built using ATR give a visual mood of volatility around a central trend line. Together, these tools inform a dynamic but statistically grounded view of market extremes.
Purpose
The main goal of this indicator is to help traders spot short‑term reversal opportunities on lower timeframes. By requiring both price and momentum (RSI) to exhibit statistically significant deviations from their norms, it filters out weak setups and focuses on higher‑probability mean‑reversion zones. Reversal signals appear when price deviates far enough from its hybrid moving average and RSI deviates similarly in the same direction. This makes it suitable for discretionary traders seeking clean entry cues in volatile environments.
Originality and Uniqueness
Uptrick: Dynamic Z‑Score Deviation distinguishes itself from standard reversal or mean‑reversion tools by combining several elements into a single framework:
A composite moving average (ALMA + Zero‑Lag EMA) for a smooth yet responsive baseline
Dual Z‑Score filters on price and RSI rather than relying on a single measure
Adaptive visual elements, including slope‑aware coloring, multi‑layer ATR shadows, and signal sizing based on combined Z‑Score magnitude
Most indicators focus on one aspect—price envelopes or RSI thresholds—whereas Uptrick: Dynamic Z‑Score Deviation requires both layers to align before signaling. Its visual design aids quick interpretation without overwhelming the chart.
Why these indicators were merged
Every component in Uptrick: Dynamic Z‑Score Deviation has a purpose:
• ALMA: provides a smooth moving average with reduced lag and fewer false crossovers than a simple SMA or EMA.
• Zero‑Lag EMA (ZLMA approximation): further reduces the delay relative to price by applying a time shift to EMA inputs. This keeps the composite MA closer to current price action.
• RSI and its EMA filter: RSI measures momentum. Applying an EMA filter on RSI smooths out false spikes and confirms genuine overbought or oversold momentum.
• Dual Z‑Scores: computing Z‑Scores on both the distance between price and the composite MA, and on smoothed RSI, ensures that signals only fire when both price and momentum are unusually stretched.
• ATR bands: using ATR‑based shadow layers visualizes volatility around the MA, guiding traders on potential support and resistance zones.
At the end, these pieces merge into a single indicator that detects statistically significant mean reversions while staying adaptive to real‑time volatility and momentum.
Calculations
1. Compute ALMA over the chosen MA length, offset, and sigma.
2. Approximate ZLMA by applying EMA to twice the price minus the price shifted by the MA length.
3. Calculate the composite moving average as the average of ALMA and ZLMA.
4. Compute raw RSI and smooth it with ALMA. Apply an EMA filter to raw RSI to reduce noise.
5. For both price and smoothed RSI, calculate the mean and standard deviation over the Z‑Score lookback period.
6. Compute Z‑Scores:
• z_price = (current price − composite MA mean) / standard deviation of price deviations
• z_rsi = (smoothed RSI − mean RSI) / standard deviation of RSI
7. Determine reversal conditions: both Z‑Scores exceed their thresholds in the same direction, RSI EMA is in oversold/overbought zones (below 40 or above 60), and price movement confirms directionality.
8. Compute signal strength as the sum of the absolute Z‑Scores, then classify into weak, medium, or strong.
9. Calculate ATR over the chosen period and multiply by layer multipliers to form shadow widths.
10.Derive slope over the chosen slope length and color the MA line and bars based on direction, optionally smoothing color transitions via EMA on RGB channels.
How this indicator actually works
1. The script begins by smoothing price data with ALMA and approximating a zero‑lag EMA, then averaging them for the main MA.
2. RSI is calculated, then smoothed and filtered.
3. Using a rolling window, the script computes statistical measures for both price deviations and RSI.
4. Z‑Scores tell how far current values lie from their recent norms.
5. When both Z‑Scores cross configured thresholds and momentum conditions align, reversal signals are flagged.
6. Signals are drawn with size and color reflecting strength.
7. The MA is plotted with dynamic coloring; ATR shadows are layered beneath to show volatility envelopes.
8. Bars can be colored to match MA slope, reinforcing trend context.
9. Alert conditions allow automated notifications when signals occur.
Inputs
Main Length: Main MA Length. Sets the period for ALMA and ZLMA.
RSI Length: RSI Length. Determines the lookback for momentum calculations.
Z-Score Lookback: Z‑Score Lookback. Window for mean and standard deviation computations.
Price Z-Score Threshold: Price Z‑Score Threshold. Minimum deviation required for price.
RSI Z-Score threshold: RSI Z‑Score Threshold. Minimum deviation required for momentum.
RSI EMA Filter Length: RSI EMA Filter Length. Smooths raw RSI readings.
ALMA Offset: Controls ALMA’s focal point in the window.
ALMA Sigma: Adjusts ALMA’s smoothing strength.
Show Reversal Signals : Toggle to display reversal signal markers.
Slope Sensitivity: Length for slope calculation. Higher values smooth slope changes.
Use Bar Coloring: Enables coloring of price bars based on MA slope.
Show MA Shadow: Toggle for ATR‑based shadow bands.
Shadow Layer Count: Number of shadow layers (1–4).
Base Shadow ATR Multiplier: Multiplier for ATR when sizing the first band.
Smooth Color Transitions (boolean): Smooths RGB transitions for line and shadows, if enabled.
ATR Length for Shadow: ATR Period for computing volatility bands.
Use Dynamic Signal Size: Toggles dynamic scaling of reversal symbols.
Features
Moving average smoothing: a hybrid of ALMA and Zero‑Lag EMA that balances responsiveness and noise reduction.
Slope coloring: MA line and optionally price bars change color based on trend direction; color transitions can be smoothed for visual continuity.
ATR shadow layers: translucent bands around the MA show volatility envelopes; up to four concentric layers help gauge distance from normal price swings.
Dual Z‑Score filters: price and momentum must both deviate beyond thresholds to trigger signals, reducing false positives.
Dynamic signal sizing: reversal markers scale in size based on the combined Z‑Score magnitude, making stronger signals more prominent.
Adaptive visuals: optional smoothing of color channels creates gradient effects on lines and fills for a polished look.
Alert conditions: built‑in buy and sell alerts notify traders when reversal setups emerge.
Conclusion
Uptrick: Dynamic Z‑Score Deviation delivers a structured way to identify short‑term reversal opportunities by fusing statistical rigor with adaptive smoothing and clear visual cues. It guides traders through multiple confirmation layers—hybrid moving average, dual Z‑Score analysis, momentum filtering, and volatility envelopes—while keeping the chart clean and informative.
Disclaimer
This indicator is provided for informational and educational purposes only and does not constitute financial advice. Trading carries risk and may not be suitable for all participants. Past performance is not indicative of future results. Always do your own analysis and risk management before making trading decisions.
Bullish and Bearish Breakout Alert for Gold Futures PullbackBelow is a Pine Script (version 6) for TradingView that includes both bullish and bearish breakout conditions for my intraday trading strategy on micro gold futures (MGC). The strategy focuses on scalping two-legged pullbacks to the 20 EMA or key levels with breakout confirmation, tailored for the Apex Trader Funding $300K challenge. The script accounts for the Daily Sentiment Index (DSI) at 87 (overbought, favoring pullbacks). It generates alerts for placing stop-limit orders for 175 MGC contracts, ensuring compliance with Apex’s rules ($7,500 trailing threshold, $20,000 profit target, 4:59 PM ET close).
Script Requirements
Version: Pine Script v6 (latest for TradingView, April 2025).
Purpose:
Bullish: Alert when price breaks above a rejection candle’s high after a two-legged pullback to the 20 EMA in a bullish trend (price above 20 EMA, VWAP, higher highs/lows).
Bearish: Alert when price breaks below a rejection candle’s low after a two-legged pullback to the 20 EMA in a bearish trend (price below 20 EMA, VWAP, lower highs/lows).
Context: 5-minute MGC chart, U.S. session (8:30 AM–12:00 PM ET), avoiding overbought breakouts above $3,450 (DSI 87).
Output: Alerts for stop-limit orders (e.g., “Buy: Stop=$3,377, Limit=$3,377.10” or “Sell: Stop=$3,447, Limit=$3,446.90”), quantity 175 MGC.
Apex Compliance: 175-contract limit, stop-losses, one-directional news trading, close by 4:59 PM ET.
How to Use the Script in TradingView
1. Add Script:
Open TradingView (tradingview.com).
Go to “Pine Editor” (bottom panel).
Copy the script from the content.
Click “Add to Chart” to apply to your MGC 5-minute chart .
2. Configure Chart:
Symbol: MGC (Micro Gold Futures, CME, via Tradovate/Apex data feed).
Timeframe: 5-minute (entries), 15-minute (trend confirmation, manually check).
Indicators: Script plots 20 EMA and VWAP; add RSI (14) and volume manually if needed .
3. Set Alerts:
Click the “Alert” icon (bell).
Add two alerts:
Bullish Breakout: Condition = “Bullish Breakout Alert for Gold Futures Pullback,” trigger = “Once Per Bar Close.”
Bearish Breakout: Condition = “Bearish Breakout Alert for Gold Futures Pullback,” trigger = “Once Per Bar Close.”
Customize messages (default provided) and set notifications (e.g., TradingView app, SMS).
Example: Bullish alert at $3,377 prompts “Stop=$3,377, Limit=$3,377.10, Quantity=175 MGC” .
4. Execute Orders:
Bullish:
Alert triggers (e.g., stop $3,377, limit $3,377.10).
In TradingView’s “Order Panel,” select “Stop-Limit,” set:
Stop Price: $3,377.
Limit Price: $3,377.10.
Quantity: 175 MGC.
Direction: Buy.
Confirm via Tradovate.
Add bracket order (OCO):
Stop-loss: Sell 175 at $3,376.20 (8 ticks, $1,400 risk).
Take-profit: Sell 87 at $3,378 (1:1), 88 at $3,379 (2:1) .
Bearish:
Alert triggers (e.g., stop $3,447, limit $3,446.90).
Select “Stop-Limit,” set:
Stop Price: $3,447.
Limit Price: $3,446.90.
Quantity: 175 MGC.
Direction: Sell.
Confirm via Tradovate.
Add bracket order:
Stop-loss: Buy 175 at $3,447.80 (8 ticks, $1,400 risk).
Take-profit: Buy 87 at $3,446 (1:1), 88 at $3,445 (2:1) .
5. Monitor:
Green triangles (bullish) or red triangles (bearish) confirm signals.
Avoid bullish entries above $3,450 (DSI 87, overbought) or bearish entries below $3,296 (support) .
Close trades by 4:59 PM ET (set 4:50 PM alert) .
Adaptive ATR LimitsThis script plots adaptive ATR limits for intraday trading. It is intended for equities. It is not tested for other securities like futures, crypto, etc, though it may work for these too. It works for both regular trading hours and extended trading hours.
The limit lines (top and bottom) are always exactly 1 ATR/ADR apart. This is a key feature of the indicator.
The main mode is ATR, which includes overnight gaps and pre- and post-market movements. This also means the previous day close is considered to part of the current days range (which aligns with the definition of ATR). There is also an ADR mode, which uses the average range the price moves within regular hours only and is not affected by prices outside of these. Other than that, they work the same (including ATR/ADR length option and smoothing).
When in ADR mode, it treats premarket as a separate session from the regular/post-market and resets the session range at the regular market open. This is so it can plot the limits in the regular/post-market hours without being affected by the pre-market range. This is necessary since the daily ADR includes only regular market moves and due to the way the limits adapt.
It tries to plot the most sensible ATR limits based on the current daily ATR, in order to provide a visual target for how far a price could/should move intraday. In order to do this, it uses two methods to calculate limits, i) based on the mid-point of the current session range, and ii) based on the currently established range and current relative price position within that range.
The session starts using the first method. As more of the ATR is covered in the session, it transitions over of the second method. Once (if) the full ATR is covered within the session, it will have completely transitioned to the second method and will only use that for the rest of the session. In between these states, a weighted average of the two methods is used depending on the amount of the ATR the session has covered.
To explain the effect, as an example, imagine that the price is approaching the full ATR range on the high side. The indicator will have almost fully transitioned to the second (relative) method. The lower ATR limit will now be anchored to the daily low as the price hits the upper ATR limit. If the price goes beyond the upper ATR, the lower ATR limit will stay anchored to the daily low, and the upper limit will stay anchored to 1 ATR above the lower limit. This allows you to see how far the price is going beyond the upper ATR limit. If the price then returns and backs off the upper ATR limit, the lower ATR limit will un-anchor from the daily low (it will actually rise since the daily ATR range has been exceeded so the lower ATR limit needs to come up since the actual daily range can't fit into the ATR range anymore). The overall effect is to give you the best visual indication where the price is in relation to a possible upper ATR-based target. Reverse this example for when price low approaches the ATR range on the low side.
There is also a "basic mode" which simply plots 1 ATR/ADR above/below the session low/high. When using ADR, the session resets at the end of the pre-market.
The ATR length (averaging period) can be set (number of days), as well as a visual smoothing of the ATR limits using EMA.
Price Variation Percent (PVP) с таймфреймомA standard PVP indicator that has a multi-timeframe function added to it
Momentum + Keltner Stochastic Combo)The Momentum-Keltner-Stochastic Combination Strategy: A Technical Analysis and Empirical Validation
This study presents an advanced algorithmic trading strategy that implements a hybrid approach between momentum-based price dynamics and relative positioning within a volatility-adjusted Keltner Channel framework. The strategy utilizes an innovative "Keltner Stochastic" concept as its primary decision-making factor for market entries and exits, while implementing a dynamic capital allocation model with risk-based stop-loss mechanisms. Empirical testing demonstrates the strategy's potential for generating alpha in various market conditions through the combination of trend-following momentum principles and mean-reversion elements within defined volatility thresholds.
1. Introduction
Financial market trading increasingly relies on the integration of various technical indicators for identifying optimal trading opportunities (Lo et al., 2000). While individual indicators are often compromised by market noise, combinations of complementary approaches have shown superior performance in detecting significant market movements (Murphy, 1999; Kaufman, 2013). This research introduces a novel algorithmic strategy that synthesizes momentum principles with volatility-adjusted envelope analysis through Keltner Channels.
2. Theoretical Foundation
2.1 Momentum Component
The momentum component of the strategy builds upon the seminal work of Jegadeesh and Titman (1993), who demonstrated that stocks which performed well (poorly) over a 3 to 12-month period continue to perform well (poorly) over subsequent months. As Moskowitz et al. (2012) further established, this time-series momentum effect persists across various asset classes and time frames. The present strategy implements a short-term momentum lookback period (7 bars) to identify the prevailing price direction, consistent with findings by Chan et al. (2000) that shorter-term momentum signals can be effective in algorithmic trading systems.
2.2 Keltner Channels
Keltner Channels, as formalized by Chester Keltner (1960) and later modified by Linda Bradford Raschke, represent a volatility-based envelope system that plots bands at a specified distance from a central exponential moving average (Keltner, 1960; Raschke & Connors, 1996). Unlike traditional Bollinger Bands that use standard deviation, Keltner Channels typically employ Average True Range (ATR) to establish the bands' distance from the central line, providing a smoother volatility measure as established by Wilder (1978).
2.3 Stochastic Oscillator Principles
The strategy incorporates a modified stochastic oscillator approach, conceptually similar to Lane's Stochastic (Lane, 1984), but applied to a price's position within Keltner Channels rather than standard price ranges. This creates what we term "Keltner Stochastic," measuring the relative position of price within the volatility-adjusted channel as a percentage value.
3. Strategy Methodology
3.1 Entry and Exit Conditions
The strategy employs a contrarian approach within the channel framework:
Long Entry Condition:
Close price > Close price periods ago (momentum filter)
KeltnerStochastic < threshold (oversold within channel)
Short Entry Condition:
Close price < Close price periods ago (momentum filter)
KeltnerStochastic > threshold (overbought within channel)
Exit Conditions:
Exit long positions when KeltnerStochastic > threshold
Exit short positions when KeltnerStochastic < threshold
This methodology aligns with research by Brock et al. (1992) on the effectiveness of trading range breakouts with confirmation filters.
3.2 Risk Management
Stop-loss mechanisms are implemented using fixed price movements (1185 index points), providing definitive risk boundaries per trade. This approach is consistent with findings by Sweeney (1988) that fixed stop-loss systems can enhance risk-adjusted returns when properly calibrated.
3.3 Dynamic Position Sizing
The strategy implements an equity-based position sizing algorithm that increases or decreases contract size based on cumulative performance:
$ContractSize = \min(baseContracts + \lfloor\frac{\max(profitLoss, 0)}{equityStep}\rfloor - \lfloor\frac{|\min(profitLoss, 0)|}{equityStep}\rfloor, maxContracts)$
This adaptive approach follows modern portfolio theory principles (Markowitz, 1952) and Kelly criterion concepts (Kelly, 1956), scaling exposure proportionally to account equity.
4. Empirical Performance Analysis
Using historical data across multiple market regimes, the strategy demonstrates several key performance characteristics:
Enhanced performance during trending markets with moderate volatility
Reduced drawdowns during choppy market conditions through the dual-filter approach
Optimal performance when the threshold parameter is calibrated to market-specific characteristics (Pardo, 2008)
5. Strategy Limitations and Future Research
While effective in many market conditions, this strategy faces challenges during:
Rapid volatility expansion events where stop-loss mechanisms may be inadequate
Prolonged sideways markets with insufficient momentum
Markets with structural changes in volatility profiles
Future research should explore:
Adaptive threshold parameters based on regime detection
Integration with additional confirmatory indicators
Machine learning approaches to optimize parameter selection across different market environments (Cavalcante et al., 2016)
References
Brock, W., Lakonishok, J., & LeBaron, B. (1992). Simple technical trading rules and the stochastic properties of stock returns. The Journal of Finance, 47(5), 1731-1764.
Cavalcante, R. C., Brasileiro, R. C., Souza, V. L., Nobrega, J. P., & Oliveira, A. L. (2016). Computational intelligence and financial markets: A survey and future directions. Expert Systems with Applications, 55, 194-211.
Chan, L. K. C., Jegadeesh, N., & Lakonishok, J. (2000). Momentum strategies. The Journal of Finance, 51(5), 1681-1713.
Jegadeesh, N., & Titman, S. (1993). Returns to buying winners and selling losers: Implications for stock market efficiency. The Journal of Finance, 48(1), 65-91.
Kaufman, P. J. (2013). Trading systems and methods (5th ed.). John Wiley & Sons.
Kelly, J. L. (1956). A new interpretation of information rate. The Bell System Technical Journal, 35(4), 917-926.
Keltner, C. W. (1960). How to make money in commodities. The Keltner Statistical Service.
Lane, G. C. (1984). Lane's stochastics. Technical Analysis of Stocks & Commodities, 2(3), 87-90.
Lo, A. W., Mamaysky, H., & Wang, J. (2000). Foundations of technical analysis: Computational algorithms, statistical inference, and empirical implementation. The Journal of Finance, 55(4), 1705-1765.
Markowitz, H. (1952). Portfolio selection. The Journal of Finance, 7(1), 77-91.
Moskowitz, T. J., Ooi, Y. H., & Pedersen, L. H. (2012). Time series momentum. Journal of Financial Economics, 104(2), 228-250.
Murphy, J. J. (1999). Technical analysis of the financial markets: A comprehensive guide to trading methods and applications. New York Institute of Finance.
Pardo, R. (2008). The evaluation and optimization of trading strategies (2nd ed.). John Wiley & Sons.
Raschke, L. B., & Connors, L. A. (1996). Street smarts: High probability short-term trading strategies. M. Gordon Publishing Group.
Sweeney, R. J. (1988). Some new filter rule tests: Methods and results. Journal of Financial and Quantitative Analysis, 23(3), 285-300.
Wilder, J. W. (1978). New concepts in technical trading systems. Trend Research.