Custom Ratio IndicatorThis indicator allows users to compare the price ratio of two customizable trading pairs. By dividing the closing price of the first trading pair by the second, it calculates and plots the resulting ratio on the chart. It is designed for traders who want to analyze correlations or relative performance between two assets. The default pairs are ETHUSDT and BTCUSDT, and users can customize these inputs. The indicator supports high precision to ensure accurate representation of small or large ratios. Additionally, the current ratio is dynamically displayed on the chart for easy reference.
אינדיקטורים ואסטרטגיות
Previous Day and Current Day High/LowKey Features:
Previous Day High and Low Lines:
Displays the high (PDH) and low (PDL) levels of the previous trading day.
Allows customization of line colors, styles (solid, dashed, or dotted), and widths.
Extends these lines by a specified number of candles into the current day for better visualization.
Current Day High and Low Lines:
Displays the high (CDH) and low (CDL) levels during the current day's regular trading hours.
Customizable line attributes, including color, style, width, and extension length.
Customizable Input Options:
User-configurable settings for both the previous and current day high/low lines, grouped under respective sections for clarity.
Regular trading hours can be defined manually (default is 9:30 AM to 4:00 PM).
Ability to toggle the visibility of the lines for both the previous and current days.
Automatic Reset at the Start of a New Day:
Captures the high and low values of the completed day and resets for the new day.
Deletes old lines and labels to ensure clarity and avoid overlap.
Dynamic Updates:
Updates the current day's high and low lines and labels as new data comes in.
Adjusts previous day lines dynamically based on the user-defined number of candles to extend.
Session-Based Filtering:
Ensures the calculations and updates are restricted to the defined regular trading hours.
Code Logic:
Input Groups: The script uses grouped inputs to allow users to configure settings for previous and current day levels separately.
Line and Label Management: It creates and deletes lines and labels dynamically to prevent clutter and keep the chart organized.
Session Check: Uses the session input to determine if a bar falls within regular trading hours.
High/Low Calculation: Tracks the high and low for both the previous and current days during regular trading hours.
New Day Detection: Identifies the start of a new trading day to update previous day values and reset current day variables.
Applications:
Intraday Trading: Helps traders identify critical support and resistance levels from the previous and current days.
Trend Analysis: Provides visual cues for price movement trends across consecutive days.
Custom Visualization: With extensive customization options, traders can adapt the indicator to suit their trading style and chart aesthetics.
This script is highly configurable, making it versatile for a wide range of trading strategies and styles.
Advanced MVRV Trend AnalyzerThe "Advanced MVRV Trend Analyzer" is a sophisticated trading tool designed for the TradingView platform that enhances traditional Market Value to Realized Value (MVRV) analysis. It provides a multi-timeframe perspective of market valuation dynamics by comparing the current market price to the realized price across short-term, mid-term, and long-term cohorts. This indicator is particularly useful for cryptocurrency traders and investors who seek deeper insights into potential overvaluation or undervaluation conditions in the market.
Key Features
Multiple Timeframes:
Analyzes market conditions across three distinct timeframes: short-term (14 days), mid-term (50 days), and long-term (200 days).
Moving Averages: Includes moving averages for each MVRV ratio to smooth out short-term fluctuations and highlight longer-term trends.
Dynamic Thresholds: Provides dynamic color-coded backgrounds that highlight overvalued and undervalued market conditions based on predefined thresholds.
How to Use
Adding the Indicator:
Open your TradingView chart.
Click on "Indicators" at the top of your screen.
Search for "Advanced MVRV Trend Analyzer" and add it to your chart.
Interpreting the Indicator:
MVRV Lines: Each of the three MVRV lines (short-term, mid-term, long-term) reflects how much higher or lower the current market price is compared to the average price at which coins were last moved. A value above 1 indicates that the current price is higher than the realized price, suggesting overvaluation. Conversely, a value below 1 suggests undervaluation.
Moving Averages: The moving averages of the MVRV ratios help identify the underlying trend. If the MVRV line deviates significantly from its moving average, it might indicate a potential reversal or continuation of the current trend.
Color-coded Backgrounds:
Red background indicates an overvalued condition where the MVRV ratio exceeds 1.5, suggesting caution as the market may be overheated.
Green background indicates an undervalued condition where the MVRV ratio is below 0.5, potentially signaling a buying opportunity.
Trading Strategies:
Overvalued Zones: Consider taking profits or setting stop-loss orders when the indicator shows a prolonged red background, especially if supported by other bearish signals.
Undervalued Zones: Look for buying opportunities when the indicator shows a prolonged green background, especially if other bullish signals are present.
Combining with Other Indicators:
Enhance your analysis by combining the "Advanced MVRV Trend Analyzer" with other technical indicators such as RSI, MACD, or volume-based tools to confirm trends and signals.
Conclusion
The "Advanced MVRV Trend Analyzer" offers a nuanced view of market dynamics, providing traders with valuable insights into when a market may be approaching extremes. By utilizing this indicator, traders can better time their entries and exits, manage risk, and align their strategies with underlying market trends.
MegaGas Bollinger Bands with Divergence and Circle SignalsIndicator: MegaGas Bollinger Bands with Divergence and Circle Signals
This script provides a powerful combination of Bollinger Bands, RSI Divergence detection, and signal visualization tools. Designed with flexibility and precision in mind, it aims to assist traders in identifying trend reversals, volatility zones, and divergence-based trading opportunities. The script is well-suited for swing trading, momentum trading, and even scalping when adapted to lower timeframes.
How It Works:
Bollinger Bands:
Bollinger Bands are used to detect price volatility and overbought/oversold conditions. The script calculates:
Basis Line: A 34-period Simple Moving Average (SMA) as the core trend line.
Upper Bands: Bands positioned 1x and 2x the standard deviation above the SMA.
Lower Bands: Bands positioned 1x and 2x the standard deviation below the SMA. These levels provide dynamic support and resistance zones, highlighting breakout and reversion opportunities.
RSI Divergence Detection:
The indicator detects bullish divergence (when RSI forms a higher low while price forms a lower low) and bearish divergence (when RSI forms a lower high while price forms a higher high). These divergences often precede significant reversals or momentum shifts.
Bullish divergence is displayed with blue triangles (up).
Bearish divergence is displayed with orange triangles (down).
Buy and Sell Signals:
Circle Signals are generated when price crosses key Bollinger Bands levels:
A green circle appears when the price crosses above the lower band (potential buy signal).
A red circle appears when the price crosses below the upper band (potential sell signal).
These signals help identify potential entry and exit points for trades, particularly in trend-following or mean-reversion strategies.
Trend Reference (Moving Average):
A 50-period Simple Moving Average (SMA) is included as a trend reference, helping traders gauge the overall market direction. Use this to confirm divergence signals and avoid trades against the prevailing trend.
Why This Indicator Is Unique:
This script integrates multiple tools in a meaningful way, emphasizing contextual trading signals. Unlike standalone Bollinger Bands or RSI indicators, it introduces:
Advanced Divergence Analysis: Enhancing traditional RSI with divergence-based alerts.
Dynamic Signal Filtering: Preventing repetitive signals by introducing state-based logic for circles and divergence signals.
Trend Alignment: Combining Bollinger Bands with an SMA to filter trades based on the prevailing trend.
How to Use:
Setup:
Apply the indicator to any chart and timeframe. For swing trading, higher timeframes like 4H or 1D are recommended.
Adjust the RSI, Bollinger Bands, and Moving Average lengths to match your strategy and asset.
Signals:
Look for divergence signals (triangles) as early warnings of trend reversals. Confirm these with price action or other tools.
Use circle signals (green/red) to time potential entries/exits around Bollinger Band extremes.
Confirmation:
Combine divergence and circle signals with the SMA line to avoid counter-trend trades. For example, take bullish signals when the price is above the SMA and bearish signals when it is below.
Chart Clarity:
The script is published with a clean chart for clarity. It visualizes all signals with distinct shapes (triangles and circles) and colors, ensuring they are easily recognizable. Bollinger Bands and the SMA are plotted with transparency to avoid clutter.
Originality:
This script is a thoughtful blend of Bollinger Bands and RSI divergence detection, carefully designed to provide traders with actionable insights. It introduces state-based logic to manage repetitive signals and seamlessly integrates trend filtering, making it a valuable tool for both novice and experienced traders.
XAUUSD Weekly Gap Indicator (oberlunar)The XAUUSD Weekly Gap Indicator is a technical tool designed specifically for tracking weekly price gaps in the XAUUSD (gold) market. It identifies and visualizes the price difference between the Friday close and the Monday open, providing valuable insights into market dynamics over the weekend.
Gap Detection:
Measures the price difference between Friday's closing price and Monday's opening price.
Highlights whether the gap is bullish (Monday opens above Friday’s close) or bearish (Monday opens below Friday’s close).
Visualization:
Draws a line or rectangle to connect the Friday close and the Monday open, clearly marking the gap on the chart.
Displays an indicator label with the gap value, often in pips or points, to quantify the gap size.
Color Coding:
Green: Bullish gap (positive price movement).
Red: Bearish gap (negative price movement).
Market Sentiment:
Large gaps can indicate significant market sentiment shifts due to weekend events, such as economic reports or geopolitical news.
Support and Resistance:
Weekly gaps often act as temporary support or resistance levels, as the market may attempt to revisit or "fill" the gap.
Trading Strategies:
Gap Filling: XAUUSD often tends to "fill" these gaps, providing trading opportunities.
Continuation or Reversal: The reaction to the gap can signal whether the trend is likely to continue or reverse.
McRib Bull Market Indicator# McRib Bull Market Indicator
## Overview
The McRib Bull Market Indicator is a unique technical analysis tool that marks McDonald's McRib sandwich release dates on your trading charts. While seemingly unconventional, this indicator serves as a fascinating historical reference point for market analysis, particularly for studying periods of market expansion.
## Key Features
- Visual yellow labels marking verified McRib release dates from 2012 to 2024
- Clean, unobtrusive design that overlays on any chart timeframe
- Covers both U.S. and international releases (including UK and Australia)
## Historical Reference Points
The indicator includes release dates from:
- December 2012
- October-December 2014
- January 2015
- October 2016
- November 2017
- October 2018
- October 2019
- December 2020
- October 2022
- November 2023
- December 2024
## Usage Guide
1. Add the indicator to any chart by searching for "McRib Bull Market Indicator"
2. The indicator will automatically display yellow labels above price candles on McRib release dates
3. Use these reference points to:
- Analyze market conditions during McRib releases
- Study potential correlations between releases and market movements
- Compare market behavior across different McRib release periods
- Identify any patterns in market expansion phases coinciding with releases
## Trading Application
While initially created as a novelty indicator, it can be used to:
- Mark specific historical points of reference for broader market analysis
- Study potential market psychology around major promotional events
- Compare seasonal market patterns with recurring release dates
- Analyze market expansion phases that coincide with releases
Remember: While this indicator provides interesting historical reference points, it should be used as part of a comprehensive trading strategy rather than as a standalone trading signal.
TICKFLOW_FUTURES-ATR-ZONESThe TICKFLOW_FUTURES-ATR-ZONES script is a dynamic indicator designed to help traders identify key zones of price action based on ATR (Average True Range) and Bollinger Bands. This script combines customizable moving averages, volatility-based bands, and trend slope calculations to provide a clear visual framework for analyzing trends, detecting potential reversals, and identifying high-probability buy/sell zones.
Key Features:
Dynamic ATR Zones:
Upper and lower bands are calculated using ATR and adjusted dynamically based on the visible price range, ensuring alignment with current market conditions.
Slope-Based Color Coding:
The middle line (moving average) dynamically changes its color based on the slope to indicate bullish, bearish, or neutral trends.
Bollinger Band Squeeze Detection:
Highlights periods of price contraction using Bollinger Band width, helping identify potential breakout setups.
Buy and Sell Signals:
Displays visual markers (BUY/SELL) based on slope changes and price action relative to the dynamic middle line.
Customizable Inputs:
Includes options to adjust ATR multiplier, Bollinger Band settings, moving average type, slope lookback period, and color preferences.
Visual Zones:
Shaded areas representing ATR-based upper and lower zones for a clear and intuitive price action framework.
Usage Instructions:
Clean Chart:
Use the script on a clean chart for best results. This ensures that the plotted zones, lines, and markers are easily interpretable without interference.
Understanding the Components:
The middle line represents the selected moving average type, providing the directional bias.
Upper and lower zones indicate potential reversal or continuation levels based on ATR.
BUY/SELL markers suggest trend initiation points but should be confirmed with additional analysis.
Customization:
Adjust input parameters (e.g., ATR multiplier, Bollinger Band settings) to fit your trading style and market conditions.
Important Notes:
This script works as a standalone tool and does not require other indicators to function.
Avoid using it with additional scripts on the same chart unless explicitly needed and described in your analysis.
4-Hour Moving AveragesTitle: 4-Hour Moving Averages Indicator
Description:
The "4-Hour Moving Averages" indicator is designed to help traders easily visualize key moving averages derived from the 4-hour timeframe, regardless of the chart interval they are using. This indicator plots four moving averages: a 15-period SMA (Short-Term), a 35-period SMA (Intermediate-Term), an 80-period SMA (Long-Term), and a 130-period SMA (Confirmation).
These moving averages provide a balanced approach for identifying short, medium, and long-term trends, as well as confirming significant market movements. Ideal for swing traders and those looking for clear trend signals, the indicator can be used for various markets, including stocks, forex, and cryptocurrencies.
The 4-hour moving averages overlay directly on the price chart, allowing for easy analysis of current price movements relative to important trend indicators. Use this script to enhance your trading decisions, identify opportunities, and avoid market traps by relying on consistent moving average trends.
Features:
- 15 SMA for Short-Term Trends (in red)
- 35 SMA for Intermediate-Term Trends (in orange)
- 80 SMA for Long-Term Trends (in green)
- 130 SMA for Confirmation (in blue)
Feel free to modify the settings to suit your specific strategy and market conditions.
Sri Yantra MTF - AynetSri Yantra MTF - Aynet Script Overview
This Pine Script generates a Sri Yantra-inspired geometric pattern overlay on price charts. The pattern is dynamically updated based on multi-timeframe (MTF) inputs, utilizing high and low price ranges, and adjusting its size relative to a chosen multiplier.
The Sri Yantra is a sacred geometric figure used in various spiritual and mathematical contexts, symbolizing the interconnectedness of the universe. Here, it is applied to visualize structured price levels.
Scientific and Technical Explanation
Multi-Timeframe Integration:
Base Timeframe (baseRes): This is the primary timeframe for the analysis. The opening price and ATR (Average True Range) are calculated from this timeframe.
Pattern Timeframe (patternRes): Defines the granularity of the pattern. It ensures synchronization with price movements on specific time intervals.
Geometric Construction:
ATR-Based Scaling: The script uses ATR as a volatility measure to dynamically size the geometric pattern. The sizeMult input scales the pattern relative to price volatility.
Pattern Width (barOffset): Defines the horizontal extent of the pattern in terms of bars. This ensures the pattern is aligned with price movements and scales appropriately.
Sri Yantra-Like Geometry:
Outer Square: A bounding box is drawn around the price level.
Triangles: Multiple layers of triangles (primary, secondary, and tertiary) are calculated and drawn to mimic the structure of the Sri Yantra. These triangles converge and diverge based on price levels.
Horizontal Lines: Added at key levels to provide additional structure and aesthetic alignment.
Dynamic Updates:
The pattern recalculates and redraws itself on the last bar of the selected timeframe, ensuring it adapts to real-time price data.
A built-in check identifies new bars in the chosen timeframe (patternRes), ensuring accurate updates.
Information Table:
Displays the selected base and pattern timeframes in a table format on the top-right corner of the chart.
Allows traders to see the active settings for quick adjustments.
Key Inputs
Style Settings:
Pattern Color: Customize the color of the geometric patterns.
Size Multiplier (sizeMult): Adjusts the size of the pattern relative to price movements.
Line Width: Controls the thickness of the geometric lines.
Timeframe Settings:
Base Resolution (baseRes): Timeframe for calculating the pattern's anchor (default: daily).
Pattern Resolution (patternRes): Timeframe granularity for the pattern’s formation.
Geometric Adjustments:
Pattern Width (barOffset): Horizontal width in bars.
ATR Multiplier (rangeSize): Vertical size adjustment based on price volatility.
Scientific Concepts
Volatility Representation:
ATR (Average True Range): A standard measure of market volatility, representing the average range of price movements over a defined period. Here, ATR adjusts the vertical height of the geometric figures.
Geometric Symmetry:
The script emulates symmetry similar to the Sri Yantra, aligning with the principles of sacred geometry, which often appear in nature and mathematical constructs. Symmetry in financial data visualizations can aid in intuitive interpretation of price movements.
Multi-Timeframe Fusion:
Synchronizing patterns with multiple timeframes enhances the relevance of overlays for different trading strategies. For example, daily trends combined with hourly patterns can help traders optimize entries and exits.
Visual Features
Outer Square:
Drawn to encapsulate the geometric structure.
Represents the broader context of price levels.
Triangles:
Three layers of interlocking triangles create a fractal pattern, providing a visual alignment to price dynamics.
Horizontal Lines:
Emphasize critical levels within the pattern, offering visual cues for potential support or resistance areas.
Information Table:
Displays the active timeframe settings, helping traders quickly verify configurations.
Applications
Trend Visualization:
Patterns overlay on price movements provide a clearer view of trend direction and potential reversals.
Volatility Mapping:
ATR-based scaling ensures the pattern adjusts to varying market conditions, making it suitable for different asset classes and trading strategies.
Multi-Timeframe Analysis:
Integrates higher and lower timeframes, enabling traders to spot confluences between short-term and long-term price levels.
Potential Enhancements
Add Fibonacci Levels: Overlay Fibonacci retracements within the pattern for deeper price level insights.
Dynamic Alerts: Include alert conditions when price intersects key geometric lines.
Custom Labels: Add text descriptions for critical intersections or triangle centers.
This script is a unique blend of technical analysis and sacred geometry, providing traders with an innovative way to visualize market dynamics.
Adaptive Moving AveragesThe Adaptive Moving Averages indicator stands out with several unique features that set it apart from traditional moving average indicators. Its most remarkable characteristic is the ability to automatically adjust the length of moving averages based on the chosen timeframe. This ensures consistency in analysis regardless of the time scale used, eliminating the need for manual recalculation of appropriate periods for each timeframe. It allows for a more fluid and accurate multi-temporal analysis.
Another innovative aspect is the indicator's consideration of different market types (stocks, forex, crypto). This approach recognizes the fundamental differences between these markets in terms of trading hours, allowing for more precise and representative calculations for each asset class. It offers increased flexibility for traders operating across various markets.
The method for calculating periods for different moving averages (week, month, quarter, semester, year) is particularly sophisticated. It takes into account the specifics of each market, such as trading days and opening hours, automatically adapting to timeframe changes. This ensures a more accurate representation of actual trading periods rather than arbitrary approximations.
The indicator offers a wide choice of moving average types, allowing traders to use their preferred method or compare different approaches. This flexibility adapts to various trading styles and technical analysis strategies, offering the possibility to experiment and find the most effective combination for each market or asset.
In conclusion, this indicator distinguishes itself through its ability to intelligently adapt to different trading contexts, offering a versatile and sophisticated solution for technical analysis. Its flexibility and adaptive approach make it a particularly interesting tool for traders seeking consistent analysis across different markets and time scales.
GaussianDistributionLibrary "GaussianDistribution"
This library defines a custom type `distr` representing a Gaussian (or other statistical) distribution.
It provides methods to calculate key statistical moments and scores, including mean, median, mode, standard deviation, variance, skewness, kurtosis, and Z-scores.
This library is useful for analyzing probability distributions in financial data.
Disclaimer:
I am not a mathematician, but I have implemented this library to the best of my understanding and capacity. Please be indulgent as I tried to translate statistical concepts into code as accurately as possible. Feedback, suggestions, and corrections are welcome to improve the reliability and robustness of this library.
mean(source, length)
Calculate the mean (average) of the distribution
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
Returns: Mean (μ)
stdev(source, length)
Calculate the standard deviation (σ) of the distribution
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
Returns: Standard deviation (σ)
skewness(source, length, mean, stdev)
Calculate the skewness (γ₁) of the distribution
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
mean (float) : the mean (average) of the distribution
stdev (float) : the standard deviation (σ) of the distribution
@return Skewness (γ₁)
skewness(source, length)
Overloaded skewness to calculate from source and length
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Skewness (γ₁)
mode(mean, stdev, skewness)
Estimate mode - Most frequent value in the distribution (approximation based on skewness)
Parameters:
mean (float) : the mean (average) of the distribution
stdev (float) : the standard deviation (σ) of the distribution
skewness (float) : the skewness (γ₁) of the distribution
@return Mode
mode(source, length)
Overloaded mode to calculate from source and length
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Mode
median(mean, stdev, skewness)
Estimate median - Middle value of the distribution (approximation)
Parameters:
mean (float) : the mean (average) of the distribution
stdev (float) : the standard deviation (σ) of the distribution
skewness (float) : the skewness (γ₁) of the distribution
@return Median
median(source, length)
Overloaded median to calculate from source and length
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Median
variance(stdev)
Calculate variance (σ²) - Square of the standard deviation
Parameters:
stdev (float) : the standard deviation (σ) of the distribution
@return Variance (σ²)
variance(source, length)
Overloaded variance to calculate from source and length
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Variance (σ²)
kurtosis(source, length, mean, stdev)
Calculate kurtosis (γ₂) - Degree of "tailedness" in the distribution
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
mean (float) : the mean (average) of the distribution
stdev (float) : the standard deviation (σ) of the distribution
@return Kurtosis (γ₂)
kurtosis(source, length)
Overloaded kurtosis to calculate from source and length
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Kurtosis (γ₂)
normal_score(source, mean, stdev)
Calculate Z-score (standard score) assuming a normal distribution
Parameters:
source (float) : Distribution source (typically a price or indicator series)
mean (float) : the mean (average) of the distribution
stdev (float) : the standard deviation (σ) of the distribution
@return Z-Score
normal_score(source, length)
Overloaded normal_score to calculate from source and length
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Z-Score
non_normal_score(source, mean, stdev, skewness, kurtosis)
Calculate adjusted Z-score considering skewness and kurtosis
Parameters:
source (float) : Distribution source (typically a price or indicator series)
mean (float) : the mean (average) of the distribution
stdev (float) : the standard deviation (σ) of the distribution
skewness (float) : the skewness (γ₁) of the distribution
kurtosis (float) : the "tailedness" in the distribution
@return Z-Score
non_normal_score(source, length)
Overloaded non_normal_score to calculate from source and length
Parameters:
source (float) : Distribution source (typically a price or indicator series)
length (int) : Window length for the distribution (must be >= 30 for meaningful statistics)
@return Z-Score
method init(this)
Initialize all statistical fields of the `distr` type
Namespace types: distr
Parameters:
this (distr)
method init(this, source, length)
Overloaded initializer to set source and length
Namespace types: distr
Parameters:
this (distr)
source (float)
length (int)
distr
Custom type to represent a Gaussian distribution
Fields:
source (series float) : Distribution source (typically a price or indicator series)
length (series int) : Window length for the distribution (must be >= 30 for meaningful statistics)
mode (series float) : Most frequent value in the distribution
median (series float) : Middle value separating the greater and lesser halves of the distribution
mean (series float) : μ (1st central moment) - Average of the distribution
stdev (series float) : σ or standard deviation (square root of the variance) - Measure of dispersion
variance (series float) : σ² (2nd central moment) - Squared standard deviation
skewness (series float) : γ₁ (3rd central moment) - Asymmetry of the distribution
kurtosis (series float) : γ₂ (4th central moment) - Degree of "tailedness" relative to a normal distribution
normal_score (series float) : Z-score assuming normal distribution
non_normal_score (series float) : Adjusted Z-score considering skewness and kurtosis
Optimized Future Time Cycles V2Time Cycle-Based Indicator Overview
This script utilizes Time Cycles to visually display the periodic fluctuations of the past and future, helping to predict key market turning points and trend shifts.
The indicator is fully customizable and marks periodic vertical lines and labels on the chart based on a specified reference date.
1. Key Features
Time Cycle Settings
Displays various user-defined time cycles (e.g., 9 days, 17 days, 26 days) visually on the chart.
Each cycle is distinguished by unique colors and labels for clear identification.
Allows users to set a reference date, from which past and future cycles are calculated.
Past and Future Cycle Visualization
Future Cycles:
Predicts potential points of market fluctuations or trend changes in the future.
Vertical lines represent future turning points based on the defined time cycles.
Past Cycles:
Displays how cyclical patterns manifested in historical market data.
Helps identify recurring patterns and similar historical market conditions.
Customizable Visuals
Adjust line styles (solid, dashed, etc.) and label spacing for a cleaner chart, even with multiple cycles displayed.
Separately toggle the visibility of past and future cycles for a more tailored analysis experience.
2. How to Use and Interpret the Indicator
Setting the Reference Date
The reference date is crucial for this indicator and works best when set to significant market events or turning points.
Both past and future cycles are calculated based on the reference date, and overlapping cycles may indicate periods of high volatility or strong trend shifts.
Cycle Analysis
Interpretation by Cycle Duration:
Short-term Cycles (9, 17 days): Useful for predicting quick market fluctuations.
Mid- to Long-term Cycles (26, 52, 200 days): Ideal for identifying major trend changes.
Overlapping Cycles:
When multiple cycles converge, significant turning points or strong market movements are likely.
Importance of Past Cycles
Past cycles are invaluable for identifying repetitive patterns in the market.
For example, analyzing strong turning points from past cycles can help anticipate similar scenarios in the future.
3. Tips for Using the Indicator
Optimize Line Styles:
When displaying both past and future cycles, charts may become cluttered. Adjusting line styles or colors can help maintain visual clarity.
Short-term vs. Long-term Cycles:
Short-term Cycles: Best suited for strategies like scalping or day trading.
Long-term Cycles: Useful for capturing major trend shifts or identifying macroeconomic changes.
Recommended Combination with Other Indicators:
Combine the Time Cycle indicator with moving averages, wave indicators, RSI, or Bollinger Bands for better results.
The time cycle identifies the timing of turning points, while tools like moving averages or RSI provide insights into trend direction during these critical moments.
4. Conclusion
This Time Cycle indicator visualizes past and future periodic fluctuations, enabling effective predictions of market trends and turning points.
The reference date and overlapping cycles are essential for pinpointing critical turning points.
The newly added past cycle visualization feature enhances the ability to recognize recurring patterns and leverage historical data for more accurate predictions.
시간 주기(Time Cycle) 기반 지표 소개
이 스크립트는 **시간 주기(Time Cycle)**를 활용해 과거와 미래의 주기적 변동을 시각적으로 보여주어, 시장의 추세 변화 시점과 변곡점을 예측하는 데 도움을 줍니다.
지표는 사용자 정의가 가능하며, 설정된 기준 날짜를 기반으로 주기적인 수직선과 레이블을 차트에 표시합니다.
1. 주요 기능
시간 주기 설정
사용자가 설정한 다양한 시간 주기(예: 9일, 17일, 26일 등)를 시각적으로 표시.
각 주기는 고유한 색상과 레이블로 구분되어 명확하게 차트에 나타납니다.
**기준 날짜(reference date)**를 설정하여, 해당 날짜를 기준으로 과거와 미래의 주기를 계산합니다.
미래와 과거 주기 표시
미래 주기:
미래의 시장 변동 시점이나 추세 변화 가능성이 높은 지점을 예측할 수 있습니다.
설정된 시간 주기에 따라 미래 변곡점을 차트에 수직선으로 나타냅니다.
과거 주기:
과거 시장에서 주기적 변동이 어떻게 나타났는지 확인 가능합니다.
이를 통해 반복되는 패턴이나 과거와 유사한 시장 상황을 파악할 수 있습니다.
시각적 사용자 설정
수직선 스타일(실선, 점선 등)과 레이블 간격을 조정하여, 복잡한 차트에서도 깔끔하게 정보를 확인할 수 있습니다.
과거와 미래의 주기 표시를 개별적으로 조정 가능하여 사용자 맞춤형 분석이 가능합니다.
2. 지표 사용 및 해석 방법
기준 날짜 설정
**기준 날짜(reference date)**는 시장에서 중요한 변동이 있었던 날을 기준으로 설정하는 것이 가장 효과적입니다.
기준 날짜를 기반으로 과거와 미래 주기가 계산되며, 주기가 겹치는 시점에서 강한 변동성이 나타날 가능성이 높습니다.
주기 분석
주기별 해석:
단기 주기 (9일, 17일): 빠른 변동성을 예측.
중·장기 주기 (26일, 52일, 200일): 큰 추세 변화를 예측.
주기가 겹치는 시점은 중요한 변곡점이 될 가능성이 크며, 추세 전환의 신호로 볼 수 있습니다.
과거 주기의 중요성
과거 주기는 시장의 반복 패턴을 찾는 데 유용합니다.
예를 들어, 과거 주기에서 강한 변곡점이 나타났던 시점을 분석하면, 미래에도 유사한 상황이 발생할 가능성을 예측할 수 있습니다.
3. 지표 활용 팁
수직선 스타일 최적화:
과거와 미래 주기를 모두 표시하면 차트가 복잡해질 수 있으므로, 선 스타일이나 색상을 조정하여 시각적으로 덜 혼란스럽게 설정하세요.
단기 vs. 장기 주기:
단기 주기는 스캘핑과 같은 빠른 매매 전략에 유용하며,
장기 주기는 대세 추세 변화를 포착하는 데 유리합니다.
결합 사용 추천:
시간 주기(Time Cycle) 지표는 이평선 파동 지표 또는 RSI, 볼린저 밴드와 함께 사용하면 더욱 효과적입니다.
시간 주기는 변곡점의 시점을 알려주고, 이평선 파동이나 RSI는 그 시점에서의 추세 방향성을 보완해 줍니다.
4. 결론
이 시간 주기(Time Cycle) 지표는 과거와 미래의 주기적 변동을 시각화하여, 시장의 추세 변화와 변곡점을 효과적으로 예측할 수 있습니다.
특히, 기준 날짜 설정과 주기적 겹침은 중요한 변곡점을 파악하는 핵심입니다.
새롭게 추가된 과거 주기 표시 기능은 반복 패턴을 확인하고 과거 데이터를 바탕으로 더 정교한 예측을 가능하게 합니다.
Pivotal Point Detection
The indicator highlights price gaps (overnight gaps) with significantly increased volume in the daily chart only. These price jumps can occur after earnings reports or other significant news and often point to an important event (e.g., a new product or business model). According to Jesse Livermore, these are called Pivotal Points.
The price jumps displayed by the indicator are not a guarantee that they represent a true Pivotal Point, but they provide a hint of a significant business development - especially when they occur repeatedly alongside revenue growth. This can help identify potentially strong growth stocks and high-performing investments. However, the underlying events and connections must be investigated through additional research.
make posible to find stocks like:
NYSE:PLTR NASDAQ:ROOT NASDAQ:NVDA NYSE:CVNA NYSE:LRN
A "pivotal price line" is drawn at the opening price of the Pivotal Point. This line is considered a support level. If the price falls below this line, the Pivotal Point loses its validity.
MACD -- Normalized█ OVERVIEW
This indicator is a normalized and scaled version of the Moving Average Convergence Divergence ( MACD ) indicator, inspired by the work in "Statistically Sound Indicators" by Timothy Masters. It enhances the traditional MACD by applying statistical normalization and scaling techniques, providing more consistent and reliable signals across different markets and timeframes.
█ CONCEPTS
The traditional MACD measures the difference between two Exponential Moving Averages ( EMAs ) of different lengths to identify momentum changes. However, its raw values are unbounded, making it challenging to compare across different instruments or timeframes.
This normalized MACD addresses this limitation by:
• Normalization : Adjusting the MACD values using the Average True Range ( ATR ) to account for market volatility.
• Scaling : Applying the Cumulative Distribution Function ( CDF ) to constrain the output between -50 and +50.
• Smoothing : Providing a smoothed signal line and histogram to effectively visualize momentum shifts.
█ FEATURES
• Normalized MACD Line : Computes the difference between the short-term and long-term EMAs, normalized by market volatility.
• Signal Line : Applies EMA smoothing to the normalized MACD line over a user-defined period.
• Histogram : Visualizes the difference between the normalized MACD line and the signal line, highlighting momentum changes.
• Customization Options :
• Adjustable lengths for the short-term EMA, long-term EMA, and signal line smoothing.
• Ability to toggle the visibility of the MACD line, signal line, and histogram.
• Statistical Scaling : Utilizes statistical methods from Timothy Masters' work to provide consistent scaling across different instruments.
█ HOW TO USE
1 — Identify Momentum Shifts :
• A crossover of the MACD line above the signal line may indicate a bullish momentum shift.
• A crossover of the MACD line below the signal line may indicate a bearish momentum shift.
2 — Analyze the Histogram :
• A rising histogram suggests strengthening momentum in the current trend direction.
• A falling histogram may signal weakening momentum or a potential reversal.
3 — Customize Parameters :
• Adjust the EMA lengths and smoothing periods to fit the specific instrument or timeframe.
• Use the visibility toggles to focus on the components most relevant to your analysis.
4 — Combine with Other Tools :
• Use in conjunction with support/resistance levels, trend lines, or other indicators to confirm signals.
• Consider the overall market context to enhance decision-making.
█ LIMITATIONS
• The indicator is based on historical price data; it may not predict future market movements accurately.
• May produce false signals during low volatility or ranging market conditions.
• Initial periods may display na values due to insufficient data for calculations.
█ NOTES
• Ensure that the MathHelpers library by HuntGatherTrade is imported for the indicator to function correctly.
• The default parameters are commonly used settings but may require adjustments based on the trading instrument and timeframe.
• The normalization and scaling techniques are designed to make the indicator's outputs more comparable across different markets.
Bayesian Price Projection Model [Pinescriptlabs]📊 Dynamic Price Projection Algorithm 📈
This algorithm combines **statistical calculations**, **technical analysis**, and **Bayesian theory** to forecast a future price while providing **uncertainty ranges** that represent upper and lower bounds. The calculations are designed to adjust projections by considering market **trends**, **volatility**, and the historical probabilities of reaching new highs or lows.
Here’s how it works:
🚀 Future Price Projection
A dynamic calculation estimates the future price based on three key elements:
1. **Trend**: Defines whether the market is predisposed to move up or down.
2. **Volatility**: Quantifies the magnitude of the expected change based on historical fluctuations.
3. **Time Factor**: Uses the logarithm of the projected period (`proyeccion_dias`) to adjust how time impacts the estimate.
🧠 **Bayesian Probabilistic Adjustment**
- Conditional probabilities are calculated using **Bayes' formula**:
\
This models future events using conditional information:
- **Probability of reaching a new all-time high** if the price is trending upward.
- **Probability of reaching a new all-time low** if the price is trending downward.
- These probabilities refine the future price estimate by considering:
- **Higher volatility** increases the likelihood of hitting extreme levels (highs/lows).
- **Market trends** influence the expected price movement direction.
🌟 **Volatility Calculation**
- Volatility is measured using the **ATR (Average True Range)** indicator with a 14-period window. This reflects the average amplitude of price fluctuations.
- To express volatility as a percentage, the ATR is normalized by dividing it by the closing price and multiplying it by 200.
- Volatility is then categorized into descriptive levels (e.g., **Very Low**, **Low**, **Moderate**, etc.) for better interpretation.
---
🎯 **Deviation Limits (Upper and Lower)**
- The upper and lower limits form a **projected range** around the estimated future price, providing a framework for uncertainty.
- These limits are calculated by adjusting the ATR using:
- A user-defined **multiplier** (`factor_desviacion`).
- **Bayesian probabilities** calculated earlier.
- The **square root of the projected period** (`proyeccion_dias`), incorporating the principle that uncertainty grows over time.
🔍 **Interpreting the Model**
This can be seen as a **dynamic probabilistic model** that:
- Combines **technical analysis** (trends and ATR).
- Refines probabilities using **Bayesian theory**.
- Provides a **visual projection range** to help you understand potential future price movements and associated uncertainties.
⚡ Whether you're analyzing **volatile markets** or confirming **bullish/bearish scenarios**, this tool equips you with a robust, data-driven approach! 🚀
Español :
📊 Algoritmo de Proyección de Precio Dinámico 📈
Este algoritmo combina **cálculos estadísticos**, **análisis técnico** y **la teoría de Bayes** para proyectar un precio futuro, junto con rangos de **incertidumbre** que representan los límites superior e inferior. Los cálculos están diseñados para ajustar las proyecciones considerando la **tendencia del mercado**, **volatilidad** y las probabilidades históricas de alcanzar nuevos máximos o mínimos.
Aquí se explica su funcionamiento:
🚀 **Proyección de Precio Futuro**
Se realiza un cálculo dinámico del precio futuro estimado basado en tres elementos clave:
1. **Tendencia**: Define si el mercado tiene predisposición a subir o bajar.
2. **Volatilidad**: Determina la magnitud del cambio esperado en función de las fluctuaciones históricas.
3. **Factor de Tiempo**: Usa el logaritmo del período proyectado (`proyeccion_dias`) para ajustar cómo el tiempo afecta la estimación.
🧠 **Ajuste Probabilístico con la Teoría de Bayes**
- Se calculan probabilidades condicionales mediante la fórmula de **Bayes**:
\
Esto permite modelar eventos futuros considerando información condicional:
- **Probabilidad de alcanzar un nuevo máximo histórico** si el precio sube.
- **Probabilidad de alcanzar un nuevo mínimo histórico** si el precio baja.
- Estas probabilidades ajustan la estimación del precio futuro considerando:
- **Mayor volatilidad** aumenta la probabilidad de alcanzar niveles extremos (máximos/mínimos).
- **La tendencia del mercado** afecta la dirección esperada del movimiento del precio.
🌟 **Cálculo de Volatilidad**
- La volatilidad se mide usando el indicador **ATR (Average True Range)** con un período de 14 velas. Este indicador refleja la amplitud promedio de las fluctuaciones del precio.
- Para obtener un valor porcentual, el ATR se normaliza dividiéndolo por el precio de cierre y multiplicándolo por 200.
- Además, se clasifica esta volatilidad en categorías descriptivas (e.g., **Muy Baja**, **Baja**, **Moderada**, etc.) para facilitar su interpretación.
🎯 **Límites de Desviación (Superior e Inferior)**
- Los límites superior e inferior representan un **rango proyectado** en torno al precio futuro estimado, proporcionando un marco para la incertidumbre.
- Estos límites se calculan ajustando el ATR según:
- Un **multiplicador** definido por el usuario (`factor_desviacion`).
- Las **probabilidades condicionales** calculadas previamente.
- La **raíz cuadrada del período proyectado** (`proyeccion_dias`), lo que incorpora el principio de que la incertidumbre aumenta con el tiempo.
---
🔍 **Interpretación del Modelo**
Este modelo se puede interpretar como un **modelo probabilístico dinámico** que:
- Integra **análisis técnico** (tendencias y ATR).
- Ajusta probabilidades utilizando **la teoría de Bayes**.
- Proporciona un **rango de proyección visual** para ayudarte a entender los posibles movimientos futuros del precio y su incertidumbre.
⚡ Ya sea que estés analizando **mercados volátiles** o confirmando **escenarios alcistas/bajistas**, ¡esta herramienta te ofrece un enfoque robusto y basado en datos! 🚀
Close Minus Moving Average█ OVERVIEW
The Close Minus Moving Average (CMMA) is a statistically robust mean reversion indicator designed to identify potential reversal points in the market. By analyzing the relationship between the closing price and its moving average, CMMA provides traders with actionable insights to enhance their trading strategies.
Important
This indicator requires the use of the MathHelpers library published by HuntGatherTrade
█ CONCEPTS
The CMMA indicator operates by calculating the logarithmic difference between the current closing price and its simple moving average (SMA). This difference is then normalized using the Average True Range (ATR) to account for market volatility. The resulting value is transformed using the Cumulative Distribution Function (CDF) to produce a standardized metric that oscillates around zero.
Key Steps :
Logarithmic Calculation: Computes the natural logarithm of the closing prices.
Moving Average: Applies a simple moving average to the logarithmic closing prices.
ATR Normalization: Utilizes ATR to normalize the difference, ensuring the indicator adapts to varying market conditions.
CDF Transformation: Transforms the normalized difference to a scale that highlights mean reversion tendencies.
Mean Reversion
Mean reversion is a financial theory suggesting that asset prices and historical returns eventually return to the long-term mean or average level of the entire dataset. The CMMA leverages this concept to signal potential entry and exit points based on deviations from the moving average.
█ FEATURES
Adaptive Normalization: Utilizes ATR to adjust for market volatility, ensuring consistent performance across different market conditions.
Statistical Robustness: Built upon methodologies from Timothy Masters, ensuring reliable mean reversion signals.
Clear Visuals: Differentiates positive and negative deviations with distinct color coding for easy interpretation.
Customizable Parameters: Allows users to adjust lookback periods and ATR lengths to tailor the indicator to their specific trading needs
.
█ HOW TO USE
Add the Indicator :
Navigate to the Pine Script editor on TradingView.
Paste the CMMA script and add it to your chart.
Adjust Parameters :
Lookback Period: Determines the number of periods for calculating the moving average of the logarithmic close. Default is 1.
ATR Length: Sets the number of periods for ATR calculation. Default is 252.
Interpret Signals :
Green Plot: Indicates that the closing price is above the moving average, suggesting bullish momentum.
Red Plot: Indicates that the closing price is below the moving average, suggesting bearish momentum.
Zero Line: Serves as a reference point for mean reversion signals.
Trading Strategy :
Buy Signal: When CMMA crosses above the zero line, indicating a potential upward reversal.
Sell Signal: When CMMA crosses below the zero line, indicating a potential downward reversal.
█ LIMITATIONS
Lagging Indicator: As with all moving averages, CMMA is based on historical data and may lag during rapid market movements.
Parameter Sensitivity: The effectiveness of CMMA can vary based on the chosen lookback and ATR periods. Users should optimize these parameters based on the specific asset and timeframe.
Market Conditions: Best suited for mean-reverting markets and may underperform in trending or highly volatile environments.
█ NOTES
Version Compatibility: The CMMA script is written in Pine Script™ version 6. Ensure your TradingView environment supports this version.
License: This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0. Read the license here.
Trend Following Strategy with KNN
### 1. Strategy Features
This strategy combines the K-Nearest Neighbors (KNN) algorithm with a trend-following strategy to predict future price movements by analyzing historical price data. Here are the main features of the strategy:
1. **Dynamic Parameter Adjustment**: Uses the KNN algorithm to dynamically adjust parameters of the trend-following strategy, such as moving average length and channel length, to adapt to market changes.
2. **Trend Following**: Captures market trends using moving averages and price channels to generate buy and sell signals.
3. **Multi-Factor Analysis**: Combines the KNN algorithm with moving averages to comprehensively analyze the impact of multiple factors, improving the accuracy of trading signals.
4. **High Adaptability**: Automatically adjusts parameters using the KNN algorithm, allowing the strategy to adapt to different market environments and asset types.
### 2. Simple Introduction to the KNN Algorithm
The K-Nearest Neighbors (KNN) algorithm is a simple and intuitive machine learning algorithm primarily used for classification and regression problems. Here are the basic concepts of the KNN algorithm:
1. **Non-Parametric Model**: KNN is a non-parametric algorithm, meaning it does not make any assumptions about the data distribution. Instead, it directly uses training data for predictions.
2. **Instance-Based Learning**: KNN is an instance-based learning method that uses training data directly for predictions, rather than generating a model through a training process.
3. **Distance Metrics**: The core of the KNN algorithm is calculating the distance between data points. Common distance metrics include Euclidean distance, Manhattan distance, and Minkowski distance.
4. **Neighbor Selection**: For each test data point, the KNN algorithm finds the K nearest neighbors in the training dataset.
5. **Classification and Regression**: In classification problems, KNN determines the class of a test data point through a voting mechanism. In regression problems, KNN predicts the value of a test data point by calculating the average of the K nearest neighbors.
### 3. Applications of the KNN Algorithm in Quantitative Trading Strategies
The KNN algorithm can be applied to various quantitative trading strategies. Here are some common use cases:
1. **Trend-Following Strategies**: KNN can be used to identify market trends, helping traders capture the beginning and end of trends.
2. **Mean Reversion Strategies**: In mean reversion strategies, KNN can be used to identify price deviations from the mean.
3. **Arbitrage Strategies**: In arbitrage strategies, KNN can be used to identify price discrepancies between different markets or assets.
4. **High-Frequency Trading Strategies**: In high-frequency trading strategies, KNN can be used to quickly identify market anomalies, such as price spikes or volume anomalies.
5. **Event-Driven Strategies**: In event-driven strategies, KNN can be used to identify the impact of market events.
6. **Multi-Factor Strategies**: In multi-factor strategies, KNN can be used to comprehensively analyze the impact of multiple factors.
### 4. Final Considerations
1. **Computational Efficiency**: The KNN algorithm may face computational efficiency issues with large datasets, especially in real-time trading. Optimize the code to reduce access to historical data and improve computational efficiency.
2. **Parameter Selection**: The choice of K value significantly affects the performance of the KNN algorithm. Use cross-validation or other methods to select the optimal K value.
3. **Data Standardization**: KNN is sensitive to data standardization and feature selection. Standardize the data to ensure equal weighting of different features.
4. **Noisy Data**: KNN is sensitive to noisy data, which can lead to overfitting. Preprocess the data to remove noise.
5. **Market Environment**: The effectiveness of the KNN algorithm may be influenced by market conditions. Combine it with other technical indicators and fundamental analysis to enhance the robustness of the strategy.
MathHelpersLibrary "MathHelpers"
Overview
A collection of helper functions for designing indicators and strategies.
calculateATR(length, log)
Calculates the Average True Range (ATR) or Log ATR based on the 'log' parameter. Sans Wilder's Smoothing
Parameters:
length (simple int)
log (simple bool)
Returns: float The calculated ATR value. Returns Log ATR if `log` is true, otherwise returns standard ATR.
CDF(z)
Computes the Cumulative Distribution Function (CDF) for a given value 'z', mimicking the CDF function in "Statistically Sound Indicators" by Timothy Masters.
Parameters:
z (simple float)
Returns: float The CDF value corresponding to the input `z`, ranging between 0 and 1.
logReturns(lookback)
Calculates the logarithmic returns over a specified lookback period.
Parameters:
lookback (simple int)
Returns: float The calculated logarithmic return. Returns `na` if insufficient data is available.
Lot Size & Risk Calculator (All Pairs)this indicator is designed to simplify and optimize risk management. It automatically calculates the ideal lot size based on your account balance, risk percentage, and defined entry and exit levels. Additionally, it includes visual tools to represent stop-loss (SL) and take-profit (TP) levels, helping you trade with precision and consistency.
WHAT IS THIS INDICATOR FOR?
This indicator is essential for traders who want to:
Maintain consistent risk in their trades.
Quickly calculate lot sizes for Forex, XAUUSD, BTCUSD, and US100.
Visualize key levels (Entry, SL, and TP) on the chart.
Monitor potential losses and gains in real time.
COMPATIBLE ASSETS
The Lot Size Calculator works with the following assets:
Forex: Standard currency pairs.
XAUUSD: Gold versus the US dollar.
BTCUSD: Bitcoin versus the US dollar.
US100: Nasdaq 100 index.
Calculations adjust automatically based on the selected asset.
TAKE-PROFIT (TP) LEVELS
The indicator allows you to define up to three take-profit levels:
TP1
TP2
TP3
.
Each level is configurable based on your exit strategy.
DASHBOARD
The dashboard is a visual tool that consolidates key information about your trade:
Account balance: Total amount available in your account.
Lot size: Calculated based on your risk and parameters.
Potential loss (SL): Amount you could lose if the price hits your stop-loss.
Potential gain (TP): Expected profit if the take-profit level is reached.
SETTINGS
The indicator offers multiple configurable options to adapt to your trading style:
Levels
Entry: Initial trade price.
Stop-Loss (SL): Maximum allowed loss level.
Take-Profit (TP): Up to three configurable levels.
Risk Management
Account balance ($): Enter your total available balance.
Risk percentage: Define how much you're willing to risk per trade
.
Visual Options
Visualization style: Choose between simple lines or visual fills.
Colors: Customize the colors of lines and labels.
Dashboard Settings
Statistics: Enable or disable key data display.
Size and position: Adjust the dashboard's size and location on the chart.
HOW TO CHANGE AN ENTRY?
Open the indicator settings in TradingView and entering the new data manually
Removing and re-adding the indicator to the chart
Global Index Spread RSI StrategyThis strategy leverages the relative strength index (RSI) to monitor the price spread between a global benchmark index (such as AMEX) and the currently opened asset in the chart window. By calculating the spread between these two, the strategy uses RSI to identify oversold and overbought conditions to trigger buy and sell signals.
Key Components:
Global Benchmark Index: The strategy compares the current asset with a predefined global index (e.g., AMEX) to measure relative performance. The choice of a global benchmark allows the trader to analyze the current asset's movement in the context of broader market trends.
Spread Calculation:
The spread is calculated as the percentage difference between the current asset's closing price and the global benchmark index's closing price:
Spread=Current Asset Close−Global Index CloseGlobal Index Close×100
Spread=Global Index CloseCurrent Asset Close−Global Index Close×100
This metric provides a measure of how the current asset is performing relative to the global index. A positive spread indicates the asset is outperforming the benchmark, while a negative spread signals underperformance.
RSI of the Spread: The RSI is then calculated on the spread values. The RSI is a momentum oscillator that ranges from 0 to 100 and is commonly used to identify overbought or oversold conditions in asset prices. An RSI below 30 is considered oversold, indicating a potential buying opportunity, while an RSI above 70 is overbought, suggesting that the asset may be due for a pullback.
Strategy Logic:
Entry Condition: The strategy enters a long position when the RSI of the spread falls below the oversold threshold (default 30). This suggests that the asset may have been oversold relative to the global benchmark and might be due for a reversal.
Exit Condition: The strategy exits the long position when the RSI of the spread rises above the overbought threshold (default 70), indicating that the asset may have become overbought and a price correction is likely.
Visual Reference:
The RSI of the spread is plotted on the chart for visual reference, making it easier for traders to monitor the relative strength of the asset in relation to the global benchmark.
Overbought and oversold levels are also drawn as horizontal reference lines (70 and 30), along with a neutral level at 50 to show market equilibrium.
Theoretical Basis:
The strategy is built on the mean reversion principle, which suggests that asset prices tend to revert to a long-term average over time. When prices move too far from this mean—either being overbought or oversold—they are likely to correct back toward equilibrium. By using RSI to identify these extremes, the strategy aims to profit from price reversals.
Mean Reversion: According to financial theory, asset prices oscillate around a long-term average, and any extreme deviation (overbought or oversold conditions) presents opportunities for price corrections (Poterba & Summers, 1988).
Momentum Indicators (RSI): The RSI is widely used in technical analysis to measure the momentum of an asset. Its application to the spread between the asset and a global benchmark allows for a more nuanced view of relative performance and potential turning points in the asset's price trajectory.
Practical Application:
This strategy works best in markets where relative strength is a key factor in decision-making, such as in equity indices, commodities, or forex markets. By assessing the performance of the asset relative to a global benchmark and utilizing RSI to identify extremes in price movements, the strategy helps traders to make more informed decisions based on potential mean reversion points.
While the "Global Index Spread RSI Strategy" offers a method for identifying potential price reversals based on relative strength and oversold/overbought conditions, it is important to recognize that no strategy is foolproof. The strategy assumes that the historical relationship between the asset and the global benchmark will hold in the future, but financial markets are subject to a wide array of unpredictable factors that can lead to sudden changes in price behavior.
Risk of False Signals:
The strategy relies heavily on the RSI to trigger buy and sell signals. However, like any momentum-based indicator, RSI can generate false signals, particularly in highly volatile or trending markets. In such conditions, the strategy may enter positions too early or exit too late, leading to potential losses.
Market Context:
The strategy may not account for macroeconomic events, news, or other market forces that could cause sudden shifts in asset prices. External factors, such as geopolitical developments, monetary policy changes, or financial crises, can cause a divergence between the asset and the global benchmark, leading to incorrect conclusions from the strategy.
Overfitting Risk:
As with any strategy that uses historical data to make decisions, there is a risk of overfitting the model to past performance. This could result in a strategy that works well on historical data but performs poorly in live trading conditions due to changes in market dynamics.
Execution Risks:
The strategy does not account for slippage, transaction costs, or liquidity issues, which can impact the execution of trades in real-market conditions. In fast-moving markets, prices may move significantly between order placement and execution, leading to worse-than-expected entry or exit prices.
No Guarantee of Profit:
Past performance is not necessarily indicative of future results. The strategy should be used with caution, and risk management techniques (such as stop losses and position sizing) should always be implemented to protect against significant losses.
Traders should thoroughly test and adapt the strategy in a simulated environment before applying it to live trades, and consider seeking professional advice to ensure that their trading activities align with their risk tolerance and financial goals.
References:
Poterba, J. M., & Summers, L. H. (1988). Mean Reversion in Stock Prices: Evidence and Implications. Journal of Financial Economics, 22(1), 27-59.
LiquidFusion SignalPro [CHE] LiquidFusion SignalPro – Indicator Overview
The LiquidFusion SignalPro is a powerful and sophisticated TradingView indicator designed to identify high-quality trade entries and exits. By combining seven unique sub-indicators, it provides comprehensive market analysis, ensuring traders can make informed decisions. This tool is suitable for all market conditions and supports customization to fit individual trading strategies.
Key Components (Sub-Indicators):
1. RPM (Relative Price Momentum):
- Measures cumulative price momentum over a specified period.
- Provides insights into price strength and directional bias.
- Input Customization:
- Source: Data for momentum calculation.
- Period: Length for momentum measurement.
- Resolution: Timeframe for data fetching.
2. BBO (Bull-Bear Oscillator):
- Calculates the strength of bullish or bearish momentum based on price movement and RSI conditions.
- Uses a super-smoothing technique for reliable signals.
- Customizable parameters include the oscillator's period and repainting options.
3. MACD (Moving Average Convergence Divergence):
- A classic momentum indicator for trend direction and strength.
- Provides buy/sell signals based on the crossover of the MACD line and signal line.
- Input Customization:
- Fast/Slow EMA Periods.
- Signal Line Period.
- Resolution and Source Data.
4. RSI (Relative Strength Index):
- Tracks overbought and oversold conditions.
- A key tool to validate trend continuation or reversals.
- Customizable period, resolution, and source.
5. CCI (Commodity Channel Index):
- Measures the deviation of price from its average.
- Useful for identifying cyclical trends.
- Input Customization includes period, resolution, and source.
6. Stochastic Oscillator:
- Indicates momentum by comparing closing prices to a range of highs and lows.
- Includes smoothing factors for %K and %D lines.
- Customizable parameters:
- %K Length and Smoothing.
- Resolution and Repainting Options.
7. Supertrend:
- A trailing stop-and-reverse system for trend-following strategies.
- Excellent for identifying strong trends and potential reversals.
- Inputs include the multiplier factor and period for ATR-like calculations.
Inputs Overview:
The indicator supports extensive customization for each sub-indicator, grouped under intuitive categories:
- Color Settings: Define bullish and bearish plot colors.
- RPM, BBO, MACD, RSI, CCI, Stochastic, and Supertrend Settings: Tailor each sub-indicator's behavior with adjustable parameters.
- UI Options: Toggle features such as bar coloring, indicator names, and plotted candles.
Trade Signals:
- Long Signal:
- All indicators align in a bullish state:
- RPM > 0, MACD > 0, RSI > 50, Stochastic > 50, CCI > 0, BBO > 0, Supertrend below price.
- Plot: Green triangle below the candle.
- Alert: Notifies the trader of a potential long entry.
- Short Signal:
- All indicators align in a bearish state:
- RPM < 0, MACD < 0, RSI < 50, Stochastic < 50, CCI < 0, BBO < 0, Supertrend above price.
- Plot: Red triangle above the candle.
- Alert: Notifies the trader of a potential short entry.
Features:
- Enhanced Visuals: Plots sub-indicator statuses using labels and color-coded shapes for clarity.
- Alerts: Integrated alert conditions for both long and short trades.
- Bar Coloring: Provides overall trend bias with green (bullish), red (bearish), or gray (neutral) bars.
- Customizable Table: Displays the indicator's status in the chart’s top-right corner.
Trading Benefits:
The LiquidFusion SignalPro excels in generating high-quality entries and exits by:
- Reducing noise through multiple indicator alignment.
- Supporting multiple timeframes and resolutions for flexibility.
- Offering customizable inputs for personalized trading strategies.
Use this tool to enhance your market analysis and improve your trading performance.
Disclaimer:
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
This indicator is inspired by the Super 6x Indicators: RSI, MACD, Stochastic, Loxxer, CCI, and Velocity . A special thanks to Loxx for their relentless effort, creativity, and contributions to the TradingView community, which served as a foundation for this work.
Happy trading and best regards
Chervolino
Global vs National Index Spread RSIThe Global vs National Index Spread RSI indicator visualizes the relative strength of national stock indices compared to a global benchmark (e.g., AMEX). It calculates the percentage spread between the closing prices of each national index and the global index, applying the Relative Strength Index (RSI) to each spread.
How It Works
Spread Calculation: The spread represents the percentage difference between a national index and the global index.
RSI Application: RSI is applied to these spreads to identify overbought or oversold conditions in the relative performance of the national indices.
Reference Lines: Overbought (70), oversold (30), and neutral (50) levels help guide interpretation.
Insights from Research
The correlation between global and national indices provides insights into market integration and interdependence. Studies such as Forbes & Rigobon (2002) emphasize the importance of understanding these linkages during periods of financial contagion. Observing spread trends with RSI can aid in identifying shifts in investor sentiment and regional performance anomalies.
Use Cases
- Detect divergences between national and global markets.
- Identify overbought or oversold conditions for specific indices.
- Complement portfolio management strategies by monitoring geographic performance.
References
Forbes, K. J., & Rigobon, R. (2002). "No contagion, only interdependence: Measuring stock market co-movements." Journal of Finance.
Eun, C. S., & Shim, S. (1989). "International transmission of stock market movements." Journal of Financial and Quantitative Analysis.
Pearson Analysis TableHere's the English translation:
The main functionality of the script lies in calculating the Pearson correlation coefficient over a given period. This coefficient quantifies the relationship between time and price movements, offering traders an objective measure of market trend linearity and, if applicable, its direction. A smoothing option is included to filter out noise and pressure.
The key parameters include the analysis window length, data source (by default, the closing price), and thresholds for identifying strong correlations. These thresholds allow trends to be classified as "bearish," "bullish," or "neutral," with the script reversing traditional interpretation for a unique perspective. For example, a positive correlation indicates a bearish trend, while a negative correlation-
The visual component of the script is a dynamic statistics table displayed on the chart. This table provides the current Pearson coefficient, correlation strength (classified as Strong, Medium, Weak, or Neutral), the inferred trend, and the analysis period. Values are color-coded for easy identification, thus enhancing trader understanding.
Additionally, the script offers alert conditions to inform traders of important market events, such as when the Pearson coefficient crosses key thresholds or changes direction. These alerts can be used to identify strong bearish or bullish trends or transitions through the neutral zone.
This tool is particularly useful for traders seeking to identify and act on statistically significant trends, providing them with an analytical edge and helping them align their strategies with market dynamics. The combination of real-time calculations, customizable thresholds, and clear visual feedback makes this indicator a robust addition to any technology.