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.
Indicators and strategies
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.
Multiple RSITitle: MultiRSI: A Versatile Multi-Timeframe RSI Indicator
Short Description:
A powerful RSI-based indicator that incorporates three RSI lengths (Fast, Medium, and Slow) to help traders analyze trends, momentum, and potential reversals with clear visual signals.
Full Description:
Overview:
The MultiRSI script provides traders with a dynamic tool to assess market conditions across multiple RSI timeframes. It calculates Fast, Medium, and Slow RSI values, assigns meaningful colors based on trend analysis, and highlights key crossover points for actionable insights.
Key Features:
Triple RSI Display:
Fast RSI (default: 8): Ideal for capturing short-term momentum.
Medium RSI (default: 12): Provides a balanced perspective.
Slow RSI (default: 16): Helps identify longer-term trends.
Trend Analysis:
Color-coded RSI lines:
Green, blue, and aqua for uptrends.
Yellow, orange, and red for potential downtrends.
Visual differentiation for easy interpretation.
Crossover Signals:
Upward Cross (triangle up): Indicates potential bullish momentum.
Downward Cross (triangle down): Suggests possible bearish momentum.
Marked directly on the chart for clarity.
Customizable Inputs:
Adjust RSI lengths to suit your trading strategy.
Grouped input settings for a seamless configuration experience.
Usage Scenarios:
Identify trend strength and reversals in different timeframes.
Spot key momentum shifts with crossover signals.
Combine with other indicators for a comprehensive trading strategy.
How It Works:
The script compares the Fast RSI against the Medium RSI and the Medium RSI against the Slow RSI to determine short-, medium-, and long-term trends. Crossovers between Medium and Slow RSI values signal potential momentum shifts.
Visualization:
Clear, color-coded plots for the three RSI levels.
Highlighted crossovers for quick decision-making.
License:
This script is open-source under the Mozilla Public License 2.0. Feel free to use, modify, and share!
BTC CME Futures Divergence TrackerThis script tracks divergences between price action and open interest for the BTC CME Futures contract (symbol "BTC1!") using the following components:
Key Features:
1. Price Analysis: Identifies lower highs in the price over a specified lookback period. Marks these points with red upward-facing triangles above the bars.
2. Open Interest Analysis: Retrieves open interest (OI) data for the BTC CME Futures contract via request.security. Detects lower highs in open interest over the same lookback period. Highlights these points with blue downward-facing triangles below the bars.
3. Divergence Detection: A divergence is identified when both price and open interest form lower highs simultaneously. Highlights such occurrences with a purple background, indicating potential bearish sentiment or weakening momentum.
4. Alerts: If divergences are detected, an alert is triggered (if enabled), notifying the trader to take action.
5. Visualization: Open interest is plotted as a blue line in a separate pane for added context. Red and blue markers highlight significant points in price and open interest trends.
Use Cases:
- Spot Weakening Trends: Divergences between price and open interest may indicate a loss of momentum or bearish sentiment, allowing traders to preemptively adjust their strategies.
- Monitor Institutional Activity: Open interest changes reflect shifts in market participation, especially in derivative markets like CME Futures.
- Set Alerts for Key Signals: With automated alerts, traders can stay informed of potential divergence signals without constant monitoring.
Customization Options:
- Lookback Period: Adjust the number of bars used to detect lower highs.
- Timeframe: Choose the timeframe for fetching open interest data (e.g., daily, hourly).
- Alert Activation: Enable or disable alerts for divergences.
This tool combines price action with open interest dynamics to provide a robust method for identifying market trends and potential reversals in BTC CME Futures.
[SGM VaR Stats VS Empirical]Main Functions
Logarithmic Returns & Historical Data
Calculates logarithmic returns from closing prices.
Stores these returns in a dynamic array with a configurable maximum size.
Approximation of the Inverse Error Function
Uses an approximation of the erfinv function to calculate z-scores for given confidence levels.
Basic Statistics
Mean: Calculates the average of the data in the array.
Standard Deviation: Measures the dispersion of returns.
Median: Provides a more robust measure of central tendency for skewed distributions.
Z-Score: Converts a confidence level into a standard deviation multiplier.
Empirical vs. Statistical Projection
Empirical Projection
Based on the median of cumulative returns for each projected period.
Applies an adjustable confidence filter to exclude extreme values.
Statistical Projection
Relies on the mean and standard deviation of historical returns.
Incorporates a standard deviation multiplier for confidence-adjusted projections.
PolyLines (Graphs)
Generates projections visually through polylines:
Statistical Polyline (Blue): Based on traditional statistical methods.
Empirical Polyline (Orange): Derived from empirical data analysis.
Projection Customization
Maximum Data Size: Configurable limit for the historical data array (max_array_size).
Confidence Level: Adjustable by the user (conf_lvl), affects the width of the confidence bands.
Projection Length: Configurable number of projected periods (length_projection).
Key Steps
Capture logarithmic returns and update the historical data array.
Calculate basic statistics (mean, median, standard deviation).
Perform projections:
Empirical: Based on the median of cumulative returns.
Statistical: Based on the mean and standard deviation.
Visualization:
Compare statistical and empirical projections using polylines.
Utility
This script allows users to compare:
Traditional Statistical Projections: Based on mathematical properties of historical returns.
Empirical Projections: Relying on direct historical observations.
Divergence or convergence of these lines also highlights the presence of skewness or kurtosis in the return distribution.
Ideal for traders and financial analysts looking to assess an asset’s potential future performance using combined statistical and empirical approaches.
Open-Close Upward Difference MarkerThis indicator, called "Open-Close Upward Difference Marker", is designed to help traders quickly spot candles where the price has moved up significantly within a certain percentage. It places a small green dot above any candle where the closing price is higher than the opening price (meaning the price went up) and the percentage difference between the open and close is greater than a set threshold.
Here’s how it works:
You can set a percentage threshold (e.g., 1%) using the input field. This threshold helps filter out small price changes, so the indicator only shows larger movements.
If the price increase from the open to the close is greater than the threshold, a small green dot will appear above the candle, letting you quickly identify upward price movements that meet your criteria.
It ignores downward price movements, so you’ll only see green dots for candles where the price has gone up.
This indicator is helpful for spotting upward trends and significant price increases, making it a simple visual aid for beginner traders.
Hosoda ProjectionsThis script, written in Pine Script v5, introduces a technical analysis tool called "Hosoda Projections." Inspired by Ichimoku Kinkō Hyō and wave-based forecasting methods, this indicator helps traders visualize potential future price levels using a combination of pivot detection and projected price movements. It offers a unique way to anticipate market dynamics and define potential targets, making it particularly useful for those who seek to combine historical price patterns with forward-looking strategies.
The script works by detecting key pivot points in the market using a customizable lookback period and then calculating a ZigZag pattern based on price fluctuations that exceed a specified percentage threshold. These pivots are used to identify three recent swing points, which serve as the foundation for projecting possible future price levels. Using these swings, the script generates levels that correspond to Fibonacci-based extensions and projections, such as 38.2%, 61.8%, 100%, 161.8%, and additional extensions like 261.8% and 361.8%. These levels are visualized on the chart as horizontal lines and labeled with their respective values for easy interpretation.
The primary advantage of the Hosoda Projections script is its ability to provide a structured approach to identifying potential price targets. By leveraging the natural rhythm of price movements, it offers insights into where the market might find support or resistance in the future. This can help traders refine their entry and exit points, manage risk more effectively, and gain a deeper understanding of market sentiment. Additionally, the dynamic nature of the projections adapts to new price data, ensuring the tool remains relevant across changing market conditions.
This script is particularly valuable for traders who appreciate the harmony between historical price action and predictive analysis. Whether you are trading forex, stocks, or cryptocurrencies, the Hosoda Projections tool can enhance your trading strategy by providing actionable and visually intuitive forecasts.
Previous Day Percentage LevelsAdds small trend lines at 25%, 50% and 75% levels from the low to the high of the previous day.
Dynamic TestingInput Parameters
`lookbackPeriod` : Number of candles to check for determining the highest high (resistance) and lowest low (support) levels.
`atrPeriod` : The period for calculating the Average True Range (ATR), a measure of market volatility.
`atrMultiplierSL` : Multiplier to calculate the stop-loss distance relative to the ATR.
`atrMultiplierTP1` and `atrMultiplierTP2` : Multipliers to calculate two take-profit levels relative to ATR.
`rewardToRisk` : The ratio between reward (profit) and risk (stop loss) for trade management.
---
Core Calculations
ATR (Average True Range)
atr = ta.atr(atrPeriod)
ATR is computed using the specified period to gauge price volatility.
Volume SMA
volumeSMA = ta.sma(volume, atrPeriod)
The script calculates the simple moving average of volume over the same period as ATR. This is used as a threshold for validating high-volume scenarios.
---
Support and Resistance Levels
`support` : Lowest price over the last `lookbackPeriod` candles.
`resistance` : Highest price over the same period.
`supportBuffer` and `resistanceBuffer` : These are "buffered" zones around support and resistance, calculated using half of the ATR to prevent false breakouts.
---
Entry Scenarios
Bullish Entry (`isBullishEntry`)
The close is above the buffered support level.
The low of the current candle touches or breaks below the support level.
The trading volume is greater than the `volumeSMA`.
Bearish Entry (`isBearishEntry`)
The close is below the buffered resistance level.
The high of the current candle touches or exceeds the resistance level.
The trading volume is greater than the `volumeSMA`.
---
Box Visualization
Bullish and Bearish Boxes
Bullish Box (`bullishBox`):
- A green, semi-transparent rectangle around the support level to highlight the bullish entry zone.
- Dynamically updates based on recent price action.
Bearish Box (`bearishBox`):
- A red, semi-transparent rectangle around the resistance level to highlight the bearish entry zone.
- Adjusts similarly as price evolves.
---
Stop Loss and Take Profit Calculations
Bullish Trades
Stop Loss (`bullishSL`): Calculated as support - atrMultiplierSL * ATR .
Take Profit 1 (`bullishTP1`): support + rewardToRisk * atrMultiplierTP1 * ATR .
Take Profit 2 (`bullishTP2`): support + rewardToRisk * atrMultiplierTP2 * ATR .
Bearish Trades
Stop Loss (`bearishSL`): resistance + atrMultiplierSL * ATR .
Take Profit 1 (`bearishTP1`): resistance - rewardToRisk * atrMultiplierTP1 * ATR .
Take Profit 2 (`bearishTP2`): resistance - rewardToRisk * atrMultiplierTP2 * ATR .
---
Visualization for Key Levels
Bullish Scenario
Green lines represent `bullishTP1` and `bullishTP2` for profit targets.
A red line indicates the `bullishSL` .
Labels like "TP1," "TP2," and "SL" dynamically appear at respective levels to make the targets and risk visually clear.
Bearish Scenario
Red lines represent `bearishTP1` and `bearishTP2` .
A green line marks the `bearishSL` .
Similar dynamic labeling for `TP1` , `TP2` , and `SL` at corresponding bearish levels.
---
Dynamic Updates
Both the entry boxes and key level visualizations (lines and labels) adjust dynamically based on real-time price and volume data.
---
Purpose
Identify high-probability bullish and bearish trade setups.
Define clear entry zones (using boxes) and exit levels (TP1, TP2, SL).
Incorporate volatility (via ATR) and volume into decision-making.
---
Technical Summary
Dynamically visualize support/resistance levels.
Set risk-managed trades using ATR-based stop-loss and profit levels.
Automate visual trade zones for enhanced chart clarity.
---
GoldenTradz EMA+SMA Insight Multi Timeframe - [TilakBala]GoldenTradz EMA+SMA Insight Multi-Timeframe
📊 Indicator By: TilakBala from GoldenTradz — Revolutionize your trading approach with precision and insight!
Unlock the full potential of moving averages with the GoldenTradz EMA+SMA Insight indicator. This feature-packed tool combines the strength of Exponential Moving Averages (EMA) and Simple Moving Averages (SMA), offering unmatched flexibility and clarity for traders. Whether you're a beginner or a pro, this indicator empowers you to make well-informed trading decisions across multiple timeframes.
Key Features & Advantages:
Multi-Timeframe Analysis: Seamlessly analyze market trends using EMAs and SMAs from different timeframes on a single chart.
Gain a broader perspective by comparing short-term and long-term trends.
Customizable Settings:
Adjust EMA and SMA lengths, sources, and timeframes to fit your trading strategy perfectly.
Enable or disable specific moving averages for a clutter-free chart view.
Enhanced Trend Detection:
Identify bullish and bearish trends quickly using visually distinct EMAs and SMAs.
Use shorter EMAs for faster signals and longer SMAs for reliable trend confirmation.
Overlay Design:
Plots moving averages directly on the price chart for effortless analysis.
Distinct colors and line thicknesses ensure clear identification of each moving average.
Versatile Applications:
Suitable for scalping, day trading, swing trading, and long-term investments.
Works flawlessly with stocks, forex, cryptocurrencies, commodities, indices, and more.
Decision-Making Support:
Crossovers between EMAs and SMAs help identify potential buy or sell opportunities.
Monitor key support and resistance levels dynamically.
Efficiency in Market Noise:
EMAs provide rapid responsiveness in volatile markets.
SMAs help smooth out market noise for clearer long-term trends.
Adaptable to Any Strategy:
Perfect for breakout, trend-following, and mean-reversion strategies.
Combine with other indicators for a comprehensive trading system.
User-Friendly:
Intuitive interface with clear input fields for quick setup.
Suitable for traders of all experience levels.
📊 Indicator By: TilakBala from GoldenTradz — Revolutionize your trading approach with precision and insight!
Transform your trading with GoldenTradz EMA+SMA Insight — the ultimate tool for trend and momentum analysis.