(BUY-SELL)RSI with Bollinger BandsThis script for TradingView combines two popular technical analysis indicators - the Relative Strength Index (RSI) and Bollinger Bands - to identify when an asset's price may be overbought or oversold.
Here's how it works:
Input parameters:
rsiLength: the RSI calculation period (default is 14).
rsiOverbought: the overbought level of the RSI (default is 70).
rsiOversold: RSI oversold level (default is 30).
bbLength: Bollinger Bands calculation period (default is 20).
bbMult: standard deviation multiplier for Bollinger Bands (default is 2.0).
reducePyramiding: option to reduce pyramiding (off by default).
Indicator Calculation:
The script calculates RSI and Bollinger Bands using the built-in functions ta.rsi() and ta.bb().
Signal conditions:
Buy signal: generated when the RSI falls below the rsiOversold level and the closing price is below the lower Bollinger Band.
Sell signal: generated when the RSI rises above the rsiOverbought level and the closing price is above the upper Bollinger Band.
Pyramiding:
The script uses the buyCount and sellCount counters to track the number of consecutive buy and sell signals.
The maxTrades parameter defines the maximum number of trades in one direction (1 if reducePyramiding is enabled, and 3 otherwise).
Volatilité
Williams BBDiv Signal [trade_lexx]📈 Williams BBDiv Signal — Improve your trading strategy with accurate signals!
Introducing Williams BBDiv Signal , an advanced trading indicator designed for a comprehensive analysis of market conditions. This indicator combines Williams%R with Bollinger Bands, providing traders with a powerful tool for generating buy and sell signals, as well as detecting divergences. It is ideal for traders who need an advantage in detecting changing trends and market conditions.
🔍 How signals work
— A buy signal is generated when the Williams %R line crosses the lower Bollinger Bands band from bottom to top. This indicates that the market may be oversold and ready for a rebound. They are displayed as green triangles located under the Williams %R graph. On the main chart, buy signals are displayed as green triangles labeled "Buy" under candlesticks.
— A sell signal is generated when the Williams %R line crosses the upper Bollinger Bands band from top to bottom. This indicates that the market may be overbought and ready for a correction. They are displayed as red triangles located above the Williams %R chart. On the main chart, the sell signals are displayed as red triangles with the word "Sell" above the candlesticks.
— Minimum Bars Between Signals
The user can adjust the minimum number of bars between the signals to avoid false signals. This helps to filter out noise and improve signal quality.
— Mode "Wait for Opposite Signal"
In this mode, buy and sell signals are generated only after receiving the opposite signal. This adds an additional level of filtering and helps to avoid false alarms.
— Mode "Overbought and Oversold Zones"
A buy signal is generated only when Williams %R is below the -80 level (Lower Band). A sell signal is generated only when Williams %R is above -20 (Upper Band).
📊 Divergences
— Bullish divergence occurs when Williams%R shows a higher low while price shows a lower low. This indicates a possible upward reversal. They are displayed as green lines and labels labeled "Bull" on the Williams %R chart. On the main chart, bullish divergences are displayed as green triangles labeled "Bull" under candlesticks.
— A bearish divergence occurs when Williams %R shows a lower high, while the price shows a higher high. This indicates a possible downward reversal. They are displayed as red lines and labels labeled "Bear" on the Williams %R chart. On the main chart, bearish divergences are displayed as red triangles with the word "Bear" above the candlesticks.
— 🔌Connector Signal🔌 and 🔌Connector Divergence🔌
It allows you to connect the indicator to trading strategies and test signals throughout the trading history. This makes the indicator an even more powerful tool for traders who want to test the effectiveness of their strategies on historical data.
🔔 Alerts
The indicator provides the ability to set up alerts for buy and sell signals, as well as for divergences. This allows traders to keep abreast of important market developments without having to constantly monitor the chart.
🎨 Customizable Appearance
Customize the appearance of Williams BBDiv Signal according to your preferences to make the analysis more convenient and visually pleasing. In the indicator settings section, you can change the colors of the buy and sell signals, as well as divergences, so that they stand out on the chart and are easily visible.
🔧 How it works
— The indicator starts by calculating the Williams %R and Bollinger Bands values for a certain period to assess market conditions. Initial assumptions are introduced for overbought and oversold levels, as well as for the standard deviation of the Bollinger Bands. The indicator then analyzes these values to generate buy and sell signals. This classification helps to determine the appropriate level of volatility for signal calculation. As the market evolves, the indicator dynamically adjusts, providing information about the trend and volatility in real time.
Quick Guide to Using Williams BBDiv Signal
— Add the indicator to your favorites by clicking on the star icon. Adjust the parameters, such as the period length for Williams %R, the type of moving average and the standard deviation for Bollinger Bands, according to your trading style. Or leave all the default settings.
— Adjust the signal filters to improve the quality of the signals and avoid false alarms, adjust the filters in the "Signal Settings" section.
— Turn on alerts so that you don't miss important trading opportunities and don't constantly sit at the chart, set up alerts for buy and sell signals, as well as for divergences. This will allow you to keep abreast of all key market developments and respond to them in a timely manner, without being distracted from other business.
— Use signals. They will help you determine the optimal entry and exit points for your positions. Also, pay attention to bullish and bearish divergences, which may indicate possible market reversals and provide additional trading opportunities.
— Use the 🔌Connector🔌 for deeper analysis and verification of the effectiveness of signals, connect it to your trading strategies. This will allow you to test signals throughout the trading history and evaluate their accuracy based on historical data. Include the indicator in your trading strategy and run testing to see how buy and sell signals have worked in the past. Analyze the test results to determine how reliable the signals are and how they can improve your trading strategy. This will help you make better informed decisions and increase your trading efficiency.
Kalman Step Signals [AlgoAlpha]Take your trading to the next level with the Kalman Step Signals indicator by AlgoAlpha! This advanced tool combines the power of Kalman Filtering and the Supertrend indicator, offering a unique perspective on market trends and price movements. Designed for traders who seek clarity and precision in identifying trend shifts and potential trade entries, this indicator is packed with customizable features to suit your trading style.
Key Features
🔍 Kalman Filter Smoothing : Dynamically smooths price data with user-defined parameters for Alpha, Beta, and Period, optimizing responsiveness and trend clarity.
📊 Supertrend Overlay : Incorporates a classic Supertrend indicator to provide clear visual cues for trend direction and potential reversals.
🎨 Customizable Appearance : Adjust colors for bullish and bearish trends, along with optional exit bands for more nuanced analysis.
🔔 Smart Alerts : Detect key moments like trend changes or rejection entries for timely trading decisions.
📈 Advanced Visualization : Includes optional entry signals, exit bands, and rejection markers to pinpoint optimal trading opportunities.
How to Use
Add the Indicator : Add the script to your TradingView favorites. Customize inputs like Kalman parameters (Alpha, Beta, Period) and Supertrend settings (Factor, ATR Period) based on your trading strategy.
Interpret the Signals : Watch for trend direction changes using Supertrend lines and directional markers. Utilize rejection entries to identify price rejections at trendlines for precision entry points.
Set Alerts : Enable the built-in alert conditions for trend changes or rejection entries to act swiftly on trading opportunities without constant chart monitoring.
How It Works
The indicator leverages a Kalman Filter to smooth raw price data, balancing responsiveness and noise reduction using user-controlled parameters. This refined price data is then fed into a Supertrend calculation, combining ATR-based volatility analysis with dynamic upper and lower bands. The result is a clear and reliable trend-detection system. Additionally, it features rejection markers for bullish and bearish reversals when prices reject the trendline, along with exit bands to visualize potential price targets. The integration of customizable alerts ensures traders never miss critical market moves.
Add the Kalman Step Signals to your TradingView charts today and enjoy a smarter, more efficient trading experience! 🚀🌟
Dynamic Momentum Range Index (DMRI)//@version=5
indicator("Dynamic Momentum Range Index (DMRI)", shorttitle="DMRI", overlay=false)
// Inputs
n = input.int(14, title="Momentum Period", minval=1)
atrLength = input.int(14, title="ATR Length", minval=1)
maLength = input.int(20, title="Moving Average Length", minval=1)
// Calculations
pm = close - close // Price Momentum (PM)
atr = ta.atr(atrLength) // Average True Range (ATR)
va = pm / atr // Volatility Adjustment (VA)
// Moving Average and Dynamic Range Factor (DRF)
ma = ta.sma(close, maLength)
drf = math.abs(close - ma) / atr
// Dynamic Momentum Range Index (DMRI)
dmri = va * drf
// Normalization
maxVal = ta.highest(dmri, atrLength)
minVal = ta.lowest(dmri, atrLength)
dmriNormalized = (dmri - minVal) / (maxVal - minVal) * 100
// Zones for Interpretation
bullishZone = 70
bearishZone = 30
// Plotting DMRI
plot(dmriNormalized, title="DMRI", color=color.blue, linewidth=2)
hline(70, "Overbought", color=color.red)
hline(30, "Oversold", color=color.green)
hline(50, "Neutral", color=color.gray)
// Background Coloring
bgcolor(dmriNormalized > bullishZone ? color.new(color.green, 90) : na, title="Bullish Zone Highlight")
bgcolor(dmriNormalized < bearishZone ? color.new(color.red, 90) : na, title="Bearish Zone Highlight")
Dynamic Momentum Range Index (DMRI)//@version=5
indicator("Dynamic Momentum Range Index (DMRI)", shorttitle="DMRI", overlay=false)
// Inputs
n = input.int(14, title="Momentum Period", minval=1)
atrLength = input.int(14, title="ATR Length", minval=1)
maLength = input.int(20, title="Moving Average Length", minval=1)
// Calculations
pm = close - close // Price Momentum (PM)
atr = ta.atr(atrLength) // Average True Range (ATR)
va = pm / atr // Volatility Adjustment (VA)
// Moving Average and Dynamic Range Factor (DRF)
ma = ta.sma(close, maLength)
drf = math.abs(close - ma) / atr
// Dynamic Momentum Range Index (DMRI)
dmri = va * drf
// Normalization
maxVal = ta.highest(dmri, atrLength)
minVal = ta.lowest(dmri, atrLength)
dmriNormalized = (dmri - minVal) / (maxVal - minVal) * 100
// Zones for Interpretation
bullishZone = 70
bearishZone = 30
// Plotting DMRI
plot(dmriNormalized, title="DMRI", color=color.blue, linewidth=2)
hline(70, "Overbought", color=color.red)
hline(30, "Oversold", color=color.green)
hline(50, "Neutral", color=color.gray)
// Background Coloring
bgcolor(dmriNormalized > bullishZone ? color.new(color.green, 90) : na, title="Bullish Zone Highlight")
bgcolor(dmriNormalized < bearishZone ? color.new(color.red, 90) : na, title="Bearish Zone Highlight")
QuickPivot Zones**Pivot Levels with Auto Support & Resistance**
This custom Pine Script indicator calculates and displays **pivot points** on your chart, offering automatic detection of potential support and resistance levels. The script calculates regular and "quick" pivot levels, allowing traders to visualize areas where price might reverse or consolidate.
### Key Features:
- **Customizable Source**: Choose whether to base pivots on `High`, `Low`, or `Close` price data.
- **Pivot Calculation**: Identifies pivot highs and lows, offering insights into possible support and resistance zones.
- **Quick Pivot Option**: Offers quicker reaction to market changes with smaller pivot calculation intervals.
- **Dynamic Levels**: Automatically updates and plots dynamic levels of support and resistance.
- **Clear Visualization**: Quickly spot key levels on the chart with distinct plot styles and shapes.
- **Flexible Inputs**: Adjust the pivot sensitivity using `left`, `right`, and `quick_right` parameters for fine-tuned results.
### Usage:
- **Pivot Points** are often used by traders to identify reversal zones or potential breakouts. This indicator will help you spot significant price levels that may impact future price movements.
- **Quick Pivot** mode provides faster updates for short-term traders or during volatile market conditions.
### Ideal For:
- **Day Traders**: Traders seeking quick and responsive pivot points.
- **Swing Traders**: To monitor key support and resistance areas for medium-term trades.
- **Price Action Traders**: Traders relying on price movements and levels without relying on traditional indicators.
Start using **Pivot Levels with Auto SR** to improve your technical analysis and decision-making process today!
---
Kernel Regression Envelope with SMI OscillatorThis script combines the predictive capabilities of the **Nadaraya-Watson estimator**, implemented by the esteemed jdehorty (credit to him for his excellent work on the `KernelFunctions` library and the original Nadaraya-Watson Envelope indicator), with the confirmation strength of the **Stochastic Momentum Index (SMI)** to create a dynamic trend reversal strategy. The core idea is to identify potential overbought and oversold conditions using the Nadaraya-Watson Envelope and then confirm these signals with the SMI before entering a trade.
**Understanding the Nadaraya-Watson Envelope:**
The Nadaraya-Watson estimator is a non-parametric regression technique that essentially calculates a weighted average of past price data to estimate the current underlying trend. Unlike simple moving averages that give equal weight to all past data within a defined period, the Nadaraya-Watson estimator uses a **kernel function** (in this case, the Rational Quadratic Kernel) to assign weights. The key parameters influencing this estimation are:
* **Lookback Window (h):** This determines how many historical bars are considered for the estimation. A larger window results in a smoother estimation, while a smaller window makes it more reactive to recent price changes.
* **Relative Weighting (alpha):** This parameter controls the influence of different time frames in the estimation. Lower values emphasize longer-term price action, while higher values make the estimator more sensitive to shorter-term movements.
* **Start Regression at Bar (x\_0):** This allows you to exclude the potentially volatile initial bars of a chart from the calculation, leading to a more stable estimation.
The script calculates the Nadaraya-Watson estimation for the closing price (`yhat_close`), as well as the highs (`yhat_high`) and lows (`yhat_low`). The `yhat_close` is then used as the central trend line.
**Dynamic Envelope Bands with ATR:**
To identify potential entry and exit points around the Nadaraya-Watson estimation, the script uses **Average True Range (ATR)** to create dynamic envelope bands. ATR measures the volatility of the price. By multiplying the ATR by different factors (`nearFactor` and `farFactor`), we create multiple bands:
* **Near Bands:** These are closer to the Nadaraya-Watson estimation and are intended to identify potential immediate overbought or oversold zones.
* **Far Bands:** These are further away and can act as potential take-profit or stop-loss levels, representing more extreme price extensions.
The script calculates both near and far upper and lower bands, as well as an average between the near and far bands. This provides a nuanced view of potential support and resistance levels around the estimated trend.
**Confirming Reversals with the Stochastic Momentum Index (SMI):**
While the Nadaraya-Watson Envelope identifies potential overextended conditions, the **Stochastic Momentum Index (SMI)** is used to confirm a potential trend reversal. The SMI, unlike a traditional stochastic oscillator, oscillates around a zero line. It measures the location of the current closing price relative to the median of the high/low range over a specified period.
The script calculates the SMI on a **higher timeframe** (defined by the "Timeframe" input) to gain a broader perspective on the market momentum. This helps to filter out potential whipsaws and false signals that might occur on the current chart's timeframe. The SMI calculation involves:
* **%K Length:** The lookback period for calculating the highest high and lowest low.
* **%D Length:** The period for smoothing the relative range.
* **EMA Length:** The period for smoothing the SMI itself.
The script uses a double EMA for smoothing within the SMI calculation for added smoothness.
**How the Indicators Work Together in the Strategy:**
The strategy enters a long position when:
1. The closing price crosses below the **near lower band** of the Nadaraya-Watson Envelope, suggesting a potential oversold condition.
2. The SMI crosses above its EMA, indicating positive momentum.
3. The SMI value is below -50, further supporting the oversold idea on the higher timeframe.
Conversely, the strategy enters a short position when:
1. The closing price crosses above the **near upper band** of the Nadaraya-Watson Envelope, suggesting a potential overbought condition.
2. The SMI crosses below its EMA, indicating negative momentum.
3. The SMI value is above 50, further supporting the overbought idea on the higher timeframe.
Trades are closed when the price crosses the **far band** in the opposite direction of the trade. A stop-loss is also implemented based on a fixed value.
**In essence:** The Nadaraya-Watson Envelope identifies areas where the price might be deviating significantly from its estimated trend. The SMI, calculated on a higher timeframe, then acts as a confirmation signal, suggesting that the momentum is shifting in the direction of a potential reversal. The ATR-based bands provide dynamic entry and exit points based on the current volatility.
**How to Use the Script:**
1. **Apply the script to your chart.**
2. **Adjust the "Kernel Settings":**
* **Lookback Window (h):** Experiment with different values to find the smoothness that best suits the asset and timeframe you are trading. Lower values make the envelope more reactive, while higher values make it smoother.
* **Relative Weighting (alpha):** Adjust to control the influence of different timeframes on the Nadaraya-Watson estimation.
* **Start Regression at Bar (x\_0):** Increase this value if you want to exclude the initial, potentially volatile, bars from the calculation.
* **Stoploss:** Set your desired stop-loss value.
3. **Adjust the "SMI" settings:**
* **%K Length, %D Length, EMA Length:** These parameters control the sensitivity and smoothness of the SMI. Experiment to find settings that work well for your trading style.
* **Timeframe:** Select the higher timeframe you want to use for SMI confirmation.
4. **Adjust the "ATR Length" and "Near/Far ATR Factor":** These settings control the width and sensitivity of the envelope bands. Smaller ATR lengths make the bands more reactive to recent volatility.
5. **Customize the "Color Settings"** to your preference.
6. **Observe the plots:**
* The **Nadaraya-Watson Estimation (yhat)** line represents the estimated underlying trend.
* The **near and far upper and lower bands** visualize potential overbought and oversold zones based on the ATR.
* The **fill areas** highlight the regions between the near and far bands.
7. **Look for entry signals:** A long entry is considered when the price touches or crosses below the lower near band and the SMI confirms upward momentum. A short entry is considered when the price touches or crosses above the upper near band and the SMI confirms downward momentum.
8. **Manage your trades:** The script provides exit signals when the price crosses the far band. The fixed stop-loss will also close trades if the price moves against your position.
**Justification for Combining Nadaraya-Watson Envelope and SMI:**
The combination of the Nadaraya-Watson Envelope and the SMI provides a more robust approach to identifying potential trend reversals compared to using either indicator in isolation. The Nadaraya-Watson Envelope excels at identifying potential areas where the price is overextended relative to its recent history. However, relying solely on the envelope can lead to false signals, especially in choppy or volatile markets. By incorporating the SMI as a confirmation tool, we add a momentum filter that helps to validate the potential reversals signaled by the envelope. The higher timeframe SMI further helps to filter out noise and focus on more significant shifts in momentum. The ATR-based bands add a dynamic element to the entry and exit points, adapting to the current market volatility. This mashup aims to leverage the strengths of each indicator to create a more reliable trading strategy.
Gap Reversal SignalsThe Gap Reversal Signals Indicator is a minimalist tool designed to identify and highlight key price action signals.
This indicator provides traders with actionable insights by plotting clean and unobtrusive red and green dots on the chart, ensuring the focus remains on critical price movements.
Gap-Up Reversal Signal (Green Dot):
A green dot is plotted below a candle when:
The candle opens above the previous candle's close (gap up).
Gap-Down Reversal Signal (Red Dot):
A red dot is plotted above a candle when:
The candle opens below the previous candle's close (gap down).
Alerts:
Alerts can be set up to notify the user when:
A gap-up reversal (green dot) is detected.
A gap-down reversal (red dot) is detected.
BB MACD CCI Combined IndicatorBB MACD CCI Combined Indicator:
The BB MACD CCI Combined Indicator is a powerful tool that combines three popular indicators: **Bollinger Bands (BB)**, **MACD**, and **CCI**. It provides traders with a comprehensive view of the market, helping to identify potential entry and exit points. However, like any indicator, its use should be part of a broader strategy and approach.
#### What You Need to Know:
1. **Multiple Signals**: The indicator generates signals based on MACD line crossovers, Bollinger Band levels, and CCI values, helping traders make informed decisions.
2. **A Complement to Your Trading Strategy**: This indicator is intended as an additional tool to your current strategy, not as a sole source of signals.
3. **Requires Caution**: Like any technical analysis tool, the indicator does not guarantee success. It’s important to consider market conditions and use the indicator as part of a larger analysis.
#### Key Considerations for Decision-Making:
- **Personal Use**: This indicator provides additional signals, but the decision to trade remains entirely up to you.
- **Not Suitable for All**: The indicator is best suited for traders who prefer multiple confirming signals. It can be effective in volatile markets but is not a one-size-fits-all solution.
- **Experience and Analysis**: Your own knowledge, experience, and ability to interpret signals will always be key to success.
#### Why Try It:
- The indicator combines proven tools like MACD, Bollinger Bands, and CCI, offering a better understanding of the market.
- It provides clear, easy-to-understand signals for potential entry and exit points.
---
Ultimately, the decision to use this indicator is yours. It offers additional information to help make decisions but should always be considered alongside other factors, such as current market conditions and your overall trading strategy.
Вот описание, которое подчеркивает независимость и позволяет пользователям принять решение о том, использовать ли твой индикатор:
---
BB MACD CCI Combined Indicator:
BB MACD CCI Combined Indicator — это мощный инструмент, который сочетает в себе три популярных индикатора: **Полосы Боллинджера (BB)**, **MACD** и **CCI**. Он предоставляет трейдерам всесторонний взгляд на рынок, помогая идентифицировать возможные точки входа и выхода. Однако, как и любой индикатор, его использование должно быть частью более широкой стратегии и подхода.
#### Что важно знать:
1. **Множество сигналов**: Индикатор генерирует сигналы на основе пересечений линий MACD, уровней полос Боллинджера и значений CCI, что помогает трейдерам принимать обоснованные решения.
2. **Дополнение к торговой стратегии**: Этот индикатор может быть полезен как дополнение к вашей текущей стратегии, но не стоит полагаться на него как на единственный источник сигналов.
3. **Требует осмотрительности**: Как и любой инструмент технического анализа, индикатор не гарантирует успеха. Необходимо учитывать рыночные условия и использовать индикатор в контексте общей картины.
#### Важные аспекты для принятия решения:
- **Личное использование**: Индикатор создан для того, чтобы предоставить дополнительные сигналы, а не диктовать действия. Решение о торговле всегда остается за вами.
- **Не идеален для всех**: Этот индикатор подходит для трейдеров, предпочитающих использование нескольких подтверждающих сигналов. Он может быть полезен на волатильных рынках, но не является универсальным решением.
- **Опыт и анализ**: Ваши собственные знания и опыт, а также способность правильно интерпретировать сигналы, всегда будут решающими факторами для успеха.
#### Почему стоит попробовать:
- Индикатор сочетает в себе проверенные инструменты, такие как MACD, полосы Боллинджера и CCI, что может помочь лучше понять рынок.
- Он предоставляет четкие и понятные сигналы для потенциальных точек входа и выхода.
---
В конечном итоге, решение использовать этот индикатор остается за вами. Он предлагает дополнительную информацию для принятия решений, но всегда следует учитывать другие факторы, такие как текущие рыночные условия и вашу торговую стратегию.
Uptrick: Smart BoundariesThis script is an indicator that combines the RSI (Relative Strength Index) and Bollinger Bands to highlight potential points where price momentum and volatility may both be at extreme levels. Below is a detailed explanation of its components, how it calculates signals, and why these two indicators have been merged into one tool. This script is intended solely for educational purposes and for traders who want to explore the combined use of momentum and volatility measures. Please remember that no single indicator guarantees profitable results.
Purpose of This Script
This script is designed to serve as a concise, all-in-one tool for traders seeking to track both momentum and volatility extremes in real time. By overlaying RSI signals with Bollinger Band boundaries, it helps users quickly identify points on a chart where price movement may be highly stretched. The goal is to offer a clearer snapshot of potential overbought or oversold conditions without requiring two separate indicators. Additionally, its optional pyramiding feature enables users to manage how many times they initiate trades when signals repeat in the same direction. Through these combined functions, the script aims to streamline technical analysis by consolidating two popular measures—momentum via RSI and volatility via Bollinger Bands—into a single, manageable interface.
1. Why Combine RSI and Bollinger Bands
• RSI (Relative Strength Index): This is a momentum oscillator that measures the speed and magnitude of recent price changes. It typically ranges between 0 and 100. Traders often watch for RSI crossing into “overbought” or “oversold” levels because it may indicate a potential shift in momentum.
• Bollinger Bands: These bands are plotted around a moving average, using a standard deviation multiplier to create an upper and lower boundary. They help illustrate how volatile the price has been relative to its recent average. When price moves outside these boundaries, some traders see it as a sign the price may be overstretched and could revert closer to the average.
Combining these two can be useful because it blends two different perspectives on market movement. RSI attempts to identify momentum extremes, while Bollinger Bands track volatility extremes. By looking for moments when both conditions agree, the script tries to highlight points where price might be unusually stretched in terms of both momentum and volatility.
2. How Signals Are Generated
• Buy Condition:
- RSI dips below a specified “oversold” level (for example, 30 by default).
- Price closes below the lower Bollinger Band.
When these occur together, the script draws a label indicating a potential bullish opportunity. The underlying reasoning is that momentum (RSI) suggests a stronger-than-usual sell-off, and price is also stretched below the lower Bollinger Band.
• Sell Condition:
- RSI rises above a specified “overbought” level (for example, 70 by default).
- Price closes above the upper Bollinger Band.
When these occur together, a label is plotted for a potential bearish opportunity. The rationale is that momentum (RSI) may be overheated, and the price is trading outside the top of its volatility range.
3. Pyramiding Logic and Trade Count Management
• Pyramiding refers to taking multiple positions in the same direction when signals keep firing. While some traders prefer just one position per signal, others like to scale into a trade if the market keeps pushing in their favor.
• This script uses variables that keep track of how many recent buy or sell signals have fired. If the count reaches a user-defined maximum, no more signals of that type will trigger additional labels. This protects traders from over-committing to one direction if the market conditions remain “extreme” for a prolonged period.
• If you disable the pyramiding feature, the script will only plot one label per side until the condition resets (i.e., until RSI and price conditions are no longer met).
4. Labels and Visual Feedback
• Whenever a buy or sell condition appears, the script plots a label directly on the chart:
- Buy labels under the price bar.
- Sell labels above the price bar.
These labels make it easier to review where both RSI and Bollinger Band conditions align. It can be helpful for visually scanning the chart to see if the signals show any patterns related to market reversals or trend continuations.
• The Bollinger Bands themselves are plotted so traders can see when the price is approaching or exceeding the upper or lower band. Watching the RSI and Bollinger Band plots simultaneously can give traders more context for each signal.
5. Originality and Usefulness
This script provides a distinct approach by merging two well-established concepts—RSI and Bollinger Bands—within a single framework, complemented by optional pyramiding controls. Rather than using each indicator separately, it attempts to uncover moments when momentum signals from RSI align with volatility extremes highlighted by Bollinger Bands. This combined perspective can aid in spotting areas of possible overextension in price. Additionally, the built-in pyramiding mechanism offers a method to manage multiple signals in the same direction, allowing users to adjust how aggressively they scale into trades. By integrating these elements together, the script aims to deliver a tool that caters to diverse trading styles while remaining straightforward to configure and interpret.
6. How to Use the Indicator
• Configure the Inputs:
- RSI Length (the lookback period used for the RSI calculation).
- RSI Overbought and Oversold Levels.
- Bollinger Bands Length and Multiplier (defines the moving average period and the degree of deviation).
- Option to reduce pyramiding.
• Set Alerts (Optional):
- You can create TradingView alerts for when these conditions occur, so you do not have to monitor the chart constantly. Choose the buy or sell alert conditions in your alert settings.
• Integration in a Trading Plan:
- This script alone is not a complete trading system. Consider combining it with other forms of analysis, such as support and resistance, volume profiles, or candlestick patterns. Thorough research, testing on historical data, and risk management are always recommended.
7. No Performance Guarantees
• This script does not promise any specific trading results. It is crucial to remember that no single indicator can accurately predict future market movements all the time. The script simply tries to highlight moments when two well-known indicators both point to an extreme condition.
• Actual trading decisions should factor in a range of market information, including personal risk tolerance and broader market conditions.
8. Purpose and Limitations
• Purpose:
- Provide a combined view of momentum (RSI) and volatility (Bollinger Bands) in a single script.
- Assist in spotting times when price may be at an extreme.
- Offer a configurable system for labeling potential buy or sell points based on these extremes.
• Limitations:
- Overbought and oversold conditions can persist for an extended period in trending markets.
- Bollinger Band breakouts do not always result in immediate reversals. Sometimes price keeps moving in the same direction.
- The script does not include a built-in exit strategy or risk management rules. Traders must handle these themselves.
Additional Disclosures
This script is published open-source and does not rely on any external or private libraries. It does not use lookahead methods or repaint signals; all calculations are performed on the current bar without referencing future data. Furthermore, the script is designed for standard candlestick or bar charts rather than non-standard chart types (e.g., Heikin Ashi, Renko). Traders should keep in mind that while the script can help locate potential momentum and volatility extremes, it does not include an exit strategy or account for factors like slippage or commission. All code comes from built-in Pine Script functions and standard formulas for RSI and Bollinger Bands. Anyone reviewing or modifying this script should exercise caution and incorporate proper risk management when applying it to their own trading.
Calculation Details
The script computes RSI by examining a user-defined number of prior bars (the RSI Length) and determining the average of up-moves relative to the average of down-moves over that period. This ratio is then scaled to a 0–100 range, so lower values typically indicate stronger downward momentum, while higher values suggest stronger upward momentum. In parallel, Bollinger Bands are generated by first calculating a simple moving average (SMA) of the closing price for the user-specified length. The script then measures the standard deviation of closing prices over the same period and multiplies it by the chosen factor (the Bollinger Bands Multiplier) to form the upper and lower boundaries around the SMA. These two measures are checked in tandem: if the RSI dips below a certain oversold threshold and price trades below the lower Bollinger Band, a condition is met that may imply a strong short-term sell-off; similarly, if the RSI surpasses the overbought threshold and price rises above the upper Band, it may indicate an overextended move to the upside. The pyramiding counters track how many of these signals occur in sequence, preventing excessive stacking of labels on the chart if conditions remain extreme for multiple bars.
Conclusion
This indicator aims to provide a more complete view of potential market extremes by overlaying the RSI’s momentum readings on top of Bollinger Band volatility signals. By doing so, it attempts to help traders see when both indicators suggest that the market might be oversold or overbought. The optional reduced pyramiding logic further refines how many signals appear, giving users the choice of a single entry or multiple scaling entries. It does not claim any guaranteed success or predictive power, but rather serves as a tool for those wanting to explore this combined approach. Always be cautious and consider multiple factors before placing any trades.
ICCMSThis TradingView Pine Script implements the Cloud indicator, which consists of several components to analyze market trends. It calculates the Tenkan-sen (conversion line) and Kijun-sen (base line) using Donchian channel averages over specified periods. Additionally, it computes two leading spans to create a cloud (Kumo) that visually represents support and resistance levels. The script plots these lines on the chart, including a lagging span that follows the price. The cloud's fill color changes based on the relationship between the leading spans, indicating bullish or bearish conditions.
Momentum Indicators SuiteThis script is a Momentum Indicators Suite for traders using Pine Script™ (version 5). Its purpose is to evaluate market conditions by aggregating signals from multiple technical indicators into a single "bullish," "bearish," or "neutral" state. Below is a detailed breakdown of its components and functionality:
1. Indicators Used
The script incorporates several well-known technical indicators to assess market momentum:
RSI (Relative Strength Index)
MACD (Moving Average Convergence Divergence)
Stochastic Oscillator
TSI (True Strength Index)
CCI (Commodity Channel Index)
Choppiness Index
Vortex Indicator
Momentum and ROC (Rate of Change)
2. Scoring System
Each indicator assigns points based on its signals:
+1 Point for bullish conditions.
-1 Point for bearish conditions.
0 Points for neutral or indecisive signals.
These points are aggregated to calculate a total score (totalPoints), representing overall market momentum.
3. Market State Determination
The total points determine the market state:
Bullish if totalPoints > 0.
Bearish if totalPoints < 0.
4. Dynamic Trend Label
When the market state changes, a label is added to the chart:
Green label for bullish trends.
Red label for bearish trends.
5. Visual Enhancements - Plot and Fill (Optional)
6. Customization - Traders can adjust several inputs for fine-tuning:
7. Target Audience - This script is ideal for:
Traders who rely on momentum and trend analysis for decision-making.
Those seeking a consolidated view of multiple indicators.
Swing and day traders aiming to identify trend changes promptly.
8. Potential Use Cases
Trend Confirmation: Helps confirm bullish or bearish market trends.
Trade Setup Identification: Assists in aligning trades with dominant market momentum.
Risk Management: Signals market neutrality or choppiness to avoid indecisive conditions.
This script simplifies complex momentum analysis by aggregating multiple indicators into actionable insights, making it a valuable tool for technical traders.
Volatility ProfileVolatility Profile allows for a fast comparison of the Average True Range from different time frames.
In addition to that, for each time frame it calculates the maximum and the minimum value over a set number of bars and divides the range between the maximum and the minimum in three parts to create three different volatility classes, which allows the user to quickly see how big the current value really is in relation to the past.
The settings allow the user to set the two extra time frames apart from the main time frame and the ATR length for each of the three ATR's, as well as the look back period to calculate the maximum and the minimum values.
This indicator is meant to help create a much more comprehensive view of the instrument's volatility.
Dynamic Hybrid IndicatorHedef: Kısa vadeli trend dönüşlerini erken tespit ederek al-sat sinyalleri üretmek.
Zaman Dilimi: 1 dakikalık, 5 dakikalık ya da 15 dakikalık grafikler.
Dynamic Volatility Heatmap (ATR)How the Script Works
Dynamic Thresholds:
atrLow and atrHigh are calculated as percentiles (20% and 80% by default) of ATR values over the last double the ATR period (28 days if ATR is 14).
This creates thresholds that adapt to recent market conditions.
Background Heatmap:
Green: ATR is below the low threshold, indicating calm markets (options are cheap).
Red: ATR is above the high threshold, signaling elevated volatility (options are expensive).
Yellow: ATR is within the normal range, showing neutral market conditions.
Overlay Lines:
]Dynamic lines for atrLow and atrHigh help visualize thresholds on the chart.
Interpretation for Trading
Green Zone (Low ATR):
Interpretation: The market is calm, and options are likely underpriced.
Trade Setup: Favor buying options (e.g., long straddles or long calls/puts) to profit from potential volatility increases.
Red Zone (High ATR):
Interpretation: The market is volatile, and options are likely overpriced.
Trade Setup: Favor selling options (e.g., credit spreads or iron condors) to benefit from volatility decay.
Yellow Zone (Neutral ATR):
Interpretation: Volatility is within typical levels, offering no strong signal.
Trade Setup: Combine with other indicators, such as gamma levels or Bollinger Bands, for confirmation.
5. Enhancing with Other Indicators
Combine with Bollinger Bands:
Overlay Bollinger Bands to identify price extremes and align them with volatility heatmap signals.
Volatility-Weighted MA (VWMA)Interpretation:
VWMA adjusts to changes in market volatility, offering dynamic support and resistance levels.
Sharp deviations from VWMA often signal potential reversals or breakouts.
How to Use for Trades:
Mean Reversion: Look for price rejections at VWMA in low-volatility environments.
Trend Breakout: Trade in the direction of the breakout when price closes strongly above/below VWMA in high-volatility conditions.
Enhanced Price Z-Score OscillatorThe Enhanced Price Z-Score Oscillator by tkarolak is a powerful tool that transforms raw price data into an easy-to-understand statistical visualization using Z-Score-derived candlesticks. Simply put, it shows how far prices stray from their average in terms of standard deviations (Z-Scores), helping traders identify when prices are unusually high (overbought) or unusually low (oversold).
The indicator’s default feature displays Z-Score Candlesticks, where each candle reflects the statistical “distance” of the open, high, low, and close prices from their average. This creates a visual map of market extremes and potential reversal points. For added flexibility, you can also switch to Z-Score line plots based on either Close prices or OHLC4 averages.
With clear threshold lines (±2σ and ±3σ) marking moderate and extreme price deviations, and color-coded zones to highlight overbought and oversold areas, the oscillator simplifies complex statistical concepts into actionable trading insights.
Santa's Adventure [AlgoAlpha]Introducing "Santa's Adventure," a unique and festive TradingView indicator designed to bring the holiday spirit to your trading charts. With this indicator, watch as Santa, his sleigh, Rudolf the reindeer, and a flurry of snowflakes come to life, creating a cheerful visual experience while you monitor the markets.
Key Features:
🎁 Dynamic Santa Sleigh Visualization : Santa's sleigh, Rudolf, and holiday presents adapt to price movements and chart structure.
🎨 Customizable Holiday Colors : Adjust colors for Santa’s outfit, Rudolf’s nose, sleigh, presents, and more.
❄️ Realistic Snow Animation : A cascade of snowflakes decorates your charts, with density and range adjustable to suit your preferences.
📏 Adaptive Scaling : All visuals scale based on price volatility and market dynamics.
🔄 Rotation by Trend : Santa and his entourage tilt to reflect market trends, making it both functional and fun!
How to Use :
Add the Indicator to Your Chart : Search for "Santa's Adventure" in the TradingView indicator library and add it to your favorites. Use the input menu to adjust snow density, sleigh colors, and other festive elements to match your trading style or holiday mood.
Observe the Market : Watch Santa’s sleigh glide across the chart while Rudolf leads the way, with snowflakes gently falling to enhance the visual charm.
How It Works :
The indicator uses price volatility and market data to dynamically position Santa, his sleigh, Rudolf, and presents on the chart. Santa's Sleigh angle adjusts based on price trends, reflecting market direction. Santa's sleigh and the snowstorm are plotted using advanced polyline arrays for a smooth and interactive display. A festive algorithm powers the snowfall animation, ensuring a consistent and immersive holiday atmosphere. The visuals are built to adapt seamlessly to any market environment, combining holiday cheer with market insights.
Add "Santa's Adventure" to your TradingView charts today and bring the holiday spirit to your trading journey, Merry Christmas! 🎅🎄
Filtered ATR with EMA OverlayFiltered ATR with EMA Overlay is an advanced volatility indicator designed to provide a more accurate representation of market conditions by smoothing the standard Average True Range (ATR). This is achieved by filtering out extreme price movements and abnormal bars that can distort traditional ATR calculations.
The indicator applies an Exponential Moving Average (EMA) to the filtered ATR, creating a dual-layered system that highlights periods of increased or decreased volatility.
Key Features:
Filtered ATR: Filters out extreme bars, reducing noise and making the ATR line more reliable.
EMA Overlay: An EMA (default period of 10) is applied to the filtered ATR, allowing traders to track average volatility trends.
Volatility Signals:
Filtered ATR > EMA(10): Indicates higher-than-average volatility. This often correlates with trend breakouts or strong price movements.
Filtered ATR < EMA(10): Suggests reduced volatility, signaling potential consolidation or sideways price action.
Parameters:
atrLength (Default: 5):
The number of bars used to calculate the ATR. A shorter period (e.g., 3-5) responds faster to price changes, while a longer period (e.g., 10-14) provides smoother results.
multiplier (Default: 1.8):
Controls the sensitivity of the filter. A lower multiplier (e.g., 1.5) filters out more bars, resulting in smoother ATR. Higher values (e.g., 2.0) allow more bars to pass through, retaining more price volatility.
maxIterations (Default: 20):
The maximum number of bars processed to detect abnormal values. Increasing this may improve accuracy at the cost of performance.
ema10Period (Default: 10):
The period for the Exponential Moving Average applied to the filtered ATR. Shorter periods provide faster signals, while longer periods give smoother, lagging signals.
Trading Strategies:
1. Breakout Strategy:
When filtered ATR crosses above EMA(10):
Enter long positions when price breaks above a key resistance level.
Higher volatility suggests strong price action and momentum.
When filtered ATR drops below EMA(10):
Exit positions or tighten stop-loss orders as volatility decreases.
Lower volatility may indicate consolidation or trend exhaustion.
2. Trend Following Strategy:
Use the filtered ATR line to track overall volatility.
If filtered ATR consistently stays above EMA: Hold positions or add to trades.
If filtered ATR remains below EMA: Reduce position size or stay out of trades.
3. Mean Reversion Strategy:
When filtered ATR spikes significantly above EMA, it may indicate market overreaction.
Look for price to revert to the mean once ATR returns below the EMA.
4. Stop-Loss Adjustment:
As volatility increases (ATR above EMA), widen stop-loss levels to avoid being stopped out by random fluctuations.
In low volatility (ATR below EMA), tighten stop-losses to minimize losses during low activity periods.
Benefits:
Reduced Noise: By filtering abnormal bars, the indicator provides cleaner signals.
Better Trend Detection: EMA smoothing highlights volatility trends.
Adaptable: The indicator can be customized for scalping, day trading, or swing trading.
Intuitive Visualization: Traders can visually see volatility shifts and adjust strategies in real-time.
Best Practices:
Timeframes: Works effectively on all timeframes, but higher timeframes (e.g., 1H, 4H, Daily) yield more reliable signals.
Markets: Suitable for forex, crypto, stocks, and commodities.
Combining Indicators: Use in combination with RSI, Moving Averages, Bollinger Bands, or price action analysis for stronger signals.
How It Works (Under the Hood):
The script calculates the Daily Range (High - Low) for each bar.
The largest and smallest bars are filtered out if their difference exceeds the multiplier (default 1.8).
The remaining bars are averaged to generate the filtered ATR.
An EMA(10) is then applied to the filtered ATR for smoother visualization.
Breadth of Volatility The Breadth of Volatility (BoV) is an indicator designed to help traders understand the activity and volatility of the market. It focuses on analyzing how fast prices are moving and how much trading volume is driving those movements. By combining these two factors—price speed and volume strength—the BoV provides a single value that reflects the current level of market activity. This can help traders identify when the market is particularly active or calm, which is useful for planning trading strategies.
The speed component of the BoV measures how quickly prices are moving compared to their recent average. This is done by using a metric called the Average True Range (ATR), which calculates the typical size of price movements over a specific period. The BoV compares the current price change to this average, showing whether the market is moving faster or slower than usual. Faster price movements generally indicate higher volatility, which might signal opportunities for active traders.
The strength component focuses on the role of trading volume in price changes. It multiplies the trading volume by the size of the price movement to create a value called volume strength. This value is then compared to the highest volume strength seen over a recent period, which helps gauge whether the current price action is being strongly supported by trading activity. When the strength value is high, it suggests that market participants are actively trading and supporting the price movement.
These two components—speed and strength—are averaged to calculate the Breadth of Volatility value. While the formula also includes a placeholder for a third component (related to fundamental analysis), it is currently inactive and does not influence the final value. The BoV is displayed as a line on a chart, with a zero line for reference. Positive BoV values indicate heightened market activity and volatility, while values near zero suggest a quieter market. This indicator is particularly helpful for new traders to monitor market conditions and adjust their strategies accordingly, whether they’re focusing on trend-following or waiting for calmer periods for more conservative trades.
Important Notice:
Trading financial markets involves significant risk and may not be suitable for all investors. The use of technical indicators like this one does not guarantee profitable results. This indicator should not be used as a standalone analysis tool. It is essential to combine it with other forms of analysis, such as fundamental analysis, risk management strategies, and awareness of current market conditions. Always conduct thorough research or consult with a qualified financial advisor before making trading decisions. Past performance is not indicative of future results.
Disclaimer:
Trading financial instruments involves substantial risk and may not be suitable for all investors. Past performance is not indicative of future results. This indicator is provided for informational and educational purposes only and should not be considered investment advice. Always conduct your own research and consult with a licensed financial professional before making any trading decisions.
Note: The effectiveness of any technical indicator can vary based on market conditions and individual trading styles. It's crucial to test indicators thoroughly using historical data and possibly paper trading before applying them in live trading scenarios.
Abnormal Delta Volume HistogramThis indicator can help traders spot potential turning points or heightened volatility and provides a dynamic measure of unusual market behavior by focusing on shifts in “delta volume.” Delta volume is approximated by assigning all of a bar’s volume to the bullish side if the close is higher than the open and to the bearish side if the close is lower. The result is a net volume measure that can hint at which side—buyers or sellers—has the upper hand. By comparing this delta volume to its historical averages and measuring how far current readings deviate in terms of standard deviations, the indicator can highlight bars that reflect significantly stronger than normal buying or selling pressure.
A histogram visualizes these delta volume values on a bar-by-bar basis, while additional reference lines for the mean and threshold boundaries allow traders to quickly identify abnormal conditions. When the histogram bars extend beyond the threshold lines, and are colored differently to signal abnormality, it can draw the trader’s eye to periods when market participation or sentiment may be shifting rapidly. This can be used as an early warning signal, prompting further investigation into price action, external news, or significant events that may be driving unusual volume patterns.
Important Notice:
Trading financial markets involves significant risk and may not be suitable for all investors. The use of technical indicators like this one does not guarantee profitable results. This indicator should not be used as a standalone analysis tool. It is essential to combine it with other forms of analysis, such as fundamental analysis, risk management strategies, and awareness of current market conditions. Always conduct thorough research or consult with a qualified financial advisor before making trading decisions. Past performance is not indicative of future results.
Disclaimer:
Trading financial instruments involves substantial risk and may not be suitable for all investors. Past performance is not indicative of future results. This indicator is provided for informational and educational purposes only and should not be considered investment advice. Always conduct your own research and consult with a licensed financial professional before making any trading decisions.
Note: The effectiveness of any technical indicator can vary based on market conditions and individual trading styles. It's crucial to test indicators thoroughly using historical data and possibly paper trading before applying them in live trading scenarios.
Z-Strike RecoveryThis strategy utilizes the Z-Score of daily changes in the VIX (Volatility Index) to identify moments of extreme market panic and initiate long entries. Scientific research highlights that extreme volatility levels often signal oversold markets, providing opportunities for mean-reversion strategies.
How the Strategy Works
Calculation of Daily VIX Changes:
The difference between today’s and yesterday’s VIX closing prices is calculated.
Z-Score Calculation:
The Z-Score quantifies how far the current change deviates from the mean (average), expressed in standard deviations:
Z-Score=(Daily VIX Change)−MeanStandard Deviation
Z-Score=Standard Deviation(Daily VIX Change)−Mean
The mean and standard deviation are computed over a rolling period of 16 days (default).
Entry Condition:
A long entry is triggered when the Z-Score exceeds a threshold of 1.3 (adjustable).
A high positive Z-Score indicates a strong overreaction in the market (panic).
Exit Condition:
The position is closed after 10 periods (days), regardless of market behavior.
Visualizations:
The Z-Score is plotted to make extreme values visible.
Horizontal threshold lines mark entry signals.
Bars with entry signals are highlighted with a blue background.
This strategy is particularly suitable for mean-reverting markets, such as the S&P 500.
Scientific Background
Volatility and Market Behavior:
Studies like Whaley (2000) demonstrate that the VIX, known as the "fear gauge," is highly correlated with market panic phases. A spike in the VIX is often interpreted as an oversold signal due to excessive hedging by investors.
Source: Whaley, R. E. (2000). The investor fear gauge. Journal of Portfolio Management, 26(3), 12-17.
Z-Score in Financial Strategies:
The Z-Score is a proven method for detecting statistical outliers and is widely used in mean-reversion strategies.
Source: Chan, E. (2009). Quantitative Trading. Wiley Finance.
Mean-Reversion Approach:
The strategy builds on the mean-reversion principle, which assumes that extreme market movements tend to revert to the mean over time.
Source: Jegadeesh, N., & Titman, S. (1993). Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency. Journal of Finance, 48(1), 65-91.
MA Deviation Suite [InvestorUnknown]This indicator combines advanced moving average techniques with multiple deviation metrics to offer traders a versatile tool for analyzing market trends and volatility.
Moving Average Types :
SMA, EMA, HMA, DEMA, FRAMA, VWMA: Standard moving averages with different characteristics for smoothing price data.
Corrective MA: This method corrects the MA by considering the variance, providing a more responsive average to price changes.
f_cma(float src, simple int length) =>
ma = ta.sma(src, length)
v1 = ta.variance(src, length)
v2 = math.pow(nz(ma , ma) - ma, 2)
v3 = v1 == 0 or v2 == 0 ? 1 : v2 / (v1 + v2)
var tolerance = math.pow(10, -5)
float err = 1
// Gain Factor
float kPrev = 1
float k = 1
for i = 0 to 5000 by 1
if err > tolerance
k := v3 * kPrev * (2 - kPrev)
err := kPrev - k
kPrev := k
kPrev
ma := nz(ma , src) + k * (ma - nz(ma , src))
Fisher Least Squares MA: Aims to reduce lag by using a Fisher Transform on residuals.
f_flsma(float src, simple int len) =>
ma = src
e = ta.sma(math.abs(src - nz(ma )), len)
z = ta.sma(src - nz(ma , src), len) / e
r = (math.exp(2 * z) - 1) / (math.exp(2 * z) + 1)
a = (bar_index - ta.sma(bar_index, len)) / ta.stdev(bar_index, len) * r
ma := ta.sma(src, len) + a * ta.stdev(src, len)
Sine-Weighted MA & Cosine-Weighted MA: These give more weight to middle bars, creating a smoother curve; Cosine weights are shifted for a different focus.
Deviation Metrics :
Average Absolute Deviation (AAD) and Median Absolute Deviation (MAD): AAD calculates the average of absolute deviations from the MA, offering a measure of volatility. MAD uses the median, which can be less sensitive to outliers.
Standard Deviation (StDev): Measures the dispersion of prices from the mean.
Average True Range (ATR): Reflects market volatility by considering the day's range.
Average Deviation (adev): The average of previous deviations.
// Calculate deviations
float aad = f_aad(src, dev_len, ma) * dev_mul
float mad = f_mad(src, dev_len, ma) * dev_mul
float stdev = ta.stdev(src, dev_len) * dev_mul
float atr = ta.atr(dev_len) * dev_mul
float avg_dev = math.avg(aad, mad, stdev, atr)
// Calculated Median with +dev and -dev
float aad_p = ma + aad
float aad_m = ma - aad
float mad_p = ma + mad
float mad_m = ma - mad
float stdev_p = ma + stdev
float stdev_m = ma - stdev
float atr_p = ma + atr
float atr_m = ma - atr
float adev_p = ma + avg_dev
float adev_m = ma - avg_dev
// upper and lower
float upper = f_max4(aad_p, mad_p, stdev_p, atr_p)
float upper2 = f_min4(aad_p, mad_p, stdev_p, atr_p)
float lower = f_min4(aad_m, mad_m, stdev_m, atr_m)
float lower2 = f_max4(aad_m, mad_m, stdev_m, atr_m)
Determining Trend
The indicator generates trend signals by assessing where price stands relative to these deviation-based lines. It assigns a trend score by summing individual signals from each deviation measure. For instance, if price crosses above the MAD-based upper line, it contributes a bullish point; crossing below an ATR-based lower line contributes a bearish point.
When the aggregated trend score crosses above zero, it suggests a shift towards a bullish environment; crossing below zero indicates a bearish bias.
// Define Trend scores
var int aad_t = 0
if ta.crossover(src, aad_p)
aad_t := 1
if ta.crossunder(src, aad_m)
aad_t := -1
var int mad_t = 0
if ta.crossover(src, mad_p)
mad_t := 1
if ta.crossunder(src, mad_m)
mad_t := -1
var int stdev_t = 0
if ta.crossover(src, stdev_p)
stdev_t := 1
if ta.crossunder(src, stdev_m)
stdev_t := -1
var int atr_t = 0
if ta.crossover(src, atr_p)
atr_t := 1
if ta.crossunder(src, atr_m)
atr_t := -1
var int adev_t = 0
if ta.crossover(src, adev_p)
adev_t := 1
if ta.crossunder(src, adev_m)
adev_t := -1
int upper_t = src > upper ? 3 : 0
int lower_t = src < lower ? 0 : -3
int upper2_t = src > upper2 ? 1 : 0
int lower2_t = src < lower2 ? 0 : -1
float trend = aad_t + mad_t + stdev_t + atr_t + adev_t + upper_t + lower_t + upper2_t + lower2_t
var float sig = 0
if ta.crossover(trend, 0)
sig := 1
else if ta.crossunder(trend, 0)
sig := -1
Backtesting and Performance Metrics
The code integrates with a backtesting library that allows traders to:
Evaluate the strategy historically
Compare the indicator’s signals with a simple buy-and-hold approach
Generate performance metrics (e.g., mean returns, Sharpe Ratio, Sortino Ratio) to assess historical effectiveness.
Practical Usage and Calibration
Default settings are not optimized: The given parameters serve as a starting point for demonstration. Users should adjust:
len: Affects how smooth and lagging the moving average is.
dev_len and dev_mul: Influence the sensitivity of the deviation measures. Larger multipliers widen the bands, potentially reducing false signals but introducing more lag. Smaller multipliers tighten the bands, producing quicker signals but potentially more whipsaws.
This flexibility allows the trader to tailor the indicator for various markets (stocks, forex, crypto) and time frames.
Disclaimer
No guaranteed results: Historical performance does not guarantee future outcomes. Market conditions can vary widely.
User responsibility: Traders should combine this indicator with other forms of analysis, appropriate risk management, and careful calibration of parameters.