Composite Indicator (Donchian + OBV)Composite Indicator (Donchian + OBV)
The Composite Indicator (Donchian + OBV) is a powerful tool designed to evaluate the strength of market breakouts and momentum trends , offering traders a comprehensive perspective on price action. This indicator combines the Donchian Channel with On-Balance Volume (OBV) to create a dynamic and easy-to-interpret metric scaled between -1 and 1 .
Key Features
Breakout Strength Analysis:
- The indicator assesses the strength of price breakouts relative to the upper and lower bounds of the Donchian Channel.
- Positive values close to 1 indicate a strong bullish breakout.
- Negative values close to -1 indicate a strong bearish breakout.
Momentum Detection with OBV:
- On-Balance Volume (OBV) tracks the cumulative buying and selling volume to gauge market momentum.
- The smoothed OBV trend ensures the momentum component aligns with price action, reducing noise.
Integrated Composite Value:
- Combines breakout strength and OBV momentum into a single metric for enhanced clarity.
- The final composite value highlights whether the market is bullish, bearish, or neutral.
Divergence Detection:
- Spot bullish divergences when the indicator rises while price falls, suggesting a potential upward reversal.
- Identify bearish divergences when the indicator falls while price rises, hinting at a potential downward reversal.
How It Works
Donchian Channel Analysis:
- Calculates the highest high and lowest low over a user-defined period to establish the upper and lower channels .
- Breakouts beyond these channels contribute to the breakout strength component.
OBV Momentum:
- Measures cumulative volume trends to validate price movements.
- Momentum is derived from the rate of change in smoothed OBV values.
Composite Calculation:
- Combines breakout strength and OBV momentum, normalized and scaled to -1 to 1 for clarity.
How to Use
Bullish Breakout:
- When the indicator value approaches 1 , it signals a strong upward breakout supported by positive OBV momentum.
- Example Action: Consider a Buy if price breaks the upper Donchian Channel with increasing OBV.
Bearish Breakout:
- When the indicator value approaches -1 , it indicates a strong downward breakout supported by negative OBV momentum.
- Example Action: Consider a Sell if price breaks the lower Donchian Channel with decreasing OBV.
Neutral Market:
- When the value is near 0 , the market is likely balanced with no significant breakout or momentum detected.
Divergence Opportunities:
- Bullish Divergence: Price makes lower lows, but the indicator trends upward → Potential upward reversal.
- Bearish Divergence: Price makes higher highs, but the indicator trends downward → Potential downward reversal.
Customization Options
Donchian Channel Length: Adjust the period for the upper and lower bounds.
OBV Smoothing Length: Modify the smoothing period for OBV to fine-tune momentum detection.
Scaling Adjustments: The composite value is automatically normalized for consistency across timeframes.
Ideal Use Cases
Breakout Trading: Identify and confirm strong breakouts in volatile markets.
Momentum Confirmation: Validate price movements with volume-based momentum.
Reversal Detection: Leverage divergences to spot potential market reversals.
Example Applications
Strong Bullish Signal:
- Price breaks the upper channel , and OBV shows increasing volume → Composite value near 1 .
- Action: Enter a Buy position and set a Stop Loss below the upper channel.
Strong Bearish Signal:
- Price breaks the lower channel , and OBV shows decreasing volume → Composite value near -1 .
- Action: Enter a Sell position and set a Stop Loss above the lower channel.
Neutral Market:
- Composite value near 0 suggests indecision or consolidation. Wait for a breakout.
Limitations
Best used alongside additional tools like RSI or MACD for filtering noise and improving decision-making.
Requires careful parameter tuning based on the asset and timeframe.
Final Thoughts
The Composite Indicator (Donchian + OBV) offers traders a versatile tool to navigate complex markets. By blending breakout analysis with volume-based momentum, this indicator provides an actionable edge for identifying high-probability opportunities and potential reversals.
Indicators and strategies
Codi's Perp-Spot Basis# Perp-Spot Basis Indicator
This indicator calculates the percentage basis between perpetual futures and spot prices for crypto assets. It is inspired by the original concept from **Krugermacro**, with the added improvement of **automatic detection of the asset pairs** based on the current chart symbol. This enhancement makes it faster and easier to apply across different assets without manual configuration.
## How It Works
The indicator compares the perpetual futures price (e.g., `BTCUSDT.P`) to the spot price (e.g., `BTCUSDT`) on Binance. The difference is expressed as a percentage: (Perp - Spot) / Spot * 100
The results are displayed in a color-coded graph:
- **Blue (Positive Basis):** Perpetual futures are trading at a premium, indicating **bullish sentiment** among derivatives traders.
- **Red (Negative Basis):** Perpetual futures are trading at a discount, indicating **bearish sentiment** among derivatives traders.
This percentage basis is a core component in understanding funding rates and derivatives market dynamics. It serves as a faster proxy for funding rates, which typically lag behind real-time price movements.
---
## How to Use It
### General Concept
- **Red (Negative Basis):** Ideal to execute **longs** when derivatives traders are overly bearish.
- **Blue (Positive Basis):** Ideal to execute **shorts** when derivatives traders are overly bullish.
### Pullback Sniping
1. During an **uptrend**:
- If the basis turns **red** temporarily, it can signal an opportunity to **buy the dip**.
2. During a **downtrend**:
- If the basis turns **blue** temporarily, it can signal an opportunity to **sell the rip**.
3. Wait for the basis to **pop back** (higher in uptrend, lower in downtrend) to time entries more effectively—this often coincides with **stop runs** or **liquidations**.
### Intraday Execution
- **When price is falling**:
- If the basis is **red**, the move is derivatives-led (**normal**).
- If the basis is **blue**, spot traders are leading, and perps are offside—wait for **price dumps** before longing.
- **When price is rising**:
- If the basis is **blue**, the move is derivatives-led (**normal**).
- If the basis is **red**, spot traders are leading, and perps are offside—wait for **price pops** before shorting.
### Larger Time Frames
- **Consistently Blue Basis:** Indicates a **bull market** as derivatives traders are bullish over the long term.
- **Consistently Red Basis:** Indicates a **bear market** as derivatives traders are bearish over the long term.
---
## Improvements Over the Original
This version of the Perp-Spot Basis indicator **automatically detects the Binance perpetual futures and spot pairs** based on the current chart symbol. For example:
- If you are viewing `ETHUSDT`, it automatically references `ETHUSDT.P` for the perpetual futures pair and `ETHUSDT` for the spot pair in BINANCE.
Thin Liquidity Zones [PhenLabs]Thin Liquidity Zones with Volume Delta
Our advanced volume analysis tool identifies and visualizes significant liquidity zones using real-time volume delta analysis. This indicator helps traders pinpoint and monitor critical price levels where substantial trading activity occurs, providing precise volume flow measurement through lower timeframe analysis.
The tool works by leveraging the fact that hedge funds, institutions, and other large market participants strategically fill their orders in areas of thin liquidity to minimize slippage and market impact. By detecting these zones, traders gain valuable insights into potential areas of accumulation, distribution, and liquidity traps, allowing for more informed trading decisions.
🔍 Key Features
Real-time volume delta calculation using lower timeframe data
Dynamic zone creation based on volume spikes
Automatic timeframe optimization
Size-filtered zones to avoid noise
Custom delta timeframe scanning
Flexible analysis period selection
📊 Visual Demonstration
💡 How It Works
The indicator continuously scans for high-volume areas where trading activity exceeds the specified threshold (default 6.0x average volume). When detected, it creates zones that display the net volume delta, showing whether buying or selling pressure dominated that price level.
Key zone characteristics:
Size filtering prevents noise from large price swings
Volume delta shows actual buying/selling pressure
Zones automatically expire based on lookback period
Real-time updates as new volume data arrives
⚙️ Settings
Time Settings
Analysis Timeframe: 15M to 1W options
Custom Period: User-defined bar count
Delta Timeframe: Automatic or manual selection
Volume Analysis
Volume Threshold: Minimum spike multiple
Volume MA Length: Averaging period
Maximum Zone Size: Size filter percentage
Display Options
Zone Color: Customizable with transparency
Delta Display: On/Off toggle
Text Position: Left/Center/Right alignment
📌 Tips for Best Results
Adjust volume threshold based on instrument volatility
Monitor zone clusters for potential support/resistance
Consider reducing max zone size in volatile markets
Use in conjunction with price action and other indicators
⚠️ Important Notes
Requires volume data from your data provider
Lower timeframe scanning may impact performance
Maximum 500 zones maintained for optimization
Zone creation is filtered by both volume and size
🔧 Volume Delta Calculation
The indicator uses TradingView’s advanced volume delta calculation, which:
Scans lower timeframe data for precision
Measures actual buying vs selling pressure
Updates in real-time with new data
Provides clear positive/negative flow indication
This tool is ideal for traders focusing on volume analysis and order flow. It helps identify key levels where significant trading activity has occurred and provides insight into the nature of that activity through volume delta analysis.
Note: Performance may vary based on your chart’s timeframe. Adjust settings according to your trading style and the instrument’s characteristics. Past performance is not indicative of future results, DYOR.
Hourly Market Movement Pattern Indicator# Hourly Market Movement Pattern Indicator
This versatile technical analysis tool identifies the most active hours for trading by analyzing historical price movements. While it can be viewed on any timeframe chart, the indicator specifically tracks and displays which hours of the day historically show the strongest upward or downward price movements, helping traders optimize their trading schedule around these recurring hourly patterns.
## Core Features
- Tracks the best performing hours for both upward and downward movements
- Viewable on any timeframe chart while maintaining hourly analysis
- Clear visual display through a color-coded table overlay
- Real-time updates with new market data
- Works with all trading instruments (stocks, crypto, forex, futures, etc.)
## Timeframe Applications
### Chart Viewing Options
- Can be viewed on any timeframe chart (1min to Monthly)
- Maintains hourly pattern analysis regardless of chart timeframe
- Helps correlate hourly patterns with your preferred trading timeframe
- Allows detailed visualization of hourly patterns within your analysis period
### Intraday Trading
- Identify the most profitable hours for trading
- Plan trading sessions around historically strong hours
- Optimize entry and exit timing based on hourly patterns
- Structure day trading schedules around peak movement hours
### Swing Trading
- Use hourly statistics to optimize entry/exit timing
- Plan trade executions during historically strong hours
- Time position entries based on hourly success rates
- Enhance swing trading decisions with hourly pattern data
## Practical Applications
### Pattern Recognition
- Track recurring hourly market movements
- Identify institutional trading hour patterns
- Detect regular market cycle hours
- Recognize changes in hourly market behavior
### Risk Management
- Adjust position sizing based on historical hourly patterns
- Plan entries during statistically favorable hours
- Time stop loss adjustments around known volatile hours
- Scale positions according to hourly success rates
### Trade Planning
- Schedule trading sessions during optimal hours
- Plan trade executions around strong movement periods
- Structure trading day around peak hours
- Time position adjustments to favorable hours
## Setup Options
- Timeframe: View on any chart timeframe while tracking hourly patterns
- Visual Display: Non-intrusive table overlay
- Color Coding: Green for upward movements, Red for downward movements
- Hour Display: 24-hour format for global market compatibility
## Trading Strategy Integration
The indicator enhances trading approaches through:
- Optimal hour identification for trade execution
- Historical hourly pattern analysis
- Day trading session optimization
- Position timing based on hourly statistics
## Notes
This indicator proves particularly valuable for:
- Traders seeking to optimize their daily trading schedule
- Day traders focusing on peak market hours
- Swing traders optimizing entry/exit timing
- Traders adapting strategies to specific market hours
- International traders tracking hour-specific patterns across sessions
The tool's hourly pattern analysis provides crucial timing information regardless of your preferred chart timeframe or trading style, helping optimize trade execution around the most statistically favorable hours of the day.
ROC-Weighted MA Oscillator [SeerQuant]ROC-Weighted MA Oscillator (ROCWMA)
The ROC-Weighted MA Oscillator (ROCWMA) is a momentum-based indicator which uniquely combines the Rate of Change (ROC) with customizable moving averages, offering a dynamic oscillator for trend analysis. Featuring z-score normalization and weighted MA integration, the ROCWMA delivers actionable trend signals with customizable thresholds.
--------------------------------------------------------------------------------------------------
⚙️ How It Works
1️⃣ Rate of Change (ROC) Normalization
The indicator begins with a normalized ROC calculation over a customizable length, transforming raw momentum data into a dynamic range for enhanced analysis.
2️⃣ Weighted Moving Average (MA)
A custom moving average (MA) is calculated using selectable MA types such as TEMA, SMA, EMA, and more. The normalized ROC is then applied as a weight to derive the ROC-Weighted MA (RWMA), blending trend and momentum data.
3️⃣ Z-Score Oscillator
The RWMA is normalized using z-score calculations, resulting in a smoothed oscillator. This process highlights deviations from the mean, identifying overbought and oversold conditions dynamically.
4️⃣ Threshold Logic
Bullish (Uptrend): Oscillator exceeds the positive threshold.
Bearish (Downtrend): Oscillator drops below the negative threshold.
Neutral: Oscillator remains between thresholds.
5️⃣ Dynamic Visual Representation
A color-coded histogram reflects trend strength and direction.
Optional candle coloring visually emphasizes trends on the chart.
Gradient fills enhance clarity of threshold areas.
--------------------------------------------------------------------------------------------------
✨ Customizable Settings
ROC Settings
Define the ROC length for momentum calculation.
MA Settings
Choose from multiple MA types (TEMA, EMA, SMA, etc.).
Customize the length and data source for MA calculations.
Adjust the signal length for smoothing.
Threshold Settings
Set neutral, bullish, and bearish thresholds to match your strategy.
Style Settings
Toggle candle coloring for visual trend enhancement.
Select from five unique color schemes to suit your chart style.
--------------------------------------------------------------------------------------------------
🚀 Features and Benefits
Momentum-Weighted Analysis: Combines ROC with advanced moving averages for precise trend evaluation.
Dynamic Thresholds: Z-score-based logic adapts to market conditions.
Visual Clarity: Color-coded histograms, candles, and gradient fills make trend detection intuitive.
Highly Customizable: Flexible inputs and multiple MA types ensure adaptability to various trading styles.
--------------------------------------------------------------------------------------------------
📜 Disclaimer
This indicator is for educational purposes only and does not constitute financial advice. Past performance is not indicative of future results. Users should consult a licensed financial advisor before making trading decisions. Use at your own risk.
--------------------------------------------------------------------------------------------------
Green/Red Candle Ratio - Ratiomizer V1.01🔥 Green/Red Candle Ratio Indicator 🔥
📊 Track Market Momentum Instantly!
🚀 Welcome to the Green/Red Candle Ratio Indicator! 🚀
This script dynamically calculates the ratio of green (bullish) vs. red (bearish) candles in your visible chart area, giving you a quick overview of market sentiment.
🛠 About This Script
⚡ Created with the help of ChatGPT – This is an early draft and open-source for everyone to use and improve!
⚠️ Short timeframe users (1min, 5min, etc.) – Be aware that too many candles can sometimes cause issues with calculations.
🔗 If you improve on this idea or use it in your own project, I’d love a little credit! 💙
📺 Follow My Trading Journey!
🎥 Live Trading, Insights & Market Analysis:
📌 YouTube → www.YouTube.com
📌 Kick → www.Kick.com
🙌 Support the content and join an awesome trading community!
💡 How to Use This Indicator
1️⃣ Apply it to your chart
2️⃣ See the real-time green/red candle ratio
3️⃣ Zoom in/out to dynamically adjust the calculations
4️⃣ Use it as an extra confirmation tool for trend momentum
💬 Feedback & improvements are welcome! If you run into issues or have ideas to make this script better, let me know in the community!
🔥 Happy Trading & Stay Profitable! 🔥 🏆
//@version=5
indicator("Green/Red Candle Ratio", overlay=true)
// Define the number of past bars to check (must be within TradingView limits)
maxBarsBack = math.min(500, bar_index) // Ensures we do not exceed available bars
// Initialize counters
greenCount = 0
redCount = 0
neutralCount = 0
totalBars = 0
// Loop through the last `maxBarsBack` bars
for i = 0 to maxBarsBack - 1
idx = bar_index - i
if idx >= 0
if close > open
greenCount := greenCount + 1
else if close < open
redCount := redCount + 1
else
neutralCount := neutralCount + 1
// Ensure only green + red candles contribute to the percentage calculation
validBars = greenCount + redCount
// Calculate ratios correctly so they always add up to 100%
greenRatio = validBars > 0 ? (greenCount / validBars) * 100 : na
redRatio = validBars > 0 ? (redCount / validBars) * 100 : na
// Create label text
labelText = "Green: " + str.tostring(greenRatio, "#.##") + "% Red: " + str.tostring(redRatio, "#.##")
labelColor = greenRatio > redRatio ? color.green : color.red
// Delete previous label before creating a new one
var label ratioLabel = na
if not na(ratioLabel)
label.delete(ratioLabel)
// Display only one label that updates dynamically
ratioLabel := label.new(bar_index, high, labelText, color=color.white, textcolor=labelColor, size=size.normal, style=label.style_label_down)
Dynamic EMA CrossoverThe Dynamic EMA Crossover indicator is designed to help traders identify trend transitions, visually understand market direction, and detect sideways consolidation zones. It simplifies decision-making by dynamically changing colors and highlighting areas of interest.
Key Features:
1. Dynamic EMA Crossovers:
• Uses two EMAs (default: 9 and 26 ) to identify bullish and bearish trends.
• EMAs and the area between them turn green during bullish trends and red during bearish trends for easy visualization.
2. Sideways Market Detection:
• Automatically detects periods of market consolidation when EMAs overlap for 10 consecutive candles and the price movement remains narrow.
• Sideways zones are highlighted with grey background, helping traders avoid false breakouts and trendless markets.
3. Customizable Inputs:
• Adjust the lengths of the two EMAs and the sensitivity of the overlap detection to match your trading style and market conditions.
How It Works:
• Trend Identification:
• When the shorter EMA crosses above the longer EMA, a bullish trend is indicated.
• When the shorter EMA crosses below the longer EMA, a bearish trend is indicated.
• The indicator dynamically adjusts the colors of the EMAs and fills the area between them for clear trend visibility.
• Sideways Market Detection:
• When the shorter EMA and longer EMA stay close (within a customizable sensitivity) for a fixed period (hardcoded to 10 candles), the indicator identifies a sideways market.
• This feature helps traders avoid entering trades during choppy or indecisive market conditions.
Who Is This For?
This indicator is ideal for:
• Trend traders looking for clear signals of trend direction.
• Swing traders who want to avoid trading in sideways markets.
• Scalpers who need quick and reliable visual cues for short-term market behavior.
Use Cases:
1. Bullish/Bearish Trends:
• Enter trades in the direction of the trend as the crossover occurs and colors change.
2. Sideways Zones:
• Avoid trades during periods of consolidation and wait for a clear breakout.
Mashup Logic:
This indicator combines:
1. EMA Crossovers:
• A tried-and-tested method for trend detection using two moving averages.
• Dynamic visual cues for bullish and bearish market phases.
2. Sideways Market Detection:
• Innovative logic to highlight sideways zones based on EMA overlap and price range analysis.
• Helps reduce noise and avoid trading during trendless periods.
3. Customization and Flexibility:
• Fully adjustable EMA lengths and overlap sensitivity to adapt to different markets and trading styles.
RSI Volatility Suppression Zones [BigBeluga]RSI Volatility Suppression Zones is an advanced indicator that identifies periods of suppressed RSI volatility and visualizes these suppression zones on the main chart. It also highlights breakout dynamics, giving traders actionable insights into potential market momentum.
🔵 Key Features:
Detection of Suppression Zones:
Identifies periods where RSI volatility is suppressed and marks these zones on the main price chart.
Breakout Visualization:
When the price breaks above the suppression zone, the box turns aqua, and an upward label is drawn to indicate a bullish breakout.
If the price breaks below the zone, the box turns purple, and a downward label is drawn for a bearish breakout.
Breakouts accompanied by a "+" label represent strong moves caused by short-lived, tight zones, signaling significant momentum.
Wave Labels for Consolidation:
If the suppression zone remains unbroken, a "wave" label is displayed within the gray box, signifying continued price stability within the range.
Gradient Intensity Below RSI:
A gradient strip below the RSI line increases in intensity based on the duration of the suppressed RSI volatility period.
This visual aid helps traders gauge how extended the low volatility phase is.
🔵 Usage:
Identify Breakouts: Use color-coded boxes and labels to detect breakouts and their direction, confirming potential trend continuation or reversals.
Evaluate Market Momentum: Leverage "+" labels for strong breakout signals caused by short suppression phases, indicating significant market moves.
Monitor Price Consolidation: Observe gray boxes and wave labels to understand ongoing consolidation phases.
Analyze RSI Behavior: Utilize the gradient strip to measure the longevity of suppressed volatility phases and anticipate breakout potential.
RSI Volatility Suppression Zones provides a powerful visual representation of RSI volatility suppression, breakout signals, and price consolidation, making it a must-have tool for traders seeking to anticipate market movements effectively.
Relative Risk MetricOVERVIEW
The Relative Risk Metric is designed to provide a relative measure of an asset's price, within a specified range, over a log scale.
PURPOSE
Relative Position Assessment: Visualizes where the current price stands within a user-defined range, adjusted for log scale.
Logarithmic Transformation: Utilizes the natural log to account for a log scale of prices, offering a more accurate representation of relative positions.
Calculation: The indicator calculates a normalized value via the function Relative Price = / log(UpperBound) − log(LowerBound) . The result is a value between 0 and 1, where 0 corresponds to the lower bound and 1 corresponds to the upper bound on a log scale.
VISUALIZATION
The indicator plots three series:
Risk Metric - a plot of the risk metric value that’s computed from an asset's relative price so that it lies within a logarithmic range between 0.0 & 1.0.
Smoothed Risk Metric - a plot of the risk metric that’s been smoothed.
Entry/Exit - a scatter plot for identified entry and exit. Values are expressed as percent and are coded as red being exit and green being entity. E.g., a red dot at 0.02 implies exit 2% of the held asset. A green dot at 0.01 implies use 1% of a designated capital reserve.
USAGE
Risk Metric
The risk metric transformation function has several parameters. These control aspects such as decay, sensitivity, bounds and time offset.
Decay - Acts as an exponent multiplier and controls how quickly dynamic bounds change as a function of the bar_index.
Time Offset - provides a centering effect of the exponential transformation relative to the current bar_index.
Sensitivity - controls how sensitive to time the dynamic bound adjustments should be.
Baseline control - Serves as an additive offset for dynamic bounds computation which ensures that bounds never become too small or negative.
UpperBound - provides headroom to accomodate growth an assets price from the baseline. For example, an upperbound of 3.5 accommodates a 3.5x growth from the baseline value (e.g., $100 -> $350).
LowerBound - provides log scale compression such that the overall metric provides meaningful insights for prices well below the average whilst avoiding extreme scaling. A lowerbound of 0.25 corresponds to a price that is approx one quarter of a normalised baseline in a log context.
Weighted Entry/Exit
This feature provides a weighted system for identifying DCA entry and exit. This weighting mechanism adjusts the metric's interpretation to highlight conditions based on dynamic thresholds and user-defined parameters to identify high-probability zones for entry/exit actions and provide risk-adjusted insights.
Weighting Parameters
The weighting function supports fine-tuning of the computed weighted entry/exit values
Base: determines the foundational multiplier for weighting the entry/exit value. A higher base amplifies the weighting effect, making the weighted values more pronounced. It acts as a scaling factor to control the overall magnitude of the weighting.
Exponent: adjusts the curve of the weighting function. Higher exponent values increase sensitivity, emphasizing differences between risk metric values near the entry or exit thresholds. This creates a steeper gradient for the computed entry/exit value making it more responsive to subtle shifts in risk levels.
Cut Off: specifies the maximum percentage (expressed as a fraction of 1.0) that the weighted entry/exit value can reach. This cap ensures the metric remains within a meaningful range and avoids skewing
Exit condition: Defines a threshold for exit. When the risk metric is below the exit threshold (but above the entry threshold) then entry/exit is neutral.
Entry condition: Defines a threshold for entry. When the risk metric is above the entry threshold (but below the exit threshold) then entry/exit is neutral.
Weighting Behaviour
For entry conditions - value is more heavily weighted as the metric approaches the entry threshold, emphasizing lower risk levels.
For exit conditions - value is more heavily weighted as the metric nears the exit threshold, emphasizing increased risk levels.
USE-CASES
Identifying potential overbought or oversold conditions within the specified logarithmic range.
Assisting in assessing how the current price compares to historical price levels on a logarithmic scale.
Guiding decision-making processes by providing insights into the relative positioning of prices within a log context
CONSIDERATIONS
Validation: It's recommended that backtesting over historical data be done before acting on any identified entry/exit values.
User Discretion: This indicator focus on price risk. Consider other risk factors and general market conditions as well.
lib_statemachine_modifiedLibrary "lib_statemachine_modified"
Modified to fix bugs and create getState and priorState methods.
method step(this, before, after, condition)
Namespace types: StateMachine
Parameters:
this (StateMachine)
before (int) : (int): Current state before transition
after (int) : (int): State to transition to
condition (bool) : (bool): Condition to trigger the transition
Returns: (bool): True if the state changed, else False
method step(this, after, condition)
Namespace types: StateMachine
Parameters:
this (StateMachine)
after (int) : (int): State to transition to
condition (bool) : (bool): Condition to trigger the transition
Returns: (bool): True if the state changed, else False
method currentState(this)
Namespace types: StateMachine
Parameters:
this (StateMachine)
method previousState(this)
Namespace types: StateMachine
Parameters:
this (StateMachine)
method changed(this, within_bars)
Namespace types: StateMachine
Parameters:
this (StateMachine)
within_bars (int) : (int): Number of bars to look back for a state change
Returns: (bool): True if a state change occurred within the timeframe, else False
method reset(this, condition, min_occurrences)
Namespace types: StateMachine
Parameters:
this (StateMachine)
condition (bool) : (bool): Condition to trigger the reset
min_occurrences (int) : (int): Minimum number of times the condition must be true to reset
Returns: (bool): True if the state was reset, else False
StateMachine
Fields:
state (series int)
neutral (series int)
enabled (series bool)
reset_counter (series int)
prior_state (series int)
last_change_bar (series int)
TASC 2025.02 Autocorrelation Indicator█ OVERVIEW
This script implements the Autocorrelation Indicator introduced by John Ehlers in the "Drunkard's Walk: Theory And Measurement By Autocorrelation" article from the February 2025 edition of TASC's Traders' Tips . The indicator calculates the autocorrelation of a price series across several lags to construct a periodogram , which traders can use to identify market cycles, trends, and potential reversal patterns.
█ CONCEPTS
Drunkard's walk
A drunkard's walk , formally known as a random walk , is a type of stochastic process that models the evolution of a system or variable through successive random steps.
In his article, John Ehlers relates this model to market data. He discusses two first- and second-order partial differential equations, modified for discrete (non-continuous) data, that can represent solutions to the discrete random walk problem: the diffusion equation and the wave equation. According to Ehlers, market data takes on a mixture of two "modes" described by these equations. He theorizes that when "diffusion mode" is dominant, trading success is almost a matter of luck, and when "wave mode" is dominant, indicators may have improved performance.
Pink spectrum
John Ehlers explains that many recent academic studies affirm that market data has a pink spectrum , meaning the power spectral density of the data is proportional to the wavelengths it contains, like pink noise . A random walk with a pink spectrum suggests that the states of the random variable are correlated and not independent. In other words, the random variable exhibits long-range dependence with respect to previous states.
Autocorrelation function (ACF)
Autocorrelation measures the correlation of a time series with a delayed copy, or lag , of itself. The autocorrelation function (ACF) is a method that evaluates autocorrelation across a range of lags , which can help to identify patterns, trends, and cycles in stochastic market data. Analysts often use ACF to detect and characterize long-range dependence in a time series.
The Autocorrelation Indicator evaluates the ACF of market prices over a fixed range of lags, expressing the results as a color-coded heatmap representing a dynamic periodogram. Ehlers suggests the information from the periodogram can help traders identify different market behaviors, including:
Cycles : Distinguishable as repeated patterns in the periodogram.
Reversals : Indicated by sharp vertical changes in the periodogram when the indicator uses a short data length .
Trends : Indicated by increasing correlation across lags, starting with the shortest, over time.
█ USAGE
This script calculates the Autocorrelation Indicator on an input "Source" series, smoothed by Ehlers' UltimateSmoother filter, and plots several color-coded lines to represent the periodogram's information. Each line corresponds to an analyzed lag, with the shortest lag's line at the bottom of the pane. Green hues in the line indicate a positive correlation for the lag, red hues indicate a negative correlation (anticorrelation), and orange or yellow hues mean the correlation is near zero.
Because Pine has a limit on the number of plots for a single indicator, this script divides the periodogram display into three distinct ranges that cover different lags. To see the full periodogram, add three instances of this script to the chart and set the "Lag range" input for each to a different value, as demonstrated in the chart above.
With a modest autocorrelation length, such as 20 on a "1D" chart, traders can identify seasonal patterns in the price series, which can help to pinpoint cycles and moderate trends. For instance, on the daily ES1! chart above, the indicator shows repetitive, similar patterns through fall 2023 and winter 2023-2024. The green "triangular" shape rising from the zero lag baseline over different time ranges corresponds to seasonal trends in the data.
To identify turning points in the price series, Ehlers recommends using a short autocorrelation length, such as 2. With this length, users can observe sharp, sudden shifts along the vertical axis, which suggest potential turning points from upward to downward or vice versa.
Ehlers Maclaurin Ultimate Smoother [CT]Ehlers Maclaurin Ultimate Smoother
Introduction
The Ehlers Maclaurin Ultimate Smoother is an innovative enhancement of the classic Ehlers SuperSmoother. By leveraging advanced Maclaurin series approximations, this indicator offers superior market analysis and signal generation.
The indicator combines Ehlers' Ultimate Smoother with Maclaurin series approximations to create a more efficient and accurate smoothing mechanism:
Input price data passes through the initial smoothing phase
Maclaurin series approximates trigonometric functions
Enhanced high-pass filter removes market noise
Final smoothing phase produces the output signal
Why the Maclaurin Approach?
The Maclaurin series is a special form of the Taylor series, centered around 0. It provides an efficient way to approximate complex functions using polynomial terms. In this indicator, we use the Maclaurin approach to improve the sine and cosine functions, resulting in:
Faster Calculations: By using polynomial approximations, we significantly reduce computational complexity.
Improved Stability: The approximation provides a more stable numerical basis for calculations.
Preservation of Precision: Despite the approximation, we maintain the precision needed for price smoothing.
Calculations
The indicator employs several key mathematical components:
Maclaurin Series Approximation:
sin(x) ≈ x - x³/3! + x⁵/5! - x⁷/7! + x⁹/9!
cos(x) ≈ 1 - x²/2! + x⁴/4! - x⁶/6! + x⁸/8!
Smoothing Algorithm:
Uses exponential smoothing with optimized coefficients
Implements high-pass filtering for noise reduction
Applies dynamic weighting based on market conditions
Mathematical Foundation
Utilizes Maclaurin series for trigonometric approximation
Implements Ehlers' smoothing principles
Incorporates advanced filtering techniques
Technical Advantages
Signal Processing:
Lag Reduction: Faster signal detection with less delay.
Noise Filtration: Effective elimination of high-frequency noise.
Precision Enhancement: Preservation of critical price movements.
Adaptive Processing: Dynamic response to market volatility.
Visual Enhancements:
Smart color intensity mapping.
Real-time visualization of trend strength.
Adaptive opacity based on movement significance.
Implementation
Core Configuration:
Plot Type: Choose between the original and the Maclaurin enhanced version.
Length: Default set to 30, optimal for daily timeframes.
hpLength: Default set to 10 for enhanced noise reduction.
Advanced Parameters:
The indicator offers advanced control with:
Dual processing modes (Original/Maclaurin).
Dynamic color intensity system.
Customizable smoothing parameters.
Professional Analysis Tools:
Accurate trend reversal identification.
Advanced support/resistance detection.
Superior performance in volatile markets.
Technical Specifications
Maclaurin Series Implementation:
The indicator employs a 5-term Maclaurin series approximation for both sine and cosine, ensuring efficient and accurate computation.
Performance Metrics
Improved processing efficiency.
Reduced memory utilization.
Increased signal accuracy.
Licensing & Attribution
© 2024 Mupsje aka CasaTropical
Professional Credits
Original Ultimate and SuperSmoother concept: John F. Ehlers
Maclaurin enhancement: Casa Tropical (CT)
www.mathsisfun.com
Trend Map For TradersThis indicator maps out EMAs of various lengths into a visual map and allows you to configure the map's sensitivity with two simple settings. The color scheme is straightforward: observe the colors from top to bottom. The top represents the short-term trend, while the bottom reflects the long-term trend. Overall, the map provides a visual overview of the current short- and long-term trends. Simple but effective.
NIFTY BANKNIFTY MIDCAP SENSEX FINNIFTY LEVELS)this indicator uses Gann's methods which are based on the idea that markets move in predictable geometric patterns and are influenced by time and price.
Key Concepts of Gann Levels:
Gann Angles:
Gann believed that specific angles could indicate the trend of a market. The most notable is the 45-degree angle, which he called the "1x1" or "45-degree line."
Angles are drawn from a significant price point, such as a high or low, and represent the speed or slope of the price movement.
Gann Square of 9:
A mathematical tool that calculates support and resistance levels based on the square root of numbers and their geometric relationships.
It aligns numbers in a spiral format, starting from a central point, and helps identify key price levels at certain degrees.
Gann Fan:
A series of lines drawn at specific angles from a significant high or low. Common angles include 1x1 (45°), 2x1 (26.25°), and 1x2 (63.75°).
These angles help traders identify potential areas where the trend might accelerate, decelerate, or reverse.
Gann Retracements:
Levels based on key price ratios derived from natural laws and geometric principles. Common Gann retracement levels include 12.5%, 25%, 50%, and 75%.
Time Analysis:
Gann emphasized the importance of time cycles. He believed markets move in time-based patterns, such as yearly cycles, seasonal cycles, or specific time intervals.
MCDX_SignalThe MCDX indicator (Market Cycle Dynamic Index) is a technical indicator developed by Trung Pham. It is a tool used for analyzing the stock market, often utilized to identify big money flow (Big Money) and evaluate the strength of individual stocks or the overall market.
MCDX is known for its distinctive histogram chart with red and green bars. The red bars typically represent the inflow of big money, while the green bars indicate small money flow or outflows.
Volume Surge Webhook AlertThis TradingView indicator, named "Volume Surge Webhook Alert," is designed to find significant increases in trading volume and send out alerts with key information. It works by looking back at the volume over a certain number of past candlesticks, which you can set using the "Lookback Period" input. The indicator calculates the average volume during this period. Then, it sets a threshold for what counts as a "volume surge." This threshold is a percentage increase over the average volume, and you can adjust this percentage using the "Volume Surge Threshold (%)" input.
When the current candlestick's volume is higher than this threshold, the indicator considers it a volume surge. To help you see this visually, the indicator plots three lines on a separate chart: the average volume (in blue), the current volume (in red), and the threshold volume (in gray circles).
If a volume surge happens, the indicator creates a webhook alert. This alert sends a message in a structured format (like a digital envelope) that contains the following information: the symbol of the stock or cryptocurrency, the timeframe of the chart you're looking at, the current volume, the average volume, the threshold volume, and a simple message saying a volume surge was detected. This alert is sent only once when the candlestick closes with a volume surge.
Additionally, when a volume surge is detected, a small red exclamation mark "!" will appear above that candlestick on the main price chart.
Essentially, this indicator helps traders spot times when trading volume is unusually high, which can sometimes be a sign of important price movements. You can customize how sensitive the indicator is by changing the "Lookback Period" and the "Volume Surge Threshold (%)". The webhook alerts allow you to be notified automatically when these surges occur, so you don't have to constantly watch the charts.
BK Multiple MA, RMA, SMA, HMA, VWAP, Rolling VWAP **Indicator Description**
I’m incredibly proud to introduce my third indicator to the TradingView community: **BK Multiple MA with HMA, VWAP, and Rolling VWAP**! This tool has been a game-changer in my trading strategy, and I’m excited to share it with others who are navigating the markets.
This indicator holds a special place in my heart because it represents the first technical analysis concept introduced to me by my mentor when I began apprenticing under him. His wisdom, guidance, and passion for trading—and for life—left an indelible mark on my journey. I dedicate this work, and every indicator I introduce, to the foundation he helped me build, while giving glory first and foremost to God.
**Moving Averages (MAs)** are one of the most widely used tools in technical analysis, and this indicator takes them to the next level. It allows you to plot **six fully customizable moving averages simultaneously**, with options including:
- **Exponential Moving Average (EMA)**
- **Simple Moving Average (SMA)**
- **Relative Moving Average (RMA)**
- **Hull Moving Average (HMA)**
- **Volume Weighted Average Price (VWAP)**
- **Rolling VWAP**
This flexibility makes the indicator highly versatile, whether you’re a day trader, swing trader, or long-term investor. By customizing periods, colors, and line widths for each MA, you can tailor the indicator to perfectly suit your trading style.
**Key Features**
1. **Six Fully Customizable MAs**:
- Adjust periods, line colors, and widths to match your preferences.
- Select from EMA, SMA, RMA, HMA, VWAP, or Rolling VWAP for each line.
2. **Unique Rolling VWAP Option**:
- Rolling VWAP calculates the volume-weighted average price over a user-defined period, such as 200 candles.
- This feature is ideal for traders seeking volume-weighted levels that don’t reset with each session, making it invaluable for trend-following and swing trading.
3. **HMA for Smoother Trends**:
- The Hull Moving Average (HMA) is designed to reduce lag and provide a responsive, noise-free view of price trends.
- It’s a powerful tool for spotting reversals and confirming directional momentum.
4. **Session VWAP**:
- Traditional VWAP resets with each trading session, making it a reliable benchmark for intraday support and resistance levels.
**How It Works**
- **VWAP**: Reflects the average price weighted by volume for the current trading session, commonly used by institutional traders to identify key price levels.
- **Rolling VWAP**: Extends VWAP functionality by calculating over a user-defined period, allowing for flexible multi-timeframe analysis.
- **HMA**: A fast, smooth moving average that reacts quickly to price changes while filtering out noise.
The combination of these options provides traders with a comprehensive view of market dynamics, enabling better decision-making.
**Final Thoughts**
This indicator is deeply meaningful to me because it represents the first concept my mentor introduced when I began apprenticing under him. His wisdom, guidance, and passion for trading—and for life—left an indelible mark on my journey. I dedicate this work, and every indicator I introduce, to the foundation he helped me build, while giving glory first and foremost to God.
If this indicator helps you succeed, I humbly ask that you honor the blessings in your life by giving back—whether through acts of kindness, philanthropy, or helping others in need.
May the Almighty guide us all toward wisdom and success in our endeavors. All glory belongs to God!
Inside Bar/Outside Bar/Mother Bar Box By SmartTrader888This Indicator shows:
1. Inside Bar
2. Outside Bar
3. Mother Bar box (Box the mother bar and all subsequent inside bars)
This indicator handles correctly the edge conditions such as:
1. bar close = bar open
2. current bar low equals to mother bar low or current bar high equals mother bar high
Smart Moving AveragesSmart Moving Averages analyzes the dynamic interplay between price action and multiple moving averages to identify high-probability support and resistance zones.
The script's distinguishing features include:
Bounce detection that filters out noise by requiring specific penetration thresholds (0.1-1.5%), helping traders identify genuine support tests versus false signals
Real-time MA clustering analysis that reveals zones where multiple moving averages converge, indicating potentially stronger support/resistance levels
Statistical tracking of bounce success rates for each MA, allowing traders to identify which moving averages are most reliable for the current market conditions
Power bounce detection that combines EMA spread analysis with trend confirmation, highlighting especially strong bullish setups
Visual stack status system that instantly communicates market health through an intuitive color-coded display showing how many MAs are below price
The script helps traders make more informed decisions by quantifying the historical reliability of different moving averages while providing real-time analysis of MA interactions with price. This systematic approach moves beyond simple MA crossovers to identify higher probability trading opportunities.
Lost Bar Locator v1 [Yaphott]Lost Bar Locator v1 helps you locate missing data on your chart.
It does this by looking for consecutive bars that have a delta time greater than the current interval.
Two lines are drawn for each group of one or more missing bars:
Bar before the missing bar(s).
Bar after the missing bar(s).
Dividend Payout RatioShows the dividend payout ratio for the specific stock.
The dividend payout ratio indicates if the dividend payout is sustainable in the long run. Therefore,
1. A dividend payout under 50% is considered sustainable. The line will be green
2. A dividend payout over 50% and under 100%, the line will be yellow, is considered a stock to investigate since the dividend payout may have to be cut in the future which will cause the stock price to crash.
3. A dividend payout over 100%, the line will be red, is considered unsustainable and the dividend payout will most likely be cut in the near future. It can take up to a few years for the dividend cut to happen if the financials do not improve.
If the dividend payout ratio is over 100%, this means that the company is paying a dividend amount over $1 for every $1 earned. Therefore, the company must borrow money or find another source to pay the dividend amount that the company cannot afford to pay with the current earnings.
Calculating the dividend payout ratio:
Divide dividend paid by earnings after tax and multiplying the result by 100%.
OHLC/4 Daily vs Quarterly CrossOHLC/4 Daily vs Quarterly Cross
The "OHLC/4 Daily vs Quarterly Cross" indicator is a powerful tool designed to provide traders with insights into trend alignment and potential market turning points. By calculating the average of the open, high, low, and close prices (OHLC/4), this script compares the daily average price action with the quarterly average to identify significant crossover events.
This indicator features two distinct lines: the Daily OHLC/4 and the Quarterly OHLC/4, each plotted in different colors for easy differentiation. A crossover occurs when the daily OHLC/4 moves above the quarterly average, potentially signaling bullish momentum or a shift in market direction. Conversely, a crossunder marks the daily OHLC/4 moving below the quarterly level, indicating potential bearish sentiment or a reversal.
With real-time plotting and built-in alert conditions, this script enables traders to stay ahead of critical market movements by setting automated notifications for crossover events. Whether you're seeking to confirm trends or identify new opportunities, the "OHLC/4 Daily vs Quarterly Cross" delivers clarity and actionable insights for more informed decision-making.