Two Pole Butterworth For Loop [BackQuant]Two Pole Butterworth For Loop
PLEASE read the following carefully, as understanding the underlying concepts and logic behind the indicator is key to incorporating it into your trading system in a sound and methodical manner.
Introducing BackQuant's Two Pole Butterworth For Loop (2P BW FL) — an advanced indicator that fuses the power of the Two Pole Butterworth filter with a dynamic for-loop scoring mechanism. This unique approach is designed to extract actionable trading signals by smoothing out price data and then analyzing it using a comparative scoring method. Let's delve into how this indicator works, why it was created, and how it can be used in various trading scenarios.
Understanding the Two Pole Butterworth Filter
The Butterworth filter is a signal processing tool known for its smooth response and minimal distortion. It's often used in electronic and communication systems to filter out unwanted noise. In trading, the Butterworth filter can be applied to price data to smooth out the volatility, providing traders with a clearer view of underlying trends without the whipsaws often associated with market noise.
The Two Pole Butterworth variant further enhances this effect by applying the filter with two poles, effectively creating a sharper transition between the passband and stopband. In simple terms, this allows the filter to follow the price action more closely, reacting to changes while maintaining smoothness.
In this script, the Two Pole Butterworth filter is applied to the Calculation Source (default is set to the closing price), creating a smoothed price series that serves as the foundation for further analysis.
Why Use a Two Pole Butterworth Filter?
The Two Pole Butterworth filter is chosen for its ability to reduce lag while maintaining a smooth output. This makes it an ideal choice for traders who want to capture trends without being misled by short-term volatility or market noise. By filtering the price data, the Two Pole Butterworth enables traders to focus on the broader market movements and avoid false signals.
The For-Loop Scoring Mechanism
In addition to the Butterworth filter, this script uses a for-loop scoring system to evaluate the smoothed price data. The for-loop compares the current value of the filtered price (referred to as "subject") to previous values over a defined range (set by the start and end input). The score is calculated based on whether the subject is higher or lower than the previous points, and the cumulative score is used to determine the strength of the trend.
Long and Short Signal Logic
Long Signals: A long signal is triggered when the score surpasses the Long Threshold (default set at 40). This suggests that the price has built sufficient upward momentum, indicating a potential buying opportunity.
Short Signals: A short signal is triggered when the score crosses under the Short Threshold (default set at -10). This indicates weakening price action or a potential downtrend, signaling a possible selling or shorting opportunity.
By utilizing this scoring system, the indicator identifies moments when the price momentum is shifting, helping traders enter positions at opportune times.
Customization and Visualization Options
One of the strengths of this indicator is its flexibility. Traders can customize various settings to fit their personal trading style or adapt it to different markets and timeframes:
Calculation Periods: Adjust the lookback period for the Butterworth filter, allowing for shorter or longer smoothing depending on the desired sensitivity.
Threshold Levels: Set the long and short thresholds to define when signals should be triggered, giving you control over the balance between sensitivity and specificity.
Signal Line Width and Colors: Customize the visual presentation of the indicator on the chart, including the width of the signal line and the colors used for long and short conditions.
Candlestick and Background Colors: If desired, the indicator can color the candlesticks or the background according to the detected trend, offering additional clarity at a glance.
Trading Applications
This Two Pole Butterworth For Loop indicator is versatile and can be adapted to various market conditions and trading strategies. Here are a few use cases where this indicator shines:
Trend Following: The Butterworth filter smooths the price data, making it easier to follow trends and identify when they are gaining or losing strength. The for-loop scoring system enhances this by providing a clear indication of how strong the current trend is compared to recent history.
Mean Reversion: For traders looking to identify potential reversals, the indicator’s ability to compare the filtered price to previous values over a range of periods allows it to spot moments when the trend may be losing steam, potentially signaling a reversal.
Swing Trading: The combination of smoothing and scoring allows swing traders to capture short to medium-term price movements by filtering out the noise and focusing on significant shifts in momentum.
Risk Management: By providing clear long and short signals, this indicator helps traders manage their risk by offering well-defined entry and exit points. The smooth nature of the Butterworth filter also reduces the risk of getting caught in false signals due to market noise.
Final Thoughts
The Two Pole Butterworth For Loop indicator offers traders a powerful combination of smoothing and scoring to detect meaningful trends and shifts in price momentum. Whether you are a trend follower, swing trader, or someone looking to refine your entry and exit points, this indicator provides the tools to make more informed trading decisions.
As always, it's essential to backtest the indicator on historical data and tailor the settings to your specific trading style and market. While the Butterworth filter helps reduce noise and smooth trends, no indicator can predict the future with absolute certainty, so it should be used in conjunction with other tools and sound risk management practices.
Thus following all of the key points here are some sample backtests on the 1D Chart
Disclaimer: Backtests are based off past results, and are not indicative of the future.
INDEX:BTCUSD
INDEX:ETHUSD
BINANCE:SOLUSD
Statistics
Crypto Heatmap [Pinescriptlabs]🌟 Crypto Heatmap is a visual tool that enables quick and efficient visualization of price behavior and percentage changes of various cryptocurrencies.
📊 It generates a heatmap to show variations in daily closing prices, helping traders quickly identify assets with the most movement.
📈 Percentage Change Calculation: It calculates the difference between the current price and the previous day's price, updating with each ticker.
✨ It uses a dynamic approach that adjusts colors based on market movements, making it easier to detect trading opportunities.
👀 You will notice for a moment that some cells disappear; this is because the table updates with each ticker to show real-time changes.
Español:
🌟 Crypto Heatmap es una herramienta visual que permite una rápida y eficiente visualización del comportamiento de precios y cambios porcentuales de varias criptomonedas.
📊 Genera un mapa de calor para mostrar las variaciones en los precios de cierre diario, ayudando a los traders a identificar rápidamente los activos con mayor movimiento.
📈 Cálculo del cambio porcentual: Calcula la diferencia entre el precio actual y el del día anterior, actualizándose en cada ticker.
✨ Utiliza un enfoque dinámico que ajusta los colores según los movimientos del mercado, facilitando la detección de oportunidades de trading.
Aquí tienes la traducción al español:
👀 **Observarás por un momento que algunas celdas desaparecen; esto es porque la tabla se actualiza en cada ticker para mostrar el cambio en tiempo real.**
2024 - Seasonality - Open to CloseScript Description:
This Pine Script is designed to visualise **seasonality** in the financial markets by calculating the **open-to-close percentage change** for each month of a selected asset. It creates a **heatmap** table to display the monthly performance over multiple years. The script provides detailed statistical summaries, including:
- **Average monthly percentage changes**
- **Standard deviation** of the changes
- **Percentage of months with positive returns**
The script also allows users to adjust colour intensities for positive and negative values, specify which year to start from, and skip specific months. Key metrics such as averages, standard deviations, and percentages of positive months can be toggled on or off based on user preferences. The result is a clear, visual representation of how an asset typically performs month by month, aiding in seasonality analysis.
Every $5 (3 Up, 3 Down) GOLD onlyDescription :
This indicator plots customizable horizontal lines spaced every $5 on the XAUUSD chart, with exactly 3 lines above and 3 lines below the nearest $5 level from the current price.
Key Features :
Line Spacing: The lines are plotted at $5 intervals starting from the nearest whole $5 price below the current price (e.g., $1900, $1905, etc.).
Customizable Line Color : Users can select the color of the lines via the indicator settings, making it adaptable to different chart themes and styles.
Customizable Line Style : The indicator allows you to choose from the following line styles:
Solid : Continuous line.
Dashed: Dashed line for a more discrete visual.
Dotted: Dotted line for minimalistic visibility.
Visibility Control : The indicator limits the number of lines to 3 above and 3 below the current price, keeping the chart clean and uncluttered while providing key levels of interest.
Use Cases :
Support and Resistance Identification: Easily spot key psychological levels in $5 increments, useful for identifying potential support or resistance zones in XAUUSD trading.
Price Action Monitoring : Traders can visually track how XAUUSD interacts with specific price levels spaced by $5 increments.
Customization Options :
Color Selection: Modify the line color to match your chart theme or highlight important levels.
Line Style: Select between solid, dashed, or dotted lines to customize the look of your chart.
This indicator is ideal for XAUUSD traders looking for clear, customizable visual levels on their charts to aid in decision-making, whether you're tracking price action or setting targets for entry and exit.
Forex - Lot size calculatorThis indicator is specifically designed for Forex traders who need a convenient lot size calculator directly on their charts. It allows users to input their account balance, risk percentage, and stop-loss distance in pips to easily determine the appropriate lot size for a given trade, ensuring effective risk management.
Key Features:
Lot Size Calculation: Automatically calculates the lot size based on user-defined inputs: account balance, risk percentage, and stop-loss distance.
Error Handling: The indicator only works with Forex pairs. If applied to non-Forex assets, a clear and prominent red error message will appear in the bottom-right corner of the chart, reminding the user that this script is intended exclusively for Forex trading.
Simple Visualization: The calculated lot size is displayed in an easy-to-read table directly on the chart.
How to Use:
Add the indicator to a Forex chart.
Enter your account balance, risk percentage, and stop-loss pips in the input fields.
The indicator will display the calculated lot size for the chosen Forex pair.
Important Notes:
This script is intended only for Forex assets. If used on other instruments (e.g., stocks, crypto, indices), an error message will be shown.
Always validate lot sizes with your broker, as there can be slight variations depending on broker specifications and leverage settings.
GBP Index vs CAD Index Currency OscillatorGBP vs CAD Currency Oscillator
This custom oscillator compares the relative strength of GBP (British Pound) and CAD (Canadian Dollar) against a basket of other currencies to determine potential overbought and oversold conditions. The indicator is designed to help traders evaluate momentum shifts and identify possible trend reversals between these two currencies, not just the GBPCAD pair.
How it Works:
Currency Index Calculation:
The oscillator calculates the average percentage change in 7 key GBP pairs (GBPUSD, EURGBP, GBPJPY, GBPAUD, GBPNZD, GBPCAD, and GBPCHF).
Similarly, it calculates the average percentage change for 7 key CAD pairs (USDCAD, EURCAD, CADJPY, AUDCAD, NZDCAD, GBPCAD, and CADCHF).
Stochastic Oscillator:
The indicator calculates a 0-100 oscillator for both the GBP and CAD currency indices based on the highest high and lowest low over a user-defined lookback period (default is 14 anlthough 60 works great on 1m chart).
The oscillator is smoothed using a simple moving average (default smoothing period is 3) to reduce noise and improve visual clarity.
Overbought/Oversold Conditions:
Overbought: When both the GBP and CAD oscillators exceed 80, the background turns red, indicating potential overbought conditions.
Oversold: When both oscillators fall below 20, the background turns green, signaling possible oversold conditions.
Crossovers:
When the GBP oscillator crosses above the CAD oscillator, a green dot appears at the bottom of the chart, signaling potential GBP strength.
When the GBP oscillator crosses below the CAD oscillator, a red dot appears, signaling potential CAD strength.
How to Use:
Overbought/Oversold Conditions: Use the red and green background highlights to spot potential overbought or oversold market conditions, helping you identify possible turning points.
Customization Options:
Lookback Period: You can adjust the lookback period for the stochastic calculation, allowing for sensitivity tuning (default: 14).
Smoothing Period: Control the degree of smoothing applied to the oscillators (default: 3).
This oscillator is ideal for traders focused on trading GBP and CAD pairs, offering a comparative analysis that can assist in better decision-making based on relative currency strength.
Double BBW OverlayDouble BBW Overlay Indicator
Overview
The Double BBW (Bollinger Band Width) Overlay indicator is a custom script for TradingView that combines two BBW indicators with adjustable settings. It allows traders to compare the volatility of two different periods of Bollinger Bands on the same chart. By default, the first BBW is calculated with a 10-period center line, and the second BBW with a 20-period center line, but these values can be customized.
How It Works
Bollinger Bands consist of an upper band, a lower band, and a middle band (typically a moving average). The Bollinger Band Width (BBW) measures the distance between the upper and lower bands relative to the center line. The width of these bands indicates market volatility:
Narrow Bands: Low volatility, usually preceding a breakout.
Wide Bands: High volatility, often following a strong price movement.
This indicator plots two BBW values on a non-overlay chart, making it easy to visualize and compare different market conditions over different periods.
Indicator Components
BBW 1 (default period: 10)
Calculates the BBW using a center line based on a 10-period moving average.
The width is plotted in blue by default.
BBW 2 (default period: 20)
Calculates the BBW using a center line based on a 20-period moving average.
The width is plotted in red by default.
Zero Line
A gray horizontal line at the value of 0 for reference, helping to understand the scale of BBW values.
Input Parameters
Center Line Period for BBW 1 (length1)
Default: 10
This controls the length of the moving average for the first BBW calculation. It defines how many periods are used to calculate the middle Bollinger Band for BBW 1.
Center Line Period for BBW 2 (length2)
Default: 20
This controls the length of the moving average for the second BBW calculation. It defines how many periods are used to calculate the middle Bollinger Band for BBW 2.
Standard Deviation Multiplier (mult)
Default: 2.0
This controls how far the upper and lower Bollinger Bands are from the center line. The multiplier affects how sensitive the Bollinger Bands are to price changes, with higher values producing wider bands.
How to Use
Adding the Indicator: Once the script is added to your TradingView account, simply apply the indicator to any chart. It will be displayed as a separate pane below the price chart, showing two BBW lines corresponding to the two different periods.
Customizing Periods: Use the settings panel to adjust the center line periods for BBW 1 and BBW 2 to match your desired trading strategy. For instance, you can analyze short-term versus long-term volatility by adjusting the periods.
Volatility Analysis:
When both BBW lines are narrow, it indicates low volatility across both short-term and long-term periods, which could suggest that a breakout is imminent.
If both BBW lines widen simultaneously, it shows that volatility is increasing in both timeframes, possibly indicating a strong trend.
Use Cases
Breakout Strategy: When the BBW lines contract significantly, it may signal that a low-volatility period is about to end, which is often followed by a price breakout in either direction.
Trend Strength: Comparing short-term and long-term BBW values can help determine if recent price movements are supported by broader market volatility or if they are isolated to the short term.
Chart Display
BBW 1: Blue line, representing the Bollinger Band Width calculated with a center line period of 10 (or your customized value).
BBW 2: Red line, representing the Bollinger Band Width calculated with a center line period of 20 (or your customized value).
Zero Line: A gray line at 0 is provided for reference, although BBW values are always positive.
Advantages of Using Double BBW
Comprehensive View of Volatility: By overlaying two BBW indicators with different timeframes, you can gain insights into both short-term and long-term market volatility trends.
Customizable: You can easily adjust the moving average periods and the standard deviation multiplier to match your preferred trading strategy or the characteristics of the asset you are trading.
Easy Visualization: The separate plots of BBW values make it easier to see shifts in market volatility, allowing you to spot potential trading opportunities.
Entry Weight Indicator(Dual Labels)이 지표는 트레이더가 동적으로 진입 비중을 결정할 수 있도록 도와주는 도구입니다. 이전 캔들의 종가를 기준으로 두 가지 다른 진입 비중을 계산하여 표시합니다.
주요 특징:
1. 두 가지 진입 비중 계산:
- 저점 기준 (EW Long): 이전 캔들 종가와 룩백 기간 내 최저가 사이의 거리를 기준으로 계산
- 고점 기준 (EW Short): 이전 캔들 종가와 룩백 기간 내 최고가 사이의 거리를 기준으로 계산
2. 시각적 표시:
- 초록색 라벨 (EW Long): 캔들 위에 표시
- 빨간색 라벨 (EW Short): 캔들 아래에 표시
- 룩백 기간 내 최고가와 최저가를 녹색과 빨간색 선으로 표시
3. 사용자 정의 파라미터:
- 원하는 손실 비율 (Desired Loss Percentage)
- 레버리지 (Leverage)
- 룩백 기간 (Lookback Period)
4. 추가 정보 표시:
- 차트 우측 상단에 이전 종가, 최고가, 최저가, 손실 비율 등의 정보를 표시
사용 방법:
1. 원하는 손실 비율, 레버리지, 룩백 기간을 설정합니다.
2. 차트에 표시되는 라벨을 통해 각 캔들에 대한 두 가지 진입 비중을 확인합니다.
3. EW Long (초록색)은 Long 진입 시 비중을, EW Short (빨간색)는 Short 진입 시 비중을 나타냅니다.
주의: 이 지표는 투자 시 직접적인 성과를 가져다주는 지표가 아니며, 실제 거래 결정 시에는 다른 분석 도구와 함께 사용하는 것이 좋습니다.
This indicator is a tool that helps traders dynamically determine their entry weight. It calculates and displays two different entry weights based on the closing price of the previous candle.
Key features:
1. Calculation of two entry weights:
- Low-based (EW Long): Calculated based on the distance between the previous candle's close and the lowest price within the lookback period
- High-based (EW Short): Calculated based on the distance between the previous candle's close and the highest price within the lookback period
2. Visual display:
- Green label (EW Long): Displayed above the candle
- Red label (EW Short): Displayed below the candle
- Highest and lowest prices within the lookback period are shown as green and red lines
3. User-defined parameters:
- Desired Loss Percentage
- Leverage
- Lookback Period
4. Additional information display:
- Information such as previous close, highest price, lowest price, and loss percentage is displayed in the upper right corner of the chart
How to use:
1. Set the desired loss percentage, leverage, and lookback period.
2. Check the two entry weights for each candle through the labels displayed on the chart.
3. EW Long (green) represents the entry weight for long positions, while EW Short (red) represents the entry weight for short positions.
Caution: This indicator does not directly lead to investment performance. When making actual trading decisions, it is advisable to use it in conjunction with other analytical tools.
EV Calculator [CHE]EV Calculator with Adjustable Boxes and Custom Colors for TradingView
Introduction:
As a trader, one of the key metrics you need to evaluate is the Expected Value (EV) of your trading strategy. Understanding EV helps you gauge whether your trades will be profitable in the long run. This TradingView script allows you to visualize your EV alongside customizable win rates and risk-to-reward ratios. With adjustable visual components, you can quickly determine whether your trading strategy has a positive or negative EV, and make informed decisions.
Features of the Script:
1. Customizable Inputs:
- Win Rate: Set your win probability (0.0 to 1.0), which represents how often your strategy is successful.
- Risk and Reward: Define how much you're risking and the potential reward for each trade.
2. Visual Representation:
- The script creates colored boxes representing different EV scenarios:
- Green Box: Indicates a good EV (>2), suggesting a highly profitable strategy.
- Yellow Box: Represents a neutral EV (between 0 and 2), where the strategy could work but is not optimal.
- Red Box: Shows a negative EV (<0), signaling that the strategy may lead to losses.
3. Adjustable Box Size:
- You can modify the width and height of the boxes to fit your chart display preferences, giving you better visual clarity based on your screen or chart style.
4. Dynamic Labels:
- Each bar in the chart includes dynamic labels showing:
- Win Rate: Displays the percentage chance of success.
- EV Value: Shows the calculated expected value based on the win rate and risk-reward ratio.
- Guide: Explains what each colored box means so that you can easily interpret the chart.
5. Scalability and Flexibility:
- The script only keeps a maximum of 20 recent entries, ensuring that your chart stays clean and organized.
- Both the number of labels and boxes adjust automatically to match your preferred settings, enhancing usability.
How the EV Calculation Works:
The formula for EV is based on a standard risk-to-reward model:
EV = (Win\ Rate \times Reward) - (Loss\ Probability \times Risk)
For example:
- If your win rate is 60% and your risk-to-reward ratio is 1:3, the script will calculate whether this strategy is expected to yield positive returns or result in long-term losses.
Example Use Case:
Let's say you are trading with a 60% win rate, risking 1 unit to gain 3 units. The script calculates that your EV is positive and represents this with a Green Box, showing you that your strategy has a high likelihood of being profitable. If your strategy slips and the win rate drops, the EV calculation will adjust, and you may see Yellow or Red Boxes, signaling a need for adjustment.
Final Thoughts:
This script is designed for traders who want to take their analysis beyond the basics. By providing real-time visualization of your EV, you can better assess whether your strategy is sound and make adjustments as needed.
How to Use:
- Adjust the input parameters for Win Rate, Risk, and Reward to match your trading strategy.
- Observe the colored boxes and labels to quickly understand if your current strategy is in a healthy EV zone.
- Use this visual feedback to refine your approach and stay on track towards profitability.
This tool simplifies the complex calculations behind EV and turns it into an intuitive and powerful decision-making aid for traders.
Now you're ready to integrate the EV Calculator with Adjustable Boxes and Custom Colors into your trading routine and start optimizing your strategies for long-term success!
Happy Trading and best regards Chervolino
RSI (Kernel Optimized) | Flux Charts💎 GENERAL OVERVIEW
Introducing our new KDE Optimized RSI Indicator! This indicator adds a new aspect to the well-known RSI indicator, with the help of the KDE (Kernel Density Estimation) algorithm, estimates the probability of a candlestick will be a pivot or not. For more information about the process, please check the "HOW DOES IT WORK ?" section.
Features of the new KDE Optimized RSI Indicator :
A New Approach To Pivot Detection
Customizable KDE Algorithm
Realtime RSI & KDE Dashboard
Alerts For Possible Pivots
Customizable Visuals
❓ HOW TO INTERPRET THE KDE %
The KDE % is a critical metric that reflects how closely the current RSI aligns with the KDE (Kernel Density Estimation) array. In simple terms, it represents the likelihood that the current candlestick is forming a pivot point based on historical data patterns. a low percentage suggests a lower probability of the current candlestick being a pivot point. In these cases, price action is less likely to reverse, and existing trends may continue. At moderate levels, the possibility of a pivot increases, indicating potential trend shifts or consolidations.Traders should start monitoring closely for confirmation signals. An even higher KDE % suggests a strong likelihood that the current candlestick could form a pivot point, which could lead to a reversal or significant price movement. These points often align with overbought or oversold conditions in traditional RSI analysis, making them key moments for potential trade entry or exit.
📌 HOW DOES IT WORK ?
The RSI (Relative Strength Index) is a widely used oscillator among traders. It outputs a value between 0 - 100 and gives a glimpse about the current momentum of the price action. This indicator then calculates the RSI for each candlesticks, and saves them into an array if the candlestick is a pivot. The low & high pivot RSIs' are inserted into two different arrays. Then the a KDE array is calculated for both of the low & high pivot RSI arrays. Explaining the KDE might be too much for this write-up, but for a brief explanation, here are the steps :
1. Define the necessary options for the KDE function. These are : Bandwidth & Nº Steps, Array Range (Array Max - Array Min)
2. After that, create a density range array. The array has (steps * 2 - 1) elements and they are calculated by (arrMin + i * stepCount), i being the index.
3. Then, define a kernel function. This indicator has 3 different kernel distribution modes : Uniform, Gaussian and Sigmoid
4. Then, define a temporary value for the current element of KDE array.
5. For each element E in the pivot RSI array, add "kernel(densityRange.get(i) - E, 1.0 / bandwidth)" to the temporary value.
6. Add 1.0 / arrSize * to the KDE array.
Then the prefix sum array of the KDE array is calculated. For each candlestick, the index closest to it's RSI value in the KDE array is found using binary search. Then for the low pivot KDE calculation, the sum of KDE values from found index to max index is calculated. For the high pivot KDE, the sum of 0 to found index is used. Then if high or low KDE value is greater than the activation threshold determined in the settings, a bearish or bullish arrow is plotted after bar confirmation respectively. The arrows are drawn as long as the KDE value of current candlestick is greater than the threshold. When the KDE value is out of the threshold, a less transparent arrow is drawn, indicating a possible pivot point.
🚩 UNIQUENESS
This indicator combines RSI & KDE Algorithm to get a foresight of possible pivot points. Pivot points are important entry, confirmation and exit points for traders. But to their nature, they can be only detected after more candlesticks are rendered after them. The purpose of this indicator is to alert the traders of possible pivot points using KDE algorithm right away when they are confirmed. The indicator also has a dashboard for realtime view of the current RSI & Bullish or Bearish KDE value. You can fully customize the KDE algorithm and set up alerts for pivot detection.
⚙️ SETTINGS
1. RSI Settings
RSI Length -> The amount of bars taken into account for RSI calculation.
Source -> The source value for RSI calculation.
2. Pivots
Pivot Lengths -> Pivot lengths for both high & low pivots. For example, if this value is set to 21; 21 bars before AND 21 bars after a candlestick must be higher for a candlestick to be a low pivot.
3. KDE
Activation Threshold -> This setting determines the amount of arrows shown. Higher options will result in more arrows being rendered.
Kernel -> The kernel function as explained in the upper section.
Bandwidth -> The bandwidth variable as explained in the upper section. The smoothness of the KDE function is tied to this setting.
Nº Bins -> The Nº Steps variable as explained in the upper section. It determines the precision of the KDE algorithm.
China's stock market Limit up / Limit downThe price limit system in China’s stock market is a regulatory measure implemented by the Chinese securities authorities to curb excessive speculation. It refers to the maximum allowable daily price fluctuation of a stock, which cannot exceed a certain percentage of the previous trading day's closing price. For regular stocks, the daily price movement limit is 10%. For stocks under special treatment (ST stocks), the maximum daily price movement is restricted to 5%. There is no price limit on the listing day of newly issued stocks or stocks undergoing a rights issue. This indicator highlights the K-lines (candlesticks) of stocks that have hit the upper or lower price limits with different background colors and lists the recent number of instances of limit-up and limit-down occurrences in a table format.
Info DisplayThis indicator can display the code, time period and current date of the selected commodity in real time in the upper right corner of the screen.
The display size of the 3 display fonts can be adjusted in the options.
Winning and Losing StreaksThe Pine Script indicator "Winning and Losing Streaks" tracks and visualizes the length of consecutive winning and losing streaks in a financial series, such as stock prices. Here’s a detailed description of the indicator, including the relevance of statistical analysis and streak tracking.
Indicator Description
The "Winning and Losing Streaks" indicator in Pine Script is designed to analyze and display streaks of consecutive winning and losing days in trading data. It helps traders and analysts understand the persistence of trends in price movements.
Here’s how it functions:
Streak Calculation:
Winning Streak: A series of consecutive days where the closing price is higher than the previous day's closing price.
Losing Streak: A series of consecutive days where the closing price is lower than the previous day's closing price.
Doji Candles: The indicator also considers Doji candles, where the difference between the opening and closing prices is minimal relative to the high-low range, and excludes these from being counted as winning or losing days.
Statistical Analysis:
The indicator computes the maximum and average lengths of winning and losing streaks.
It also tracks the current streak lengths and maintains arrays to store the historical streak data.
Visualization:
Histograms: Winning and losing streaks are visualized using histograms, which provide a clear graphical representation of streak lengths over time.
Relevance of Statistical Analysis and Streak Tracking
1. Statistical Significance of Streaks
Tracking winning and losing streaks has significant statistical implications for trading strategies and risk management:
Autocorrelation: Streaks in financial time series can reveal autocorrelation, where past returns influence future returns. Studies have shown that financial time series often exhibit autocorrelation, which can be used to forecast future price movements (Lo, 1991; Jegadeesh & Titman, 1993). Understanding streaks helps in identifying and leveraging these patterns.
Behavioral Finance: Streak analysis aligns with concepts from behavioral finance, such as the "hot-hand fallacy," where investors may perceive trends as more persistent than they are (Gilovich, Vallone, & Tversky, 1985). Statistical streak analysis provides a more objective view of trend persistence, helping to avoid biases.
2. Risk Management and Strategy Development
Risk Assessment: Identifying the length and frequency of losing streaks is crucial for managing risk and adjusting trading strategies. Long losing streaks can indicate potential strategy weaknesses or market regime changes, prompting a reassessment of trading rules and risk management practices (Brock, Lakonishok, & LeBaron, 1992).
Strategy Optimization: Statistical analysis of streaks can aid in optimizing trading strategies. For example, understanding the average length of winning and losing streaks can help in setting more effective stop-loss and take-profit levels, as well as in determining the optimal position sizing (Fama & French, 1993).
Scientific References:
Lo, A. W. (1991). "Long-Term Memory in Stock Market Prices." Econometrica, 59(5), 1279-1313. This paper discusses the presence of long-term memory in stock prices, which is relevant for understanding the persistence of streaks.
Jegadeesh, N., & Titman, S. (1993). "Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency." Journal of Finance, 48(1), 65-91. This study explores momentum and reversal strategies, which are related to the concept of streaks.
Gilovich, T., Vallone, R., & Tversky, A. (1985). "The Hot Hand in Basketball: On the Misperception of Random Sequences." Cognitive Psychology, 17(3), 295-314. This paper provides insight into the psychological aspects of streaks and persistence.
Brock, W., Lakonishok, J., & LeBaron, B. (1992). "Simple Technical Trading Rules and the Stochastic Properties of Stock Returns." Journal of Finance, 47(5), 1731-1764. This research examines the effectiveness of technical trading rules, relevant for streak-based strategies.
Fama, E. F., & French, K. R. (1993). "Common Risk Factors in the Returns on Stocks and Bonds." Journal of Financial Economics, 33(1), 3-56. This paper provides a foundation for understanding risk factors and strategy performance.
By analyzing streaks, traders can gain valuable insights into market dynamics and refine their trading strategies based on empirical evidence.
FED and ECB Interest RatesFED and ECB Interest Rates Indicator
This indicator provides a clear visual representation of the Federal Reserve (FED) and European Central Bank (ECB) interest rates, offering traders and analysts a quick way to track these crucial economic metrics.
• Displays both FED (red) and ECB (blue) interest rates on a single chart
• Shows rates in basis points in the status line for precise reading
• Uses daily data for up-to-date rate information
• Features robust error handling for consistent performance
How It Works:
• Fetches FED rate from FRED and ECB rate from ECONOMICS database
• Plots rates as percentage values on the chart
• Displays rates in basis points when hovering over the chart
Use Cases:
• Monitor central bank policies and their potential impact on markets
• Compare FED and ECB rate trends over time
• Analyze correlation between interest rates and asset prices
• Assist in fundamental analysis for forex, equities, and fixed income trading
Note:
This indicator is for informational purposes only. Always combine this data with other forms of analysis and stay informed about central bank announcements and economic events.
Enhance your trading strategy with real-time insights into two of the world's most influential interest rates!
Currency Futures StatisticsThe "Currency Futures Statistics" indicator provides comprehensive insights into the performance and characteristics of various currency futures. This indicator is crucial for portfolio management as it combines multiple metrics that are instrumental in evaluating currency futures' risk and return profiles.
Metrics Included:
Historical Volatility:
Definition: Historical volatility measures the standard deviation of returns over a specified period, scaled to an annual basis.
Importance: High volatility indicates greater price fluctuations, which translates to higher risk. Investors and portfolio managers use volatility to gauge the stability of a currency future and to make informed decisions about risk management and position sizing (Hull, J. C. (2017). Options, Futures, and Other Derivatives).
Open Interest:
Definition: Open interest represents the total number of outstanding futures contracts that are held by market participants.
Importance: High open interest often signifies liquidity in the market, meaning that entering and exiting positions is less likely to impact the price significantly. It also reflects market sentiment and the degree of participation in the futures market (Black, F., & Scholes, M. (1973). The Pricing of Options and Corporate Liabilities).
Year-over-Year (YoY) Performance:
Definition: YoY performance calculates the percentage change in the futures contract's price compared to the same week from the previous year.
Importance: This metric provides insight into the long-term trend and relative performance of a currency future. Positive YoY performance suggests strengthening trends, while negative values indicate weakening trends (Fama, E. F. (1991). Efficient Capital Markets: II).
200-Day Simple Moving Average (SMA) Position:
Definition: This metric indicates whether the current price of the currency future is above or below its 200-day simple moving average.
Importance: The 200-day SMA is a widely used trend indicator. If the price is above the SMA, it suggests a bullish trend, while being below indicates a bearish trend. This information is vital for trend-following strategies and can help in making buy or sell decisions (Bollinger, J. (2001). Bollinger on Bollinger Bands).
Why These Metrics are Important for Portfolio Management:
Risk Assessment: Historical volatility and open interest provide essential information for assessing the risk associated with currency futures. Understanding the volatility helps in estimating potential price swings, which is crucial for managing risk and setting appropriate stop-loss levels.
Liquidity and Market Participation: Open interest is a critical indicator of market liquidity. Higher open interest usually means tighter bid-ask spreads and better liquidity, which facilitates smoother trading and better execution of trades.
Trend Analysis: YoY performance and the SMA position help in analyzing long-term trends. This analysis is crucial for making strategic investment decisions and adjusting the portfolio based on changing market conditions.
Informed Decision-Making: Combining these metrics allows for a holistic view of the currency futures market. This comprehensive view helps in making informed decisions, balancing risks and returns, and optimizing the portfolio to align with investment goals.
In summary, the "Currency Futures Statistics" indicator equips investors and portfolio managers with valuable data points that are essential for effective risk management, liquidity assessment, trend analysis, and overall portfolio optimization.
Global Liquidity Index and DEMA1001. Global Liquidity Index:
The code calculates global liquidity from economic data from multiple countries and regions. Specifically, it aggregates money supply data from major economies such as the United States, Europe, China, and Japan, and sums and adjusts them to get a global liquidity index.
This index is calculated by summing data from different sources and subtracting the impact of some financial instruments (such as reverse repurchase agreements, etc.), and then converting the result into a number in trillions. This can help analyze the liquidity conditions in global money markets.
2. ROC SMA (Simple Moving Average of Rate of Change):
The code calculates the rate of change (ROC) of the global liquidity index, which is a way to measure the speed of change of the index.
Then, a simple moving average (SMA) is applied to the rate of change, which helps smooth the data and identify trends.
The ROC SMA curve is displayed in yellow to help users observe the trend of liquidity changes.
3. DEMA (Double Exponential Moving Average):
DEMA is a more complex moving average that attempts to reduce the lag of the moving average and provide a more sensitive trend response.
The calculation method is to first calculate a standard exponential moving average (EMA), then calculate the EMA of this EMA, and use these two results to calculate DEMA.
The code allows users to set the period length of DEMA (default is 100), which can adjust the speed of DEMA's response to price changes.
The DEMA curve is displayed in blue, helping users to more accurately capture the trends and changes of global liquidity indicators.
Korean Exchange Relative Volume BarchartKorean Exchange Relative Volume Barchart
The Korean Exchange Relative Volume Barchart indicator compares the trading volume of a cryptocurrency on any symbol with the combined volumes of major Korean exchanges, Upbit and Bithumb. This tool helps traders understand regional trading activities, offering insights into market sentiment influenced by Korean markets.
For example 0.5 would indicate that the Korean exchanges are doing 50% of the volume of the selected symbol.
Features:
Exchange Selection: Include or exclude Upbit and Bithumb in the comparison.
Automatic Symbol Mapping: Automatically maps the current chart's symbol to equivalent symbols on Upbit and Bithumb.
Stacked Bar Chart Visualization: Plots a stacked bar chart showing the relative volume contributions of Binance, Upbit, and Bithumb.
Usage:
Add the Indicator: Apply it to a cryptocurrency chart on TradingView.
Configure Settings: Toggle inclusion of Upbit and Bithumb in the settings.
Interpret the Chart: The stacked bar chart displays the proportion of trading volumes from each exchange.
Notes:
Symbol Compatibility: Ensure the cryptocurrency is listed on the Korean exchanges for accurate comparison.
Data Accuracy: Volumes are compared in the same base currency (e.g., BTC), so no exchange rate conversion is necessary.
Enhance your trading analysis by understanding the influence of Korean exchanges on cryptocurrency volumes with the Korean Exchange Volume Comparison indicator.
Stationarity Test: Dickey-Fuller & KPSS [Pinescriptlabs]
📊 Kwiatkowski-Phillips-Schmidt-Shin Model Indicator & Dickey-Fuller Test 📈
This algorithm performs two statistical tests on the price spread between two selected instruments: the first from the current chart and the second determined in the settings. The purpose is to determine if their relationship is stationary. It then uses this information to generate **visual signals** based on how far the current relationship deviates from its historical average.
⚙️ Key Components:
• 🧪 ADF Test (Augmented Dickey-Fuller):** Checks if the spread between the two instruments is stationary.
• 🔬 KPSS Test (Kwiatkowski-Phillips-Schmidt-Shin):** Another test for stationarity, complementing the ADF test.
• 📏 Z-Score Calculation:** Measures how many standard deviations the current spread is from its historical mean.
• 📊 Dynamic Threshold:** Adjusts the trading signal threshold based on recent market volatility.
🔍 What the Values Mean:
The indicator displays several key values in a table:
• 📈 ADF Stationarity:** Shows "Stationary" or "Non-Stationary" based on the ADF test result.
• 📉 KPSS Stationarity:** Shows "Stationary" or "Non-Stationary" based on the KPSS test result.
• 📏 Current Z-Score:** The current Z-score of the spread.
• 🔗 Hedge Ratio:** The relationship coefficient between the two instruments.
• 🌐 Market State:** Describes the current market condition based on the Z-score.
📊 How to Interpret the Chart:
• The main chart displays the Z-score of the spread over time.
• The green and red lines represent the upper and lower thresholds for trading signals.
• The area between the **Z-score** and the thresholds is filled when a trading signal is active.
• Additional charts show the **statistics of the ADF and KPSS tests** and their critical values.
**📉 Practical Example: NVIDIA Corporation (NVDA)**
Looking at the chart for **NVIDIA Corporation (NVDA)**, we can see how the indicator applies in a real case:
1. **Main Chart (Top):**
• Shows the **historical price** of NVIDIA on a weekly scale.
• A general **uptrend** is observed with periods of consolidation.
2. **KPSS & ADF Indicator (Bottom):**
• The lower chart shows the KPSS & ADF Model indicator applied to NVIDIA.
• The **green line** represents the Z-score of the spread.
• The **green shaded areas** indicate periods where the Z-score exceeded the thresholds, generating trading signals.
3. **📋 Current Values in the Table:**
• **ADF Stationarity:** Non-Stationary
• **KPSS Stationarity:** Non-Stationary
• **Current Z-Score:** 3.45
• **Hedge Ratio:** -164.8557
• **Market State:** Moderate Volatility
4. **🔍 Interpretation:**
• A Z-score of **3.45** suggests that NVIDIA’s price is significantly above its historical average relative to **EURUSD**.
• Both the **ADF** and **KPSS** tests indicate **non-stationarity**, suggesting **caution** when using mean reversion signals at this moment.
• The market state "Moderate Volatility" indicates noticeable deviation, but not extreme.
---
**💡 Usage:**
• **When Both Tests Show Stationarity:**
• **🔼 If Z-score > Upper Threshold:** Consider **buying the first instrument** and **selling the second**.
• **🔽 If Z-score < Lower Threshold:** Consider **selling the first instrument** and **buying the second**.
• **When Either Test Shows Non-Stationarity:**
• Wait for the relationship to become **stationary** before trading.
• **Market State:**
• Use this information to evaluate **general market conditions** and adjust your trading strategy accordingly.
**Mirror Comparison of the Same as Symbol 2 🔄📊**
**📊 Table Values:**
• **Extreme Volatility Threshold:** This value is displayed when the **Z-score** exceeds **100%**, indicating **extreme deviation**. It signals a potential **trading opportunity**, as the spread has reached unusually high or low levels, suggesting a **reversion or correction** in the market.
• **Mean Reversion Threshold:** Appears when the **Z-score** begins returning towards the mean after a period of **high or extreme volatility**. It indicates that the spread between the assets is returning to normal levels, suggesting a phase of **stabilization**.
• **Neutral Zone:** Displayed when the **Z-score** is near **zero**, signaling that the spread between assets is within expected limits. This indicates a **balanced market** with no significant volatility or clear trading opportunities.
• **Low Volatility Threshold:** Appears when the **Z-score** is below **70%** of the dynamic threshold, reflecting a period of **low volatility** and market stability, indicating fewer trading opportunities.
Español:
📊 Indicador del Modelo Kwiatkowski-Phillips-Schmidt-Shin & Prueba de Dickey-Fuller 📈
Este algoritmo realiza dos pruebas estadísticas sobre la diferencia de precios (spread) entre dos instrumentos seleccionados: el primero en el gráfico actual y el segundo determinado en la configuración. El objetivo es determinar si su relación es estacionaria. Luego utiliza esta información para generar señales visuales basadas en cuánto se desvía la relación actual de su promedio histórico.
⚙️ Componentes Clave:
• 🧪 Prueba ADF (Dickey-Fuller Aumentada): Verifica si el spread entre los dos instrumentos es estacionario.
• 🔬 Prueba KPSS (Kwiatkowski-Phillips-Schmidt-Shin): Otra prueba para la estacionariedad, complementando la prueba ADF.
• 📏 Cálculo del Z-Score: Mide cuántas desviaciones estándar se encuentra el spread actual de su media histórica.
• 📊 Umbral Dinámico: Ajusta el umbral de la señal de trading en función de la volatilidad reciente del mercado.
🔍 Qué Significan los Valores:
El indicador muestra varios valores clave en una tabla:
• 📈 Estacionariedad ADF: Muestra "Estacionario" o "No Estacionario" basado en el resultado de la prueba ADF.
• 📉 Estacionariedad KPSS: Muestra "Estacionario" o "No Estacionario" basado en el resultado de la prueba KPSS.
• 📏 Z-Score Actual: El Z-score actual del spread.
• 🔗 Ratio de Cobertura: El coeficiente de relación entre los dos instrumentos.
• 🌐 Estado del Mercado: Describe la condición actual del mercado basado en el Z-score.
📊 Cómo Interpretar el Gráfico:
• El gráfico principal muestra el Z-score del spread a lo largo del tiempo.
• Las líneas verdes y rojas representan los umbrales superior e inferior para las señales de trading.
• El área entre el Z-score y los umbrales se llena cuando una señal de trading está activa.
• Los gráficos adicionales muestran las estadísticas de las pruebas ADF y KPSS y sus valores críticos.
📉 Ejemplo Práctico: NVIDIA Corporation (NVDA)
Observando el gráfico para NVIDIA Corporation (NVDA), podemos ver cómo se aplica el indicador en un caso real:
Gráfico Principal (Superior): • Muestra el precio histórico de NVIDIA en escala semanal. • Se observa una tendencia alcista general con períodos de consolidación.
Indicador KPSS & ADF (Inferior): • El gráfico inferior muestra el indicador Modelo KPSS & ADF aplicado a NVIDIA. • La línea verde representa el Z-score del spread. • Las áreas sombreadas en verde indican períodos donde el Z-score superó los umbrales, generando señales de trading.
📋 Valores Actuales en la Tabla: • Estacionariedad ADF: No Estacionario • Estacionariedad KPSS: No Estacionario • Z-Score Actual: 3.45 • Ratio de Cobertura: -164.8557 • Estado del Mercado: Volatilidad Moderada
🔍 Interpretación: • Un Z-score de 3.45 sugiere que el precio de NVIDIA está significativamente por encima de su promedio histórico en relación con EURUSD. • Tanto la prueba ADF como la KPSS indican no estacionariedad, lo que sugiere precaución al usar señales de reversión a la media en este momento. • El estado del mercado "Volatilidad Moderada" indica una desviación notable, pero no extrema.
💡 Uso:
• Cuando Ambas Pruebas Muestran Estacionariedad:
• 🔼 Si Z-score > Umbral Superior: Considera comprar el primer instrumento y vender el segundo.
• 🔽 Si Z-score < Umbral Inferior: Considera vender el primer instrumento y comprar el segundo.
• Cuando Alguna Prueba Muestra No Estacionariedad:
• Espera a que la relación se vuelva estacionaria antes de operar.
• Estado del Mercado:
• Usa esta información para evaluar las condiciones generales del mercado y ajustar tu estrategia de trading en consecuencia.
Comparativo en Espejo del Mismo Como Símbolo 2 🔄📊
📊 Valores de la Tabla:
• Umbral de Volatilidad Extrema: Este valor se muestra cuando el Z-score supera el 100%, indicando desviación extrema. Señala una posible oportunidad de trading, ya que el spread entre los activos ha alcanzado niveles inusualmente altos o bajos, lo que podría indicar una reversión o corrección en el mercado.
• Umbral de Reversión a la Media: Aparece cuando el Z-score comienza a volver hacia la media tras un período de alta o extrema volatilidad. Indica que el spread entre los activos está regresando a niveles normales, sugiriendo una fase de estabilización.
• Zona Neutral: Se muestra cuando el Z-score está cerca de cero, señalando que el spread entre activos está dentro de lo esperado. Esto indica un mercado equilibrado con ninguna volatilidad significativa ni oportunidades claras de trading.
• Umbral de Baja Volatilidad: Aparece cuando el Z-score está por debajo del 70% del umbral dinámico, reflejando un período de baja volatilidad y estabilidad del mercado, indicando menos oportunidades de trading.
Correlation with AveragesThe "Correlation with Averages" indicator is designed to visualize and analyze the correlation between a selected asset's price and a base symbol's price, such as the S&P 500 (SPY). This indicator allows users to evaluate how closely an asset’s price movements align with those of the base symbol over various time periods, providing insights into market trends and potential portfolio adjustments.
Key Features:
Base Symbol and Correlation Period:
Users can specify the base symbol (default is SPY) and the period for correlation measurement (default is 252 trading days, approximating one year).
Correlation Calculation:
The indicator computes the correlation between the asset’s closing price and the base symbol’s closing price for the defined period.
Visualization:
The correlation value is plotted on the chart, with conditional background colors indicating the strength and direction of the correlation:
Red for negative correlation (below -0.5)
Green for positive correlation (above 0.5)
Yellow for neutral correlation (between -0.5 and 0.5)
Average Correlation Over Time:
Average correlations are calculated and displayed for various periods: one week, one month, one year, and five years.
A table on the chart provides dynamic updates of these average values with color-coded backgrounds to indicate correlation strength.
The Role of Correlation in Portfolio Management
Correlation is a crucial concept in portfolio management because it measures the degree to which two securities move in relation to each other. Understanding correlation helps investors construct diversified portfolios that balance risk and return. Here's why correlation is important:
Diversification:
By including assets with low or negative correlation in a portfolio, investors can reduce overall portfolio volatility and risk. For instance, if one asset is negatively correlated with another, when one performs poorly, the other may perform well, thus smoothing the overall returns.
Risk Management:
Correlation analysis helps in identifying the potential impact of one asset’s performance on the entire portfolio. Assets with high correlation can lead to concentrated risk, while those with low correlation offer better risk management.
Performance Analysis:
Correlation measures the degree to which asset returns move together. This can inform strategic decisions, such as whether to adjust positions based on expected market conditions.
Scientific References
Markowitz, H. M. (1952). "Portfolio Selection." Journal of Finance, 7(1), 77-91.
This foundational paper introduced Modern Portfolio Theory, highlighting the importance of diversification and correlation in reducing portfolio risk.
Jorion, P. (2007). Financial Risk Manager Handbook. Wiley.
This handbook provides an in-depth exploration of risk management techniques, including the use of correlation in portfolio management.
Elton, E. J., Gruber, M. J., Brown, S. J., & Goetzmann, W. N. (2014). Modern Portfolio Theory and Investment Analysis. Wiley.
This book elaborates on the concepts of correlation and diversification, offering practical insights into portfolio construction and risk management.
By utilizing the "Correlation with Averages" indicator, traders and portfolio managers can make informed decisions based on the relationship between asset prices and the base symbol, ultimately enhancing their investment strategies.
Bull/Bear Ratio By Month Table [MsF]Japanese below / 日本語説明は英文の後にあります。
-------------------------
This is an indicator that shows monthly bull-bear ratio in a table.
By specifying the start year and end year, the ratio will be calculated and showed based on the number of bullish and bearish lines in the monthly bar. It allows you to analyze the trend of each symbol and month (bullish / bearish). Up to 10 symbols can be specified.
You can take monthly bull-bear ratio for the past 10 or 20 years on the web, but with this indicator, you can narrow it down to the period in which you want to see the symbols you want to see. It is very convenient because you can take statistics at will.
Furthermore, if the specified ratio is exceeded, the font color can be changed to any color, making it very easy to read.
=== Parameter description ===
- From … Year of start of aggregation
- To … Year of end of aggregation
- Row Background Color … Row title background color
- Col Background Color … Column title background color
- Base Text Color … Text color
- Background Color … Background Color
- Border Color … Border Color
- Location … Location
- Text Size … Text Size
- Highlight Threshold … Ratio threshold, and color
- Display in counter? … Check if you want to show the number of times instead of the ratio
-------------------------
月別陰陽確率をテーブル表示するインジケータです。
開始年から終了年を指定することで、月足における陽線数および陰線数を元に確率を計算して表示します。
この機能により各シンボルおよび各月の特徴(買われやすい/売られやすい)を認識することができアノマリー分析が可能です。
シンボルは10個まで指定可能です。
過去10年、20年の月別陰陽確率は、Web上でよく見かけますが、このインジケータでは見たいシンボルを見たい期間に絞って、
自由自在に統計を取ることができるため大変便利です。
なお、指定した確率を上回った場合、文字色を任意の色に変更することができるため、大変見やすくなっています。
=== パラメータの説明 ===
- From … 集計開始年
- To … 集計終了年
- Row Background Color … 行タイトルの背景色
- Col Background Color … 列タイトルの背景色
- Base Text Color … テキストカラー
- Background Color … 背景色
- Border Color … 区切り線の色
- Location … 配置
- Text Size … テキストサイズ
- Highlight Threshold … 色変更する確率の閾値、および色
- Display in counter? … 確率ではなく回数表示する場合はチェックする
Solar System in 3D [Astro Tool w/ Zodiac]Hello Traders and Developers,
I am excited to announce my latest Open Source indicator. At the core, this is a demonstration of PineScript’s capabilities in Rendering 3D Animations, while at the same time being a practical tool for Financial Astrologists.
This 3D Engine dynamically renders all the major celestial bodies with their individual orbits, rotation speeds, polar inclinations and astrological aspects, all while maintaining accurate spatial relationships and perspective.
This is a Geocentric model of the solar system (viewed from the perspective of Earth), since that is what most Astrologists use. Thanks to the AstroLib Library created by @BarefootJoey, this model uses the real coordinates of cosmic bodies for every timestamp.
This script truly comes to life when using the “Bar Replay” mode in TradingView, as you can observe the relationships between planets and price action as time progresses, with the full animation capabilities as mentioned above.
In addition to what I have described, this indicator also displays the orbital trajectories for each cosmic body, and has labels for everything. I have also added the ability to hover on all the labels, and see a short description of what they imply in Astrology.
Optional Planetary Aspect Computation
This indicator supports all the Major Planetary Aspects, with an accuracy defined by the user (1° by default).
Conjunction: 0° Alignment. This draws a RED line starting from the center, and going through both planets.
Sextile: 60° Alignment. This draws three YELLOW lines, connecting the planets to each other and to the center.
Square: 90° Alignment. This draws three BLUE lines, connecting the planets to each other and to the center.
Trine: 120° Alignment. This draws three PURPLE lines, connecting the planets to each other and to the center.
Opposition: 180° Alignment. This draws a GREEN line starting from one planet, passing through the center and ending on the second planet.
The below image depicts a Top-Down view of the system, with the Moon in Opposition to Venus and with Mars in Square with Neptune .
Retrograde Computation
This indicator also displays when a planet enters Retrograde (Apparent Backward Motion) by making its orbital trajectory dashed and the planet name getting a red background.
The image below displays an example of Jupiter, Saturn, Neptune and Pluto in Retrograde Motion, from the camera perspective of a 65 degree inclination.
Optional Zodiac Computation (Tropical and Sidereal)
Zodiac represents the relatively stationary star formations that rest along the ecliptic plane, with planets transitioning from one to the next, each with a 30° separation (making 12 in total). I have implemented the option to switch between Tropical mode (where these stars were 2,000 years ago) and Sidereal (where these stars are today).
The image below displays the Zodiac labels with clear lines denoting where each planet falls into.
While this indicator is deployed in a separate pane, it is trivial to transfer it onto your price chart, just by clicking and dragging the graphics. After that, you can adjust the visuals by dragging the scale on the side, or optimizing model settings. You can also drag the model above or below the price, as shown in the following image:
Of course, there are a lot of options to customize this planetary model to your tastes and analytical needs. Aside from visual changes for the labels, colors or resolution you can also disable certain planets that don’t meet your needs as shown below:
Once can also infer the current lunar phases using the Aspects between the Sun and Moon. When the Moon is Opposite the Sun that is a Full Moon, while when they are Conjunct that is a New Moon (and sometimes Eclipse).
—---------------------------------------------------------------------------
I have made this indicator open source to help PineScript programmers understand how to approach 3D graphics rendering, enabling them to develop ever more capable scripts and continuously push the boundaries of what's possible on TradingView.
The code is well documented with comments and has a clear naming convention for functions and variables, to aid developers understand how everything operates.
For financial astrologists, this indicator offers a new way to visualize and correlate planetary movements, adding depth and ease to astrological market analysis.
Regards,
Hawk
Ema Z-score | viResearchEma Z-score | viResearch
Conceptual Foundation and Innovation
The "Ema Z-score" indicator introduces a novel method of analyzing price deviations from the mean by combining the Exponential Moving Average (EMA) with a Z-score calculation. The Z-score is a statistical measure that quantifies how far a value deviates from the mean in terms of standard deviations. By applying the Z-score to an EMA, this indicator provides traders with insights into the strength and momentum of price movements relative to a smoothed average. This enables better detection of overbought and oversold conditions, as well as potential trend reversals.
The use of the Z-score helps filter out noise and provides more robust signals by highlighting extreme deviations from the mean, allowing traders to make more informed decisions in both trending and ranging markets.
Technical Composition and Calculation
The "Ema Z-score" script consists of two main components: the Exponential Moving Average (EMA) and the Z-score calculation. The EMA is calculated over a user-defined length, smoothing price movements to provide a clearer trend line. The Z-score is then derived by measuring the deviation of the current EMA value from the mean of the EMA over a lookback period, divided by the standard deviation of the EMA during that same period.
For the Z-score calculation, the script first computes the mean EMA over the lookback period using the ta.ema function. It then calculates the standard deviation of the EMA over the same period using the ta.stdev function. The Z-score is determined by subtracting the mean EMA from the current EMA value and dividing by the standard deviation, producing a normalized measure of deviation from the average.
Features and User Inputs
The "Ema Z-score" script offers several customizable inputs that allow traders to adjust the indicator according to their strategies. The EMA Length controls the smoothing period of the EMA, while the Lookback Period defines how far back the script looks when calculating the mean and standard deviation for the Z-score. Customizable thresholds allow traders to define when the Z-score signals potential uptrends or downtrends, based on their chosen levels of deviation.
Practical Applications
The "Ema Z-score" indicator is designed for traders who want to better understand price deviations from the mean and use those insights to identify potential trading opportunities. This tool is particularly effective for:
Identifying Overbought and Oversold Conditions: The Z-score provides a quantitative measure of how far the price has deviated from the mean, helping traders spot extreme conditions that could lead to reversals. Detecting Trend Reversals: By monitoring when the Z-score crosses certain thresholds, traders can identify potential trend reversals early and adjust their positions accordingly. Confirming Trend Strength: The Z-score can help confirm whether a price move is backed by momentum or is likely to revert to the mean, providing additional context for trade entries and exits.
Advantages and Strategic Value
The "Ema Z-score" script offers a significant advantage by combining the smoothing effect of the EMA with the precision of Z-score analysis. This approach reduces the impact of market noise while highlighting meaningful deviations from the norm. The ability to quantify deviations in terms of standard deviations gives traders a statistical edge in identifying overbought or oversold conditions and potential trend shifts. This makes the "Ema Z-score" an effective tool for both trend-following and contrarian strategies.
Alerts and Visual Cues
The script includes alert conditions to notify traders of key Z-score threshold crossings. The "Ema Z-score Long" alert is triggered when the Z-score exceeds the upper threshold, signaling a potential upward trend. Conversely, the "Ema Z-score Short" alert signals a possible downward trend when the Z-score falls below the lower threshold. Visual cues such as color changes in the bar chart and Z-score plot help traders easily identify these conditions on the chart.
Summary and Usage Tips
The "Ema Z-score | viResearch" indicator offers a unique combination of EMA smoothing and Z-score analysis, giving traders a statistical measure of price deviations and improving their ability to detect overbought or oversold conditions, trend reversals, and trend confirmations. By incorporating this script into your trading strategy, you can better quantify price extremes and make more informed decisions in both volatile and stable markets. Whether you're focused on spotting early reversals or confirming ongoing trends, the "Ema Z-score" provides a reliable and customizable solution.
Note: Backtests are based on past results and are not indicative of future performance.