Momentum Regression [BackQuant]Momentum Regression
The Momentum Regression is an advanced statistical indicator built to empower quants, strategists, and technically inclined traders with a robust visual and quantitative framework for analyzing momentum effects in financial markets. Unlike traditional momentum indicators that rely on raw price movements or moving averages, this tool leverages a volatility-adjusted linear regression model (y ~ x) to uncover and validate momentum behavior over a user-defined lookback window.
Purpose & Design Philosophy
Momentum is a core anomaly in quantitative finance — an effect where assets that have performed well (or poorly) continue to do so over short to medium-term horizons. However, this effect can be noisy, regime-dependent, and sometimes spurious.
The Momentum Regression is designed as a pre-strategy analytical tool to help you filter and verify whether statistically meaningful and tradable momentum exists in a given asset. Its architecture includes:
Volatility normalization to account for differences in scale and distribution.
Regression analysis to model the relationship between past and present standardized returns.
Deviation bands to highlight overbought/oversold zones around the predicted trendline.
Statistical summary tables to assess the reliability of the detected momentum.
Core Concepts and Calculations
The model uses the following:
Independent variable (x): The volatility-adjusted return over the chosen momentum period.
Dependent variable (y): The 1-bar lagged log return, also adjusted for volatility.
A simple linear regression is performed over a large lookback window (default: 1000 bars), which reveals the slope and intercept of the momentum line. These values are then used to construct:
A predicted momentum trendline across time.
Upper and lower deviation bands , representing ±n standard deviations of the regression residuals (errors).
These visual elements help traders judge how far current returns deviate from the modeled momentum trend, similar to Bollinger Bands but derived from a regression model rather than a moving average.
Key Metrics Provided
On each update, the indicator dynamically displays:
Momentum Slope (β₁): Indicates trend direction and strength. A higher absolute value implies a stronger effect.
Intercept (β₀): The predicted return when x = 0.
Pearson’s R: Correlation coefficient between x and y.
R² (Coefficient of Determination): Indicates how well the regression line explains the variance in y.
Standard Error of Residuals: Measures dispersion around the trendline.
t-Statistic of β₁: Used to evaluate statistical significance of the momentum slope.
These statistics are presented in a top-right summary table for immediate interpretation. A bottom-right signal table also summarizes key takeaways with visual indicators.
Features and Inputs
✅ Volatility-Adjusted Momentum : Reduces distortions from noisy price spikes.
✅ Custom Lookback Control : Set the number of bars to analyze regression.
✅ Extendable Trendlines : For continuous visualization into the future.
✅ Deviation Bands : Optional ±σ multipliers to detect abnormal price action.
✅ Contextual Tables : Help determine strength, direction, and significance of momentum.
✅ Separate Pane Design : Cleanly isolates statistical momentum from price chart.
How It Helps Traders
📉 Quantitative Strategy Validation:
Use the regression results to confirm whether a momentum-based strategy is worth pursuing on a specific asset or timeframe.
🔍 Regime Detection:
Track when momentum breaks down or reverses. Slope changes, drops in R², or weak t-stats can signal regime shifts.
📊 Trade Filtering:
Avoid false positives by entering trades only when momentum is both statistically significant and directionally favorable.
📈 Backtest Preparation:
Before running costly simulations, use this tool to pre-screen assets for exploitable return structures.
When to Use It
Before building or deploying a momentum strategy : Test if momentum exists and is statistically reliable.
During market transitions : Detect early signs of fading strength or reversal.
As part of an edge-stacking framework : Combine with other filters such as volatility compression, volume surges, or macro filters.
Conclusion
The Momentum Regression indicator offers a powerful fusion of statistical analysis and visual interpretation. By combining volatility-adjusted returns with real-time linear regression modeling, it helps quantify and qualify one of the most studied and traded anomalies in finance: momentum.
Volatilite
ZF RSI PLOT1. How RSI Is Calculated
RSI is typically computed over 14 periods (days, hours, etc.) using the formula:
RSI=100−1001+RS
RSI=100−1+RS100
where
RS=Average Gain over N periodsAverage Loss over N periods
RS=Average Loss over N periodsAverage Gain over N periods
2. Overbought (> 70)
Definition: An RSI reading above 70 suggests that the instrument has experienced relatively large gains and may be “overbought.”
Interpretation:
Potential Reversal: Prices may have risen too far, too fast, and could be due for a pullback or consolidation.
Exit/Take Profits: Traders often trim long positions or tighten stops as RSI climbs above 70.
Confirmation Needed:
Bearish “RSI divergence” (price makes a higher high while RSI makes a lower high).
Price action signals (e.g., bearish candlestick patterns).
Volume drying up on advances.
3. Oversold (< 30)
Definition: An RSI reading below 30 suggests that the instrument has experienced relatively large losses and may be “oversold.”
Interpretation:
Potential Bounce: Prices may have fallen too far, too fast, and could be due for a rebound or consolidation.
Buying Opportunity: Traders often look to initiate or add to long positions as RSI drops below 30.
Confirmation Needed:
Bullish “RSI divergence” (price makes a lower low while RSI makes a higher low).
Price action signals (e.g., hammer candlesticks, support levels).
Volume picking up on declines.
4. Divergences
Bullish Divergence: Price ↓ makes a lower low, RSI ↑ makes a higher low ⇒ possible trend change to the upside.
Bearish Divergence: Price ↑ makes a higher high, RSI ↓ makes a lower high ⇒ possible trend change to the downside.
5. Adjustments & Variations
Stronger Trends: Use 80/20 thresholds to avoid early signals in very strong up- or down-trends.
Shorter/Longer Periods: Adjust the look-back period (e.g., 9 for more sensitivity, 21 for smoother signals) depending on your time frame.
6. Limitations & Best Practices
Can Stay Extreme: In strong trends, RSI may remain overbought/oversold for extended periods—don’t trade it in isolation.
Combine with Other Tools: Use trend filters (moving averages, ADX), support/resistance, and volume to confirm entries.
Risk Management: Always set stops and manage position size; RSI signals can fail.
7. Putting It All Together
Identify Trend: Is the market in an uptrend, downtrend, or range?
Watch RSI Extremes: Note when RSI crosses above 70 or below 30.
Seek Confirmation: Look for divergences, candlestick/pricing signals, and supporting volume.
Execute & Manage: Enter with clear stop-loss levels, consider scaling, and lock in profits appropriately.
By understanding both the raw threshold signals and the nuances—like divergences and trend-context—you can harness RSI’s simplicity while mitigating its pitfalls.
Rolling Log Returns [BackQuant]Rolling Log Returns
The Rolling Log Returns indicator is a versatile tool designed to help traders, quants, and data-driven analysts evaluate the dynamics of price changes using logarithmic return analysis. Widely adopted in quantitative finance, log returns offer several mathematical and statistical advantages over simple returns, making them ideal for backtesting, portfolio optimization, volatility modeling, and risk management.
What Are Log Returns?
In quantitative finance, logarithmic returns are defined as:
ln(Pₜ / Pₜ₋₁)
or for rolling periods:
ln(Pₜ / Pₜ₋ₙ)
where P represents price and n is the rolling lookback window.
Log returns are preferred because:
They are time additive : returns over multiple periods can be summed.
They allow for easier statistical modeling , especially when assuming normally distributed returns.
They behave symmetrically for gains and losses, unlike arithmetic returns.
They normalize percentage changes, making cross-asset or cross-timeframe comparisons more consistent.
Indicator Overview
The Rolling Log Returns indicator computes log returns either on a standard (1-period) basis or using a rolling lookback period , allowing users to adapt it to short-term trading or long-term trend analysis.
It also supports a comparison series , enabling traders to compare the return structure of the main charted asset to another instrument (e.g., SPY, BTC, etc.).
Core Features
✅ Return Modes :
Normal Log Returns : Measures ln(price / price ), ideal for day-to-day return analysis.
Rolling Log Returns : Measures ln(price / price ), highlighting price drift over longer horizons.
✅ Comparison Support :
Compare log returns of the primary instrument to another symbol (like an index or ETF).
Useful for relative performance and market regime analysis .
✅ Moving Averages of Returns :
Smooth noisy return series with customizable MA types: SMA, EMA, WMA, RMA, and Linear Regression.
Applicable to both primary and comparison series.
✅ Conditional Coloring :
Returns > 0 are colored green ; returns < 0 are red .
Comparison series gets its own unique color scheme.
✅ Extreme Return Detection :
Highlight unusually large price moves using upper/lower thresholds.
Visually flags abnormal volatility events such as earnings surprises or macroeconomic shocks.
Quantitative Use Cases
🔍 Return Distribution Analysis :
Gain insight into the statistical properties of asset returns (e.g., skewness, kurtosis, tail behavior).
📉 Risk Management :
Use historical return outliers to define drawdown expectations, stress tests, or VaR simulations.
🔁 Strategy Backtesting :
Apply rolling log returns to momentum or mean-reversion models where compounding and consistent scaling matter.
📊 Market Regime Detection :
Identify periods of consistent overperformance/underperformance relative to a benchmark asset.
📈 Signal Engineering :
Incorporate return deltas, moving average crossover of returns, or threshold-based triggers into machine learning pipelines or rule-based systems.
Recommended Settings
Use Normal mode for high-frequency trading signals.
Use Rolling mode for swing or trend-following strategies.
Compare vs. a broad market index (e.g., SPY or QQQ ) to extract relative strength insights.
Set upper and lower thresholds around ±5% for spotting major volatility days.
Conclusion
The Rolling Log Returns indicator transforms raw price action into a statistically sound return series—equipping traders with a professional-grade lens into market behavior. Whether you're conducting exploratory data analysis, building factor models, or visually scanning for outliers, this indicator integrates seamlessly into a modern quant's toolbox.
BB + RSI & Volume FilterThis script overlays three sets of technical filters on your price chart and generates signals when conditions align:
Bollinger Bands
Calculates upper, middle, and lower bands using either SMA or EMA.
Buy signal when price crosses up through the lower band.
Sell signal when price crosses down through the upper band.
Volume Filter
Computes a simple moving average of volume.
Ensures breakout moves have sufficient volume by requiring current volume > SMA(volume) × multiplier.
RSI Filter
Computes RSI on the chosen source.
Buy when RSI crosses above the oversold threshold.
Sell when RSI crosses below the overbought threshold.
Only plots RSI signals that pass the volume filter.
You get:
Bollinger entry/exit shapes (labeled “BB ↑/↓”).
RSI entry/exit shapes (labeled “RSI”) only when volume confirms the move.
Alerts for each signal type.
This combination reduces false breakouts by requiring both volatility (Bollinger) or momentum (RSI) and volume confirmation
RSI-BBGun-v6.1RSI BB Gun – Operator's Guide
“Eyes on target. Wait for the right moment. Then strike.”
________________________________________
🎯 Mission Objective
RSI BB Gun identifies extreme market conditions using RSI and Bollinger Bands, then overlays trend and volatility intelligence so you know when the setup is real.
The ❌ is your target acquisition signal—price just moved from an extreme zone back into play. Now you’ve got a clean radar lock.
________________________________________
📡 How to Operate
🟣 Step 1: Watch for the ❌'s (Black X = RSI & Bollinger Band Extremes Encountered)
• The Purple X means price and RSI are both stretched—and just snapped back into range.
• The target is now in the cross hairs and potentially ready for engagement.
🟥 Step 2: Confirm the Trend
• The thick ribbon tells you if the trend is with you:
o 🟢 Green = Uptrend. Focus on long setups.
o 🔴 Red = Downtrend. Focus on puts or short plays.
• Align with trend. Only engage when the field favors your position.
🔺 Step 3: Evaluate Signal Context
• Green Triangles = price just crossed below lower Bollinger Band (oversold).
• Red Triangles = price crossed above upper Band (overbought).
• Horizontal Lines Disappeared = The bar after the green or red horizontal line disappears means its time. We patiently wait for this as it means the momentum may be changing.
• These are your early indicators—they scout the setup on the GO / NO GO DECISION.
• ❌ + triangle + trend = clean shot.
________________________________________
☁️ Avoid These Situations
• ❌ in a choppy/no-trend zone = false alarm. Don’t engage.
• Repeated black ❌s without a purple ❌confirmation = low conviction. Let it go.
________________________________________
________________________________________
🪖 Operator's Mindset
“You don’t chase trades. You stalk them. When the ❌ flashes, the system has found a target. What you do next is up to your discipline, your tools, and your plan.”
________________________________________
Note: This is a free version. Upcoming paid version includes multi-timeframes working together. Multiple strategies. Volatility meter. Make money and master the BB Gun so that you can elevate to the Snipers weapon.
🔒 Want More Firepower?
Upgraded version coming soon. Unlocks next-gen targeting tools:
• Multi-timeframe RSI intelligence in a live dashboard
• Precision-timed combo signals based on layered volatility + RSI logic
• Advanced trend filters, trade zone overlays, and sniper-level entry indicators
• Ideal for swing traders and options strategists who want clarity under pressure
💥 Budget-friendly. No subscription. Upgrade when you're ready to go Pro.
Tip: Make 4+ trades mastering this setup. Then use a small portion of the trades to gain more features. Always be in a position you cannot lose.
🆚 Why This Beats Standard RSI/BB Tools
Mission Feature Basic Indicators RSI Ribbon Lite
Trend Confirmation ❌ ✅ Ribbon Overlay
Multi-Timeframe Awareness ❌ ✅ 5-Timeframe RSI Grid
Volatility Confirmation ❌ ✅ Weighted ATR Scoring
Combo Signal Alerts ❌ ✅ ❌ Reentry Combo Alerts
TradingView Alerts ❌ ✅ Built-In Radar Ping
#rsi #bb #bollingerbands #hull ma #trend
ATR Stop-Loss with Fibonacci Take-Profit [jpkxyz]ATR Stop-Loss with Fibonacci Take-Profit Indicator
This comprehensive indicator combines Average True Range (ATR) volatility analysis with Fibonacci extensions to create dynamic stop-loss and take-profit levels. It's designed to help traders set precise risk management levels and profit targets based on market volatility and mathematical ratios.
Two Operating Modes
Default Mode (Rolling Levels)
In default mode, the indicator continuously plots evolving stop-loss and take-profit levels based on real-time price action. These levels update dynamically as new bars form, creating rolling horizontal lines across the chart. I use this mode primarily to plot the rolling ATR-Level which I use to trail my Stop-Loss into profit.
Characteristics:
Levels recalculate with each new bar
All selected Fibonacci levels display simultaneously
Uses plot() functions with trackprice=true for price tracking
Custom Anchor Mode (Fixed Levels)
This is the primary mode for precision trading. You select a specific timestamp (typically your entry bar), and the indicator locks all calculations to that exact moment, creating fixed horizontal lines that represent your actual trade levels.
Characteristics:
Entry line (blue) marks your anchor point
Stop-loss calculated using ATR from the anchor bar
Fibonacci levels projected from entry-to-stop distance
Lines terminate when price breaks through them
Includes comprehensive alert system
Core Calculation Logic
ATR Stop-Loss Calculation:
Stop Loss = Entry Price ± (ATR × Multiplier)
Long positions: SL = Entry - (ATR × Multiplier)
Short positions: SL = Entry + (ATR × Multiplier)
ATR uses your chosen smoothing method (RMA, SMA, EMA, or WMA)
Default multiplier is 1.5, adjustable to your risk tolerance
Fibonacci Take-Profit Projection:
The distance from entry to stop-loss becomes the base unit (1.0) for Fibonacci extensions:
TP Level = Entry + (Entry-to-SL Distance × Fibonacci Ratio)
Available Fibonacci Levels:
Conservative: 0.618, 1.0, 1.618
Extended: 2.618, 3.618, 4.618
Complete range: 0.0 to 4.764 (23 levels total)
Multi-Timeframe Functionality
One of the indicator's most powerful features is timeframe flexibility. You can analyze on one timeframe while using stop-loss and take-profit calculations from another.
Best Practices:
Identify your entry point on execution timeframe
Enable "Custom Anchor" mode
Set anchor timestamp to your entry bar
Select appropriate analysis timeframe
Choose relevant Fibonacci levels
Enable alerts for automated notifications
Example Scenario:
Analyse trend on 4-hour chart
Execute entry on 5-minute chart for precision
Set custom anchor to your 5-minute entry bar
Configure timeframe setting to "4h" for swing-level targets
Select appropriate Fibonacci Extension levels
Result: Precise entry with larger timeframe risk management
Visual Intelligence System
Line Behaviour in Custom Anchor Mode:
Active levels: Lines extend to the right edge
Hit levels: Lines terminate at the breaking bar
Entry line: Always visible in blue
Stop-loss: Red line, terminates when hit
Take-profits: Green lines (1.618 level in gold for emphasis)
Customisation Options:
Line width (1-4 pixels)
Show/hide individual Fibonacci levels
ATR length and smoothing method
ATR multiplier for stop-loss distance
ALIP FX Smart Scalper – Precision for 1-Min TradersALIP FX Smart Scalper – Precision for 1-Min Traders
Looking for a powerful and clean scalping tool built for the 1-minute chart?
This indicator is engineered for serious scalpers who demand high accuracy, zero repaint, and trend-aligned signals.
✅ Key Features:
🔹 Trend-based filtering (EMA logic)
🔹 RSI + ATR + Slope conditions
🔹 No repaint – signals appear only on closed candles
🔹 Buy & Sell alerts with label and audio
🔹 Works best on BTC, NAS100, Gold (1m/5m TF)
💡 Why It Works:
The ALIP FX Smart Scalper ignores weak noise signals and only highlights clean trend-following opportunities.
Perfect for traders who want fast decisions with logic, not luck.
📌 Live test it now on TradingView
🔗
📥 More tools & education: t.me
🔻 Powered by: ALIP FX
"Success Elevated. Trade Smarter."
#ALIPFX #ScalpingIndicator #NoRepaint #TradingTools #SmartScalper #BTCUSD #NASDAQ100 #Gold
+ ATR Table and BracketsHi, all. I'm back with a new indicator—one I firmly believe could be one of the most valuable indicators you keep in your indicator toolshed—based around true range.
This is a simple, streamlined indicator utilizing true range and average true range that will help any trader with stoploss, trailing stoploss, and take-profit placement—things that I know many traders use average true range for. It could also be useful for trade entries as well, depending on the trader's style.
Typically, most traders (or at least what I've seen recommended across websites, video tutorials on YouTube, etc.) are taught to simply take the ATR number and use that, and possibly some sort of multiplier, as your stoploss and take-profit. This is fine, but I thought that it might be possible to dive a bit deeper into these values. Because an average is a combination of values, some higher, some lower, and we often see ATR spikes during periods of high volatility, I thought wouldn't it be useful to know what value those ATR spikes are, and how do they relate to the ATR? Then I thought to myself, well, what about the most volatile candle within that ATR (the candle with the greatest true range)? Couldn't knowing that value be useful to a trader? So then the idea of a table displaying these values, along with the ATR and the ATR times some multiplier number, would be a useful, simple way to display this information. That's what we have here.
The table is made up of two columns, one with the name of the metric being measured, and the other with its value. That's it. Simple.
As nice as this was, I thought an additional, great, and perhaps better, way to visualize this information would be in the form of brackets extending from the current bar. These are simply lines/labels plotted at the price values of the ATR, ATR times X, highest ATR, highest ATR times X, and highest TR value. These labels supply the actual values of the ATR, etc., but may also display the price if you should choose (both of these values are toggleable in the 'Inputs' section of the indicator.). Additionally, you can choose to display none of these labels, or all five if you wish (leaves the chart a bit cluttered, as shown in the image below), though I suspect you'll determine your preferences for which information you'd like to see and which not.
Chart with all five lines/labels displayed. I adjusted the ATRX value to 3 just to make the screenshot as legible as possible. Default is set to 1.5. As you can see, the label doesn't show the multiplier number, but the table does.
Here's a screenshot of the labels showing the price in addition to the value of the ATR, set to "Previous Closing Price," (see next paragraph for what that means) and highest TR. Personally, I don't see the value in the displaying the price, but I thought some people might want that. It's not available in the table as of now, but perhaps if I get enough requests for it I will add it.
That's basically it, but one last detail I need to go over is the dropdown box labeled "Bar Value ATR Levels are Oriented To." Firstly, this has no effect on Highest ATR, Highest ATRX, and Highest TR levels. Those are based on the ATR up to the last closed candle, meaning they aren't including the value of the currently open candle (this would be useless). However, knowing that different traders trade different ways it seemed to me prudent to allow for traders to select which opening or closing value the trader wishes to have the ATR brackets based on. For example, as someone who has consumed much No Nonsense Forex content I know that traders are urged to enter their trades in the last fifteen minutes of the trading day because the ATR is unlikely to change significantly in that period (ATR being the centerpiece of NNFX money management), so one of three selections here is to plot the brackets based on the ATR's inclusion of this value (this of course means the brackets will move while the candle is still open). The other options are to set the brackets to the current opening price, or the previous closing price. Depending on what you're trading many times these prices are virtually identical, but sometimes price gaps (stocks in particular), so, wanting your brackets placed relative to the previous close as opposed to the current open might be preferable for some traders.
And that's it. I really hope you guys like this indicator. I haven't seen anything closely similar to it on TradingView, and I think it will be something you all will find incredibly handy.
Please enjoy!
Bollinger Band + RSI Strategy ScannerVrushaNilansh Indicator for 15min. Trading Based on Bollinger Bands+RSI
Omori Law Recovery PhasesWhat is the Omori Law?
Originally a seismological model, the Omori Law describes how earthquake aftershocks decay over time. It follows a power law relationship: the frequency of aftershocks decreases roughly proportionally to 1/(t+c)^p, where:
t = time since the main shock
c = time offset constant
p = power law exponent (typically around 1.0)
Application to the markets
Financial markets experience "aftershocks" similar to earthquakes:
Market Crashes as Main Shocks: Major market declines (crashes) represent the initial shock event.
Volatility Decay: After a crash, market volatility typically declines following a power law pattern rather than a linear or exponential one.
Behavioral Components: The decay pattern reflects collective market psychology - initial panic gives way to uncertainty, then stabilization, and finally normalization.
The Four Recovery Phases
The Omori decay pattern in markets can be divided into distinct phases:
Acute Phase: Immediately after the crash, characterized by extreme volatility, panic selling, and sharp reversals. Trading is hazardous.
Reaction Phase: Volatility begins decreasing, but markets test previous levels. False rallies and retests of lows are common.
Repair Phase: Structure returns to the market. Volatility approaches normal levels, and traditional technical analysis becomes more reliable.
Recovery Phase: The final stage where market behavior normalizes completely. The impact of the original shock has fully decayed.
Why It Matters for Traders
Understanding where the market stands in this recovery cycle provides valuable context:
Risk Management: Adjust position sizing based on the current phase
Strategy Selection: Different strategies work in different phases
Psychological Preparation: Know what to expect based on the phase
Time Horizon Guidance: Each phase suggests appropriate time frames for trading
ATRWhat the Indicator Shows:
A compact table with four cells is displayed in the bottom-left corner of the chart:
| ATR | % | Level | Lvl+ATR |
Explanation of the Columns:
ATR — The averaged daily range (volatility) calculated with filtering of abnormal bars (extremely large or small daily candles are ignored).
% — The percentage of the daily ATR that the price has already covered today (the difference between the daily Open and Close relative to ATR).
Level — A custom user-defined level set through the indicator settings.
Lvl+ATR — The sum of the daily ATR and the user-defined level. This can be used, for example, as a target or stop-loss reference.
Color Highlighting of the "%" Cell:
The background color of the "%" ATR cell changes depending on the value:
✅ If the value is less than 10% — the cell is green (market is calm, small movement).
➖ If the value is between 10% and 50% — no highlighting (average movement, no signal).
🟡 If the value is between 50% and 70% — the cell is yellow (movement is increasing, be alert).
🔴 If the value is above 70% — the cell is red (the market is actively moving, high volatility).
Key Features:
✔ All ATR calculations and percentage progress are performed strictly based on daily data, regardless of the chart's current timeframe.
✔ The indicator is ideal for intraday traders who want to monitor daily volatility levels.
✔ The table always displays up-to-date information for quick decision-making.
✔ Filtering of abnormal bars makes ATR more stable and objective.
What is Adaptive ATR in this Indicator:
Instead of the classic ATR, which simply averages the true range, this indicator uses a custom algorithm:
✅ It analyzes daily bars over the past 100 days.
✅ Calculates the range High - Low for each bar.
✅ If the bar's range deviates too much from the average (more than 1.8 times higher or lower), the bar is considered abnormal and ignored.
✅ Only "normal" bars are included in the calculation.
✅ The average range of these normal bars is the adaptive ATR.
Detailed Algorithm of the getAdaptiveATR() Function:
The function takes the number of bars to include in the calculation (for example, 5):
The average of the last 5 normal bars is calculated.
pinescript
Копировать
Редактировать
adaptiveATR = getAdaptiveATR(5)
Step-by-Step Process:
An empty array ranges is created to store the ranges.
Daily bars with indices from 1 to 100 are iterated over.
For each bar:
🔹 The daily High and Low with the required offset are loaded via request.security().
🔹 The range High - Low is calculated.
🔹 The temporary average range of the current array is calculated.
🔹 The bar is checked for abnormality (too large or too small).
🔹 If the bar is normal or it's the first bar — its range is added to the array.
Once the array accumulates the required number of bars (count), their average is calculated — this is the adaptive ATR.
If it's not possible to accumulate the required number of bars — na is returned.
Что показывает индикатор:
На графике внизу слева отображается компактная таблица из четырех ячеек:
ATR % Уровень Ур+ATR
Пояснения к столбцам:
ATR — усреднённый дневной диапазон (волатильность), рассчитанный с фильтрацией аномальных баров (слишком большие или маленькие дневные свечи игнорируются).
% — процент дневного ATR, который уже "прошла" цена на текущий день (разница между открытием и закрытием относительно ATR).
Уровень — пользовательский уровень, который задаётся вручную через настройки индикатора.
Ур+ATR — сумма уровня и дневного ATR. Может использоваться, например, как ориентир для целей или стопов.
Цветовая подсветка ячейки "%":
Цвет фона ячейки с процентом ATR меняется в зависимости от значения:
✅ Если значение меньше 10% — ячейка зелёная (рынок пока спокоен, маленькое движение).
➖ Если значение от 10% до 50% — фон не подсвечивается (среднее движение, нет сигнала).
🟡 Если значение от 50% до 70% — ячейка жёлтая (движение усиливается, повышенное внимание).
🔴 Если значение выше 70% — ячейка красная (рынок активно движется, высокая волатильность).
Особенности работы:
✔ Все расчёты ATR и процентного прохождения производятся исключительно по дневным данным, независимо от текущего таймфрейма графика.
✔ Индикатор подходит для трейдеров, которые торгуют внутри дня, но хотят ориентироваться на дневные уровни волатильности.
✔ В таблице всегда отображается актуальная информация для принятия быстрых торговых решений.
✔ Фильтрация аномальных баров делает ATR более устойчивым и объективным.
Что такое адаптивный ATR в этом индикаторе
Вместо классического ATR, который просто усредняет истинный диапазон, здесь используется собственный алгоритм:
✅ Он берет дневные бары за последние 100 дней.
✅ Для каждого из них рассчитывает диапазон High - Low.
✅ Если диапазон бара слишком сильно отличается от среднего (более чем в 1.8 раза больше или меньше), бар считается аномальным и игнорируется.
✅ Только нормальные бары попадают в расчёт.
✅ В итоге считается среднее из диапазонов этих нормальных баров — это и есть адаптивный ATR.
Подробный алгоритм функции getAdaptiveATR()
Функция принимает количество баров для расчёта (например, 5):
Считается 5 последних нормальных баров
pinescript
Копировать
Редактировать
adaptiveATR = getAdaptiveATR(5)
Пошагово:
Создаётся пустой массив ranges для хранения диапазонов.
Перебираются дневные бары с индексами от 1 до 100.
Для каждого бара:
🔹 Через request.security() подгружаются дневные High и Low с нужным смещением.
🔹 Считается диапазон High - Low.
🔹 Считается временное среднее диапазона по текущему массиву.
🔹 Проверяется, не является ли бар аномальным (слишком большой или маленький).
🔹 Если бар нормальный или это самый первый бар — его диапазон добавляется в массив.
Как только массив набирает заданное количество баров (count), берётся их среднее значение — это и есть адаптивный ATR.
Если не удалось набрать нужное количество баров — возвращается na.
Candle Pattern Detector By Prashanth
Bullish Signal (🟢 below candle):
Plotted when any of the following occur:
✅ Bullish Engulfing
✅ Bullish Three-Line Strike
✅ Bottom wick ≥ % threshold (default: 80%)
Bearish Signal (🔴 above candle):
Plotted when any of the following occur:
❌ Bearish Engulfing
❌ Bearish Three-Line Strike
❌ Top wick ≥ % threshold (default: 80%)
Only one signal per candle (🟢 or 🔴)
If both bullish and bearish conditions happen on same candle → no signal
Helps simplify visual clutter while scanning for strong candle patterns
KosATRWhat this Pine Script does:
✅ This indicator displays daily ATR (Average True Range) information on any chart timeframe (minutes, hours, etc.), ensuring the calculations are based strictly on daily price data.
Displayed Information in the Table:
The script creates a table in the bottom-left corner of the chart that shows:
ATR — A custom, filtered version of the daily ATR that excludes abnormal price bars (extremely large or small daily ranges).
% — The percentage of the ATR that today's price movement (Open to Close) has covered so far.
Level — A manually defined fixed level, set through the script's input.
Level + ATR — The sum of the daily ATR and your defined level, useful for setting price targets or alerts.
Key Features:
Uses request.security() to ensure all calculations (high, low, open, close) are taken from the daily timeframe, even when you're viewing lower or higher timeframes.
Implements a filtering method to calculate an "adaptive ATR," ignoring price ranges that are too large or too small (outliers), making the ATR value more stable and realistic.
Displays a live, easy-to-read table directly on the chart for quick reference during trading.
Summary:
This script provides traders with reliable, daily-based ATR data, helping assess current price movement strength relative to historical daily volatility. It's especially useful for intraday traders who want constant awareness of daily ATR levels, regardless of their current chart timeframe.
Intra-bar Close/Open Gap [YuL]Just checking one idea: look at gaps between close and open bars on lower timeframe to try to estimate how much slippage exists there that may be a result of buying or selling pressure.
Perhaps it only useful in real time to see if situation of the current bar is changing.
Open to ideas and suggestions.
Adaptive Squeeze Momentum +OVERVIEW
Adaptive Squeeze Momentum+ is an enhanced, auto-adaptive momentum indicator inspired by the classic Squeeze Momentum concept. This script dynamically adjusts its parameters to any timeframe without requiring manual inputs, making it a versatile tool for intraday traders and long-term investors alike.
CONCEPTS
The indicator combines Bollinger Bands (BB) and Keltner Channels (KC) to identify volatility compression ("squeeze") and expansion phases. When BB contracts within KC, a squeeze is detected, signaling reduced volatility and potential for a breakout. Additionally, a linear regression momentum calculation helps assess the strength and direction of price moves.
FEATURES
Auto-Adaptation:
Automatically adjusts BB/KC lengths and multipliers based on the chart timeframe (from 1 minute to 1 month).
Dynamic Squeeze Detection:
Clear visual encoding of squeeze status:
- Gray cross: neutral
- Blue cross: squeeze active
- Yellow cross: squeeze released
Momentum Histogram:
Colored area chart shows positive and negative momentum with slope-based coloring.
Clean Visualization:
Minimalist plots focused on actionable signals.
USAGE
Identify Squeeze Phases:
When the blue cross appears, the market is in a volatility squeeze, potentially preceding a breakout.
Monitor Momentum Direction:
The area plot shows the magnitude and direction of price momentum.
Confirm Entries and Exits:
Combine squeeze releases (yellow) with positive momentum for potential long entries or negative momentum for shorts.
Adaptable to Any Market:
Works seamlessly across cryptocurrencies, stocks, forex, and indices on all timeframes.
Shavarie's Sniper LineShavarie’s Sniper Line is a precision confirmation tool built for high-quality entries — not noisy signals.
It activates only when all 3 conditions agree:
🔁 Momentum bend detection
💧 Money Flow Index (MFI) pressure
🔺 Delta volume strength (emulated from price/volume flow)
When all conditions align, the Sniper Line shifts to:
+1 for potential buy zone
-1 for potential sell zone
0 when neutral — no action
Best used in combination with supply/demand zones, Heikin Ashi, or larger trend structures. Built for traders who value patience, precision, and massive R:R setups.
Relative Measured Volatility (RMV)RMV • Volume-Sensitive Consolidation Indicator
A lightweight Pine Script that highlights true low-volatility, low-volume bars in a single squeeze measure.
What it does
Calculates each bar’s raw High-Low range.
Down-weights bars where volume is below its 30-day average, emphasizing genuine quiet periods.
Normalizes the result over the prior 15 bars (excluding the current bar), scaling from 0 (tightest) to 100 (most volatile).
Draws the series as a step plot, shades true “tight” bars below the user threshold, and marks sustained squeezes with a small arrow.
Key inputs
Lookback (bars): Number of bars to use for normalization (default 15).
Tight Threshold: RMV value under which a bar is considered squeezed (default 15).
Volume SMA Period: Period for the volume moving average benchmark (default 30).
How it works
Raw range: barRange = high - low
Volume ratio: volRatio = min(volume / sma(volume,30), 1)
Weighted range: vwRange = barRange * volRatio
Rolling min/max (prior 15 bars): exclude today so a new low immediately registers a 0.
Normalize: rmv = clamp(100 * (vwRange - min) / (max - min), 0, 100)
Visualization & signals
Step line for exact bar-by-bar values.
Shaded background when RMV < threshold.
Consecutive-bar filter ensures arrows only appear when tightness lasts at least two bars, cutting noise.
Why use it
Quickly spot consolidation zones that combine narrow price action with genuine dry volume—ideal for swing entries ahead of breakouts.
Gabriel's Andean Oscillator📈 Gabriel's Andean Oscillator — Enhanced Trend-Momentum Hybrid
Gabriel's Andean Oscillator is a sophisticated trend-momentum indicator inspired by Alex Grover’s original Andean Oscillator concept. This enhanced version integrates multiple envelope types, smoothing options, and the ability to track volatility from both open/close and high/low dynamics—making it more responsive, adaptable, and visually intuitive.
🔍 What It Does
This oscillator measures bullish and bearish "energy" by calculating variance envelopes around price. Instead of traditional momentum formulas, it builds two exponential variance envelopes—one capturing the downside (bullish potential) and the other capturing the upside (bearish pressure). The result is a smoothed oscillator that reflects internal market tension and potential breakouts.
⚙️ Key Features
📐 Envelope Types:
Choose between:
"Regular" – Uses single EMA-based smoothing on open/close variance. Ideal for shorter timeframes.
"Double Smoothed" – Adds an extra layer of smoothing for noise reduction. Ideal for longer timeframes.
📊 Bullish & Bearish Components:
Bull = Measures potential upside using price lows (or open/close).
Bear = Measures downside pressure using highs (or open/close).
These can optionally be derived from high/low or open/close for flexible interpretation.
📏 Signal Line:
A customizable EMA of the dominant component to confirm momentum direction.
📉 Break Zone Area Plot:
An optional filled area showing when bull > bear or vice versa, useful for detecting expansion/contraction phases.
🟢 High/Low Overlay Option (Use Highs and Lows?):
Visualize secondary components derived from high/low prices to compare against the open/close dynamics and highlight volatility asymmetry.
🧠 How to Use It
Trend Confirmation:
When bull > bear and rising above signal → bullish bias.
When bear > bull and rising above signal → bearish bias.
Breakout Potential:
Watch the Break area plot (√(bull - bear)) for rapid expansion, signaling volatility bursts or directional moves.
High/Low Envelope Divergence:
Enabling the high/low comparison reveals hidden strength or weakness not visible in open/close alone.
🛠 Customizable Inputs
Envelope Type: Regular vs. Double Smoothed
EMA Envelope Lengths: For both regular and smoothed logic
Signal Length: Controls EMA smoothing for the signal
Use Highs and Lows?: Toggles second set of envelopes; the original doesn't include highs and lows.
Plot Breaks: Enables the filled “break” zone area, the squared difference between Open and Close.
🧪 Based On:
Andean Oscillator - Alpaca Markets
Licensed under CC BY-NC-SA 4.0
Developed by Gabriel, based on the work of Alex Grover
Info TablesThis indicator provides two clear tables showing key market metrics, helping you make sense of price action. Each metric is chosen to give you practical insights, and you can customize the display to fit your needs.
## Key Features and Why Metrics Matter
### Main Table Metrics
- **ML-Predicted Price**:
- **What**: A price forecast based on a machine learning model using past price, volume, and RSI data.
- **Why**: Shows where the market might head, helping you gauge if the current price is too high or low compared to the prediction. Useful for spotting potential reversals or continuations.
- **Deviation %**:
- **What**: The percentage difference between the current price and the predicted price.
- **Why**: Tells you how far the market is straying from the ML forecast. A large deviation might suggest overbought/oversold conditions or a trend shift.
- **VWAP Deviation %**:
- **What**: The percentage difference between the current price and the Volume Weighted Average Price (VWAP).
- **Why**: VWAP is a benchmark for fair price; deviation shows if the market is stretched above or below this level, aiding entries or exits.
- **FRED UNRATE % Change**:
- **What**: The percentage change in the U.S. unemployment rate from FRED data.
- **Why**: Offers macro context. Rising unemployment can signal economic weakness, impacting market sentiment, while falling rates may boost confidence.
- **Open Interest**:
- **What**: The total number of open futures contracts for MESM2.
- **Why**: High open interest indicates strong market participation, often tied to liquidity and conviction. Low levels might suggest indecision or lack of commitment.
- **COT Commercial Long/Short**:
- **What**: Commitment of Traders (COT) data showing commercial traders’ long and short positions.
- **Why**: Reveals how big players (hedgers) are positioned. More longs than shorts can hint at bullish sentiment, while more shorts suggest bearish views.
### New Metrics Table
- **QQE Bias**:
- **What**: A momentum indicator based on a smoothed RSI with trailing stops.
- **Why**: Highlights bullish (green) or bearish (red) momentum, helping you confirm short-term trade directions or avoid choppy markets (gray).
- **Volume Momentum**:
- **What**: A score (1–20) comparing current volume to past volume over a lookback period.
- **Why**: High scores indicate strong buying/selling pressure, signaling potential breakouts or reversals. Low scores suggest weak participation.
- **ATR Volatility**:
- **What**: A score (1–20) based on the Average True Range, measuring price volatility.
- **Why**: High volatility warns of larger price swings, useful for setting stop-losses or avoiding trades in choppy conditions. Low volatility may indicate consolidation.
- **ADX Trend**:
- **What**: The Average Directional Index, measuring trend strength.
- **Why**: High ADX values confirm strong trends, guiding you to trade with the trend. Low values suggest range-bound markets, better for mean-reversion strategies.
- **RSI**:
- **What**: Relative Strength Index, showing overbought (>70) or oversold (<30) conditions.
- **Why**: Helps identify potential reversal points or confirm momentum. Useful for timing entries in overextended markets.
- **Frahm Volatility**:
- **What**: A score (1–20) based on true range over a time window (e.g., 24 hours).
- **Why**: Measures short-term volatility, helping you adjust position sizes or avoid trading during erratic price moves.
- **Frahm Avg Candle (Ticks)**:
- **What**: The average candle size in ticks over the same time window.
- **Why**: Indicates typical price movement, useful for setting realistic profit targets or stop-losses based on recent market behavior.
### Additional Features
- **Plotted Predicted Price**:
- **What**: An optional line showing the ML-predicted price on the chart.
- **Why**: Lets you visually compare the predicted price to actual price action, making it easier to spot divergence or alignment.
- **Custom Gradient Colors**:
- **What**: User-defined colors for high/low values in both tables.
- **Why**: Makes it quick to see which metrics are at extremes (e.g., high deviation or strong ADX), improving decision-making under pressure.
- **Alerts**:
- **What**: Notifications for high/low Frahm volatility and bullish/bearish QQE Bias.
- **Why**: Keeps you informed of critical changes (e.g., volatility spikes or momentum shifts) without needing to watch the chart constantly.
## Customization Options
- **ML Matrix Inputs**:
- Adjust the **ML Lookback Period** (e.g., 200–300 for volatile markets, 1000 for trends) to control how much history the ML model uses.
- Set the **ML RSI Period** (e.g., 7–10 for fast markets, 20 for calm) to tweak the RSI’s sensitivity in the prediction.
- **Plot Settings**:
- Toggle the predicted price line and choose its color (default blue) for clear visibility.
- **Table Settings**:
- Position tables (top/bottom, left/center/right) and show/hide them to focus on what matters.
- **Gradient Color Settings**:
- Pick colors for high/low values in each table to match your chart or preferences.
- **Timeframe & Thresholds**:
- Set specific timeframes (e.g., 5-minute for smoother data) and thresholds (e.g., tighter deviation ranges) for each metric to suit your trading style.
## Ideal Use Case
This indicator is perfect for MESM2 traders navigating fast-moving markets. The Main Table gives you a big-picture view (predicted price, macro data, and positioning), while the New Metrics Table zooms in on momentum and volatility, ideal for scalping or trend trades. Use it to confirm entries, set stops, or avoid choppy periods.
## Why It’s Valuable
The **ML Matrix - Tables Only** puts essential data at your fingertips. Each metric is selected to answer a specific question—Is the price overextended? Is momentum building? Are big players bullish? Are conditions too volatile?—helping you trade with clarity and confidence, whether you’re catching quick moves or riding longer trends.
TICK ±1200 Intrabar MarkerMarks +1100 and -1200 NYSE TICK readings on any chart. Useful for TICK fades without having to look at the actual USI:TICK chart.
Simple Market Kill-Zones + Open (UTC)What it does
This Pine v6 indicator highlights the “kill-zones” around the big session opens—Asian (23:00–03:00 UTC), London (07:00–09:00 UTC) and New York (13:30–15:30 UTC)—by reading each bar’s actual UTC timestamp. It also draws dashed vertical lines at exactly 23:00, 07:00 and 13:30 UTC, so you never miss the liquidity ramps. Because it uses raw UTC hours/minutes, it stays accurate even when exchanges pause (e.g. Nano-BTC’s daily halt) or your chart’s display timezone changes.
Key Inputs
Show Asia/London/NY Kill Zone – toggle each shaded band on/off
Zone Colors – pick your own semi-transparent hues
Show Session-Open Lines – enable dashed verticals at the exact open times
Line Colors – customize the line opacity and style
How to use
Apply on your favorite timeframe (15 min–1 h is a sweet spot).
Toggle the zones you care about and pick readable colors.
Use the dashed lines as entry triggers or as visual bookmarks.
In your own Pine strategies, wrap order logic with the zone booleans to only trade when liquidity’s alive.
LaCrazy Smash CandleLaCrazy Smash Candle highlights powerful engulfing candles that signal potential momentum reversals or breakout continuation.
Smash Long: The candle's low touches or dips below the prior candle's low, then closes above the previous high with a strong body (minimum % of the candle range).
Smash Short: The candle's high touches or exceeds the prior high, then closes below the previous low with a strong body.
These “Smash” moves often occur at key pivot points, signaling decisive rejections or trend continuation. Customize the body strength filter to match your strategy needs.
Price Extension from 8 EMAOverview
This indicator can be used to see how far away the price is from the 8 EMA. It compares this to the Average Daily Range % to see if the stock may be overextended. The "Extension Multiplier" represents how far the stock is extended away from the 8 EMA.
Core Concept
This indicator is best used for breakout trades that are trying to make sure they are not chasing the stock.
How to Use This Indicator
This tool is primarily intended for analyzing daily charts of individual stocks and is often used by breakout traders to evaluate potential entry areas.
If the stock is far away from the 8 EMA, it is likely not ready to break out. If it is close to the 8ema, it could be ready to move higher.
This indicator can also be used in the opposite way. For example, shorting or puts.
Understanding the colors
Green (Not Extended): Indicates the price is close to the 8 EMA. This often corresponds to periods of consolidation.
Yellow (Slightly Extended): The price is beginning to move away from the 8 EMA.
Orange (Extended): The price has moved a considerable distance from the 8 EMA.
Red (Very Extended): The price is at an extreme distance from the 8 EMA, historically increasing the likelihood of a pullback or consolidation.
Settings
Info Row Position: Adjusts the vertical position of the display table on the chart. Useful when using other indicators.
ADR Length: Sets the lookback period for calculating the Average Daily Range. Or the average range % for different timeframes.
Timeframe: Determines the timeframe for the EMA and ADR calculation (the default is Daily).