Machine Learning Key Levels [AlgoAlpha]🟠 OVERVIEW
This script plots Machine Learning Key Levels on your chart by detecting historical pivot points and grouping them using agglomerative clustering to highlight price levels with the most past reactions. It combines a pivot detection, hierarchical clustering logic, and an optional silhouette method to automatically select the optimal number of key levels, giving you an adaptive way to visualize price zones where activity concentrated over time.
🟠 CONCEPTS
Agglomerative clustering is a bottom-up method that starts by treating each pivot as its own cluster, then repeatedly merges the two closest clusters based on the average distance between their members until only the desired number of clusters remain. This process creates a hierarchy of groupings that can flexibly describe patterns in how price reacts around certain levels. This offers an advantage over K-means clustering, since the number of clusters does not need to be predefined. In this script, it uses an average linkage approach, where distance between clusters is computed as the average pairwise distance of all contained points.
The script finds pivot highs and lows over a set lookback period and saves them in a buffer controlled by the Pivot Memory setting. When there are at least two pivots, it groups them using agglomerative clustering: it starts with each pivot as its own group and keeps merging the closest pairs based on their average distance until the desired number of clusters is left. This number can be fixed or chosen automatically with the silhouette method, which checks how well each point fits in its cluster compared to others (higher scores mean cleaner separation). Once clustering finishes, the script takes the average price of each cluster to create key levels, sorts them, and draws horizontal lines with labels and colors showing their strength. A metrics table can also display details about the clusters to help you understand how the levels were calculated.
🟠 FEATURES
Agglomerative clustering engine with average linkage to merge pivots into level groups.
Dynamic lines showing each cluster’s price level for clarity.
Labels indicating level strength either as percent of all pivots or raw counts.
A metrics table displaying pivot count, cluster count, silhouette score, and average pivots per cluster.
Optional silhouette-based auto-selection of cluster count to adaptively find the best fit.
🟠 USAGE
Add the indicator to any chart. Choose how far back to detect pivots using Pivot Length and set Pivot Memory to control how many are kept for clustering (more pivots give smoother levels but can slow performance). If you want the script to pick the number of levels automatically, enable Auto No. Levels ; otherwise, set Number of Levels . The colored horizontal lines represent the calculated key levels, and circles show where pivots occurred colored by which cluster they belong to. The labels beside each level indicate its strength, so you can see which levels are supported by more pivots. If Show Metrics Table is enabled, you will see statistics about the clustering in the corner you selected. Use this tool to spot areas where price often reacts and to plan entries or exits around levels that have been significant over time. Adjust settings to better match volatility and history depth of your instrument.
波動率
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.
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.
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
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.
+ 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!
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
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
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
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
Unified ATR LevelsThis is a unified ATR-based band plotting indicator.
It allows you to display:
Default ATR (on current timeframe)
Preset ATR (mapped to higher timeframe logic)
User-defined ATR (on any custom timeframe)
✳️ Features:
Configurable multipliers, colors, and line widths
Smart label positioning (left, middle, right)
Clean visuals with adjustable label size
Ideal for multi-timeframe analysis and volatility zones
📌 All feedback welcome!
Tags:
volatility, ATR, multi-timeframe, support-and-resistance, custom-indicator
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).
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.
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.
Bollinger Band + RSI Strategy ScannerVrushaNilansh Indicator for 15min. Trading Based on Bollinger Bands+RSI
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.
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.
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
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.
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.
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.
Frahm Factor Position Size CalculatorThe Frahm Factor Position Size Calculator is a powerful evolution of the original Frahm Factor script, leveraging its volatility analysis to dynamically adjust trading risk. This Pine Script for TradingView uses the Frahm Factor’s volatility score (1-10) to set risk percentages (1.75% to 5%) for both Margin-Based and Equity-Based position sizing. A compact table on the main chart displays Risk per Trade, Frahm Factor, and Average Candle Size, making it an essential tool for traders aligning risk with market conditions.
Calculates a volatility score (1-10) using true range percentile rank over a customizable look-back window (default 24 hours).
Dynamically sets risk percentage based on volatility:
Low volatility (score ≤ 3): 5% risk for bolder trades.
High volatility (score ≥ 8): 1.75% risk for caution.
Medium volatility (score 4-7): Smoothly interpolated (e.g., 4 → 4.3%, 5 → 3.6%).
Adjustable sensitivity via Frahm Scale Multiplier (default 9) for tailored volatility response.
Position Sizing:
Margin-Based: Risk as a percentage of total margin (e.g., $175 for 1.75% of $10,000 at high volatility).
Equity-Based: Risk as a percentage of (equity - minimum balance) (e.g., $175 for 1.75% of ($15,000 - $5,000)).
Compact 1-3 row table shows:
Risk per Trade with Frahm score (e.g., “$175.00 (Frahm: 8)”).
Frahm Factor (e.g., “Frahm Factor: 8”).
Average Candle Size (e.g., “Avg Candle: 50 t”).
Toggles to show/hide Frahm Factor and Average Candle Size rows, with no empty backgrounds.
Four sizes: XL (18x7, large text), L (13x6, normal), M (9x5, small, default), S (8x4, tiny).
Repositionable (9 positions, default: top-right).
Customizable cell color, text color, and transparency.
Set Frahm Factor:
Frahm Window (hrs): Pick how far back to measure volatility (e.g., 24 hours). Shorter for fast markets, longer for chill ones.
Frahm Scale Multiplier: Set sensitivity (1-10, default 9). Higher makes the score jumpier; lower smooths it out.
Set Margin-Based:
Total Margin: Enter your account balance (e.g., $10,000). Risk auto-adjusts via Frahm Factor.
Set Equity-Based:
Total Equity: Enter your total account balance (e.g., $15,000).
Minimum Balance: Set to the lowest your account can go before liquidation (e.g., $5,000). Risk is based on the difference, auto-adjusted by Frahm Factor.
Customize Display:
Calculation Method: Pick Margin-Based or Equity-Based.
Table Position: Choose where the table sits (e.g., top_right).
Table Size: Select XL, L, M, or S (default M, small text).
Table Cell Color: Set background color (default blue).
Table Text Color: Set text color (default white).
Table Cell Transparency: Adjust transparency (0 = solid, 100 = invisible, default 80).
Show Frahm Factor & Show Avg Candle Size: Check to show these rows, uncheck to hide (default on).
Alpha Trader University - London Continuation StrategyAlpha Trader University - London Continuation Strategy Indicator
OVERVIEW:
This educational indicator implements the London Continuation Strategy, a session-based trading methodology that capitalizes on price continuation patterns between the Asia and London trading sessions. Designed to teach traders about session timing, market structure, and continuation strategies.
STRATEGY METHODOLOGY:
The London Continuation Strategy is based on the market principle that directional movements established during the Asia session often continue during the early London session, creating high-probability trading opportunities.
SESSION ANALYSIS FRAMEWORK:
1. ASIA SESSION (4:00-9:00 Dubai Time):
- Establishes initial market direction and sentiment
- Creates key support and resistance levels
- Provides the foundation for continuation bias
- Blue box visualization with range tracking
2. PRE-LONDON SESSION (9:00-11:00 Dubai Time):
- Transition period between major sessions
- Setup and preparation phase for London entries
- Confirmation or negation of Asia session bias
- Teal box visualization for monitoring
3. LONDON SESSION (11:00-12:00 Dubai Time):
- Primary entry window for continuation trades
- Highest probability period for strategy execution
- Green box labeled "Entry Window" for clear identification
- Optimal timing for trade execution
EDUCATIONAL VALUE:
- Learn session-based trading concepts and timing
- Understand market flow between major trading centers
- Develop skills in identifying continuation patterns
- Practice using session ranges for risk management
- Build foundation for advanced session strategies
TRADING APPLICATIONS:
- Entry Timing: Use London session start for optimal entry points
- Direction Bias: Follow Asia session directional momentum
- Risk Management: Utilize session ranges for stop-loss placement
- Target Setting: Project targets based on session volatility patterns
- Market Structure: Respect key session levels and range breaks
UNIQUE FEATURES:
- Dubai timezone optimization for Middle East traders
- Three-session comprehensive analysis framework
- Real-time session range tracking and visualization
- Customizable visual elements and colors
- Educational labels and clear entry window identification
TECHNICAL IMPLEMENTATION:
- Accurate timezone conversion (UTC to Dubai time)
- Dynamic session detection and range calculation
- Real-time box and label updates during active sessions
- Clean visual design with professional color coding
- Efficient memory management for optimal performance
CUSTOMIZATION OPTIONS:
- Session colors for personal preference
- Box border width adjustment
- Label size customization
- Visual element toggle capabilities
RISK MANAGEMENT INTEGRATION:
- Session range-based stop-loss guidance
- Volatility assessment through range analysis
- Clear entry and exit timing signals
- Structure-based risk parameter definition
This indicator transforms complex session analysis into a systematic, visual trading approach, helping traders understand market timing and develop disciplined continuation strategies.
EDUCATIONAL DISCLAIMER: This indicator is designed for educational purposes and strategy development. It should be used as part of a comprehensive trading plan with proper risk management. Past performance of any strategy does not guarantee future results. Always practice proper risk management and consider market conditions before trading.