Breadth Thrust Indicator by Zweig (NYSE Data with Volume)The Breadth Thrust Indicator, based on Zweig's methodology, is used to gauge the strength of market breadth and potential bullish signals. This indicator evaluates the breadth of the market by analyzing the ratio of advancing to declining stocks and their associated volumes.
Usage:
Smoothing Length: Adjusts the smoothing period for the combined ratio of breadth and volume.
Low Threshold: Defines the threshold below which the smoothed combined ratio should fall to consider a bullish signal.
High Threshold: Sets the upper threshold that the smoothed combined ratio must exceed to confirm a bullish Breadth Thrust signal.
Signal Interpretation:
Bullish Signal: A background color change to green indicates that the Breadth Thrust condition has been met. This occurs when the smoothed combined ratio crosses above the high threshold after being below the low threshold. This signal suggests strong market breadth and potential bullish momentum.
By using this indicator, traders can identify periods of strong market participation and potential upward price movement, helping them make informed trading decisions.
Quản lý danh mục đầu tư
csv_series_libraryThe CSV Series Library is an innovative tool designed for Pine Script developers to efficiently parse and handle CSV data for series generation. This library seamlessly integrates with TradingView, enabling the storage and manipulation of large CSV datasets across multiple Pine Script libraries. It's optimized for performance and scalability, ensuring smooth operation even with extensive data.
Features:
Multi-library Support: Allows for distribution of large CSV datasets across several libraries, ensuring efficient data management and retrieval.
Dynamic CSV Parsing: Provides robust Python scripts for reading, formatting, and partitioning CSV data, tailored specifically for Pine Script requirements.
Extensive Data Handling: Supports parsing CSV strings into Pine Script-readable series, facilitating complex financial data analysis.
Automated Function Generation: Automatically wraps CSV blocks into distinct Pine Script functions, streamlining the process of integrating CSV data into Pine Script logic.
Usage:
Ideal for traders and developers who require extensive data analysis capabilities within Pine Script, especially when dealing with large datasets that need to be partitioned into manageable blocks. The library includes a set of predefined functions for parsing CSV data into usable series, making it indispensable for advanced trading strategy development.
Example Implementation:
CSV data is transformed into Pine Script series using generated functions.
Multiple CSV blocks can be managed and parsed, allowing for flexible data series creation.
The library includes comprehensive examples demonstrating the conversion of standard CSV files into functional Pine Script code.
To effectively utilize the CSV Series Library in Pine Script, it is imperative to initially generate the correct data format using the accompanying Python program. Here is a detailed explanation of the necessary steps:
1. Preparing the CSV Data:
The Python script provided with the CSV Series Library is designed to handle CSV files that strictly contain no-space, comma-separated single values. It is crucial that your CSV file adheres to this format to ensure compatibility and correctness of the data processing.
2. Using the Python Program to Generate Data:
Once your CSV file is prepared, you need to use the Python program to convert this file into a format that Pine Script can interpret. The Python script performs several key functions:
Reads the CSV file, ensuring that it matches the required format of no-space, comma-separated values.
Formats the data into blocks, where each block is a string of data that does not exceed a specified character limit (default is 4,000 characters). This helps manage large datasets by breaking them down into manageable chunks.
Wraps these blocks into Pine Script functions, each block being encapsulated in its own function to maintain organization and ease of access.
3. Generating and Managing Multiple Libraries:
If the data from your CSV file exceeds the Pine Script or platform limits (e.g., too many characters for a single script), the Python script can split this data into multiple blocks across several files.
4. Creating a Pine Script Library:
After generating the formatted data blocks, you must create a Pine Script library where these blocks are integrated. Each block of data is contained within its function, like my_csv_0(), my_csv_1(), etc. The full_csv() function in Pine Script then dynamically loads and concatenates these blocks to reconstruct the full data series.
5. Exporting the full_csv() Function:
Once your Pine Script library is set up with all the CSV data blocks and the full_csv() function, you export this function from the library. This exported function can then be used in your actual trading projects. It allows Pine Script to access and utilize the entire dataset as if it were a single, continuous series, despite potentially being segmented across multiple library files.
6. Reconstructing the Full Series Using vec :
When your dataset is particularly large, necessitating division into multiple parts, the vec type is instrumental in managing this complexity. Here’s how you can effectively reconstruct and utilize your segmented data:
Definition of vec Type: The vec type in Pine Script is specifically designed to hold a dataset as an array of floats, allowing you to manage chunks of CSV data efficiently.
Creating an Array of vec Instances: Once you have your data split into multiple blocks and each block is wrapped into its own function within Pine Script libraries, you will need to construct an array of vec instances. Each instance corresponds to a segment of your complete dataset.
Using array.from(): To create this array, you utilize the array.from() function in Pine Script. This function takes multiple arguments, each being a vec instance that encapsulates a data block. Here’s a generic example:
vec series_vector = array.from(vec.new(data_block_1), vec.new(data_block_2), ..., vec.new(data_block_n))
In this example, data_block_1, data_block_2, ..., data_block_n represent the different segments of your dataset, each returned from their respective functions like my_csv_0(), my_csv_1(), etc.
Accessing and Utilizing the Data: Once you have your vec array set up, you can access and manipulate the full series through Pine Script functions designed to handle such structures. You can traverse through each vec instance, processing or analyzing the data as required by your trading strategy.
This approach allows Pine Script users to handle very large datasets that exceed single-script limits by segmenting them and then methodically reconstructing the dataset for comprehensive analysis. The vec structure ensures that even with segmentation, the data can be accessed and utilized as if it were contiguous, thus enabling powerful and flexible data manipulation within Pine Script.
Library "csv_series_library"
A library for parsing and handling CSV data to generate series in Pine Script. Generally you will store the csv strings generated from the python code in libraries. It is set up so you can have multiple libraries to store large chunks of data. Just export the full_csv() function for use with this library.
method csv_parse(data)
Namespace types: array
Parameters:
data (array)
method make_series(series_container, start_index)
Namespace types: array
Parameters:
series_container (array)
start_index (int)
Returns: A tuple containing the current value of the series and a boolean indicating if the data is valid.
method make_series(series_vector, start_index)
Namespace types: array
Parameters:
series_vector (array)
start_index (int)
Returns: A tuple containing the current value of the series and a boolean indicating if the data is valid.
vec
A type that holds a dataset as an array of float arrays.
Fields:
data_set (array) : A chunk of csv data. (A float array)
Correlation Clusters [LuxAlgo]The Correlation Clusters is a machine learning tool that allows traders to group sets of tickers with a similar correlation coefficient to a user-set reference ticker.
The tool calculates the correlation coefficients between 10 user-set tickers and a user-set reference ticker, with the possibility of forming up to 10 clusters.
🔶 USAGE
Applying clustering methods to correlation analysis allows traders to quickly identify which set of tickers are correlated with a reference ticker, rather than having to look at them one by one or using a more tedious approach such as correlation matrices.
Tickers belonging to a cluster may also be more likely to have a higher mutual correlation. The image above shows the detailed parts of the Correlation Clusters tool.
The correlation coefficient between two assets allows traders to see how these assets behave in relation to each other. It can take values between +1.0 and -1.0 with the following meaning
Value near +1.0: Both assets behave in a similar way, moving up or down at the same time
Value close to 0.0: No correlation, both assets behave independently
Value near -1.0: Both assets have opposite behavior when one moves up the other moves down, and vice versa
There is a wide range of trading strategies that make use of correlation coefficients between assets, some examples are:
Pair Trading: Traders may wish to take advantage of divergences in the price movements of highly positively correlated assets; even highly positively correlated assets do not always move in the same direction; when assets with a correlation close to +1.0 diverge in their behavior, traders may see this as an opportunity to buy one and sell the other in the expectation that the assets will return to the likely same price behavior.
Sector rotation: Traders may want to favor some sectors that are expected to perform in the next cycle, tracking the correlation between different sectors and between the sector and the overall market.
Diversification: Traders can aim to have a diversified portfolio of uncorrelated assets. From a risk management perspective, it is useful to know the correlation between the assets in your portfolio, if you hold equal positions in positively correlated assets, your risk is tilted in the same direction, so if the assets move against you, your risk is doubled. You can avoid this increased risk by choosing uncorrelated assets so that they move independently.
Hedging: Traders may want to hedge positions with correlated assets, from a hedging perspective, if you are long an asset, you can hedge going long a negatively correlated asset or going short a positively correlated asset.
Grouping different assets with similar behavior can be very helpful to traders to avoid over-exposure to those assets, traders may have multiple long positions on different assets as a way of minimizing overall risk when in reality if those assets are part of the same cluster traders are maximizing their risk by taking positions on assets with the same behavior.
As a rule of thumb, a trader can minimize risk via diversification by taking positions on assets with no correlations, the proposed tool can effectively show a set of uncorrelated candidates from the reference ticker if one or more clusters centroids are located near 0.
🔶 DETAILS
K-means clustering is a popular machine-learning algorithm that finds observations in a data set that are similar to each other and places them in a group.
The process starts by randomly assigning each data point to an initial group and calculating the centroid for each. A centroid is the center of the group. K-means clustering forms the groups in such a way that the variances between the data points and the centroid of the cluster are minimized.
It's an unsupervised method because it starts without labels and then forms and labels groups itself.
🔹 Execution Window
In the image above we can see how different execution windows provide different correlation coefficients, informing traders of the different behavior of the same assets over different time periods.
Users can filter the data used to calculate correlations by number of bars, by time, or not at all, using all available data. For example, if the chart timeframe is 15m, traders may want to know how different assets behave over the last 7 days (one week), or for an hourly chart set an execution window of one month, or one year for a daily chart. The default setting is to use data from the last 50 bars.
🔹 Clusters
On this graph, we can see different clusters for the same data. The clusters are identified by different colors and the dotted lines show the centroids of each cluster.
Traders can select up to 10 clusters, however, do note that selecting 10 clusters can lead to only 4 or 5 returned clusters, this is caused by the machine learning algorithm not detecting any more data points deviating from already detected clusters.
Traders can fine-tune the algorithm by changing the 'Cluster Threshold' and 'Max Iterations' settings, but if you are not familiar with them we advise you not to change these settings, the defaults can work fine for the application of this tool.
🔹 Correlations
Different correlations mean different behaviors respecting the same asset, as we can see in the chart above.
All correlations are found against the same asset, traders can use the chart ticker or manually set one of their choices from the settings panel. Then they can select the 10 tickers to be used to find the correlation coefficients, which can be useful to analyze how different types of assets behave against the same asset.
🔶 SETTINGS
Execution Window Mode: Choose how the tool collects data, filter data by number of bars, time, or no filtering at all, using all available data.
Execute on Last X Bars: Number of bars for data collection when the 'Bars' execution window mode is active.
Execute on Last: Time window for data collection when the `Time` execution window mode is active. These are full periods, so `Day` means the last 24 hours, `Week` means the last 7 days, and so on.
🔹 Clusters
Number of Clusters: Number of clusters to detect up to 10. Only clusters with data points are displayed.
Cluster Threshold: Number used to compare a new centroid within the same cluster. The lower the number, the more accurate the centroid will be.
Max Iterations: Maximum number of calculations to detect a cluster. A high value may lead to a timeout runtime error (loop takes too long).
🔹 Ticker of Reference
Use Chart Ticker as Reference: Enable/disable the use of the current chart ticker to get the correlation against all other tickers selected by the user.
Custom Ticker: Custom ticker to get the correlation against all the other tickers selected by the user.
🔹 Correlation Tickers
Select the 10 tickers for which you wish to obtain the correlation against the reference ticker.
🔹 Style
Text Size: Select the size of the text to be displayed.
Display Size: Select the size of the correlation chart to be displayed, up to 500 bars.
Box Height: Select the height of the boxes to be displayed. A high height will cause overlapping if the boxes are close together.
Clusters Colors: Choose a custom colour for each cluster.
Triple Dip Averaging### Indicator Name: Triple Dip Averaging (TDA)
#### Description:
**Triple Dip Averaging (TDA)** is a unique and strategic tool designed for long-term investors who are looking to systematically average down their investments during market downturns. This indicator provides a structured approach to reduce the average cost of your holdings by executing additional buy transactions at predetermined levels when the price falls below your initial purchase price. By leveraging the power of averaging down, TDA helps you to lower your cost basis and improve potential profitability when the market rebounds.
#### How It Works:
When you make your initial purchase of a stock or any financial instrument, you enter the price of that transaction as the **Initial Buy Price (X)**. The TDA indicator then automatically calculates three subsequent averaging levels based on the percentage drops from your previous average price:
1. **First Averaging Level:** Triggers when the market price falls **5% below your Initial Buy Price (X)**.
2. **Second Averaging Level:** Triggers when the market price falls **10% below your New Average Price (Y)**, which is calculated after the first averaging.
3. **Third Averaging Level:** Triggers when the market price falls **15% below your New Average Price (Z)**, which is calculated after the second averaging.
These levels are plotted on your chart as visual guides, showing where you would perform your averaging transactions. This structured approach not only helps you to systematically manage your investments but also takes the emotion out of decision-making during volatile market conditions.
#### How to Use:
1. **Initial Setup:**
- Input your **Initial Buy Price (X)** into the indicator settings.
- Set the quantity of shares or units you bought at this price.
- Enable the alert feature if you wish to be notified when the price reaches each averaging level.
2. **Interpreting the Indicator:**
- **Blue Horizontal Line:** Represents your Initial Buy Price (X).
- **Red Dashed Lines:** Represent the levels where averaging down should occur.
- The first red dashed line indicates the 5% drop level (first averaging level).
- The second red dashed line indicates the 10% drop level (second averaging level).
- The third red dashed line indicates the 15% drop level (third averaging level).
3. **Executing Your Trades:**
- When the market price reaches each red dashed line, consider placing a buy order for the same quantity as your initial purchase. This will lower your average buy price.
- The indicator provides you with exact levels for where to average down, helping you to be prepared and disciplined in your approach.
4. **Alerts:**
- Alerts are built into the indicator for each averaging level. You will receive notifications when the market price reaches these critical points, allowing you to act quickly and efficiently.
#### Benefits:
- **Systematic Approach:** Removes emotion from trading decisions by following a pre-determined plan.
- **Improved Risk Management:** By averaging down at specific intervals, you can lower your cost basis and potentially reduce losses.
- **Customizable Alerts:** Stay informed with alerts that notify you when it’s time to consider additional purchases.
**Triple Dip Averaging (TDA)** is a powerful addition to any long-term investor's toolkit, providing a disciplined approach to managing your investments through market fluctuations. Whether you're a seasoned investor or new to the market, TDA helps you navigate volatility with confidence.
Market Structure Based Stop LossMarket Structure Based Dynamic Stop Loss
Introduction
The Market Structure Based Stop Loss indicator is a strategic tool for traders designed to be useful in both rigorous backtesting and live testing, by providing an objective, “guess-free” stop loss level. This indicator dynamically plots suggested stop loss levels based on market structure, and the concepts of “interim lows/highs.”
It provides a robust framework for managing risk in both long and short positions. By leveraging historical price movements and real time market dynamics, this indicator helps traders identify quantitatively consistent risk levels while optimizing trade returns.
Legend
This indicator utilizes various inputs to customize its functionality, including "Stop Loss Sensitivity" and "Wick Depth," which dictate how closely the stop loss levels hug the price's highs and lows. The stop loss levels are plotted as lines on the trading chart, providing clear visual cues for position management. As seen in the chart below, this indicator dynamically plots stop loss levels for both long and short positions at every point in time.
A “Stop Loss Table” is also included, in order to enhance precision trading and increase backtesting accuracy. It is customizable in both size and positioning.
Case Study
Methodology
The methodology behind this indicator focuses on the precision placement of stop losses using market structure as a guide. It calculates stop losses by identifying the "lowest close" and the corresponding "lowest low" for long setups, and inversely for short setups. By adjusting the sensitivity settings, traders can tweak the indicator's responsiveness to price changes, ensuring that the stop losses are set with a balance between tight risk control and enough room to avoid premature exits due to market noise. The indicator's ability to adapt to different trading styles and time frames makes it an essential tool for traders aiming for efficiency and effectiveness in their risk management strategies.
An important point to make is the fact that the stop loss levels are always placed within the wicks. This is important to avoid what can be described as a “floating stop loss”. A stop loss placed outside of a wick is susceptible to an outsized degree of slippage. This is because traders always cluster their stop losses at high/low wicks, and a stop loss placed outside of this level will inevitably be caught in a low liquidity cascade or “wash-out.” When price approaches a cluster of stop losses, it is highly probable that you will be stopped out anyway, so it is prudent to attempt to be the trader who gets stopped out first in order to avoid high slippage, and losses above what you originally intended.
// For long positions: stop-loss is slightly inside the lowest wick
float dynamic_SL_Long = lowestClose - (lowestClose - lowestLow) * (1 - WickDepth)
// For short positions: stop-loss is slightly inside the highest wick
float dynamic_SL_Short = highestClose + (highestHigh - highestClose) * (1 - WickDepth)
The percentage depth of the wick in which the stop loss is placed is customisable with the “Wick Depth” variable, in order to customize stop loss strategies around the liquidity of the market a trader is executing their orders in.
[2024] Inverted Yield CurveInverted Yield Curve Indicator
Overview:
The Inverted Yield Curve Indicator is a powerful tool designed to monitor and analyze the yield spread between the 10-year and 2-year US Treasury rates. This indicator helps traders and investors identify periods of yield curve inversion, which historically have been reliable predictors of economic recessions.
Key Features:
Yield Spread Calculation: Accurately calculates the spread between the 10-year and 2-year Treasury yields.
Visual Representation: Plots the yield spread on the chart, with clear visualization of positive and negative spreads.
Inversion Highlighting: Background shading highlights periods where the yield curve is inverted (negative spread), making it easy to spot critical economic signals.
Alerts: Customizable alerts notify users when the yield curve inverts, allowing timely decision-making.
Customizable Yield Plots: Users can choose to display the individual 2-year and 10-year yields for detailed analysis.
How It Works:
Data Sources: Utilizes the Federal Reserve Economic Data (FRED) for fetching the 2-year and 10-year Treasury yield rates.
Spread Calculation: The script calculates the difference between the 10-year and 2-year yields.
Visualization: The spread is plotted as a blue line, with a grey zero line for reference. When the spread turns negative, the background turns red to indicate an inversion.
Customizable Plots: Users can enable or disable the display of individual 2-year and 10-year yields through simple input options.
Usage:
Economic Analysis: Use this indicator to anticipate potential economic downturns by monitoring yield curve inversions.
Market Timing: Identify periods of economic uncertainty and adjust your investment strategies accordingly.
Alert System: Set alerts to receive notifications whenever the yield curve inverts, ensuring you never miss crucial economic signals.
Important Notes:
Data Accuracy: Ensure that the FRED data symbols (FRED
and FRED
) are correctly referenced and available in your TradingView environment.
Customizations: The script is designed to be flexible, allowing users to customize plot colors and alert settings to fit their preferences.
Disclaimer:
This indicator is intended for educational and informational purposes only. It should not be considered as financial advice. Always conduct your own research and consult with a financial advisor before making investment decisions.
Portfolio Index Generator [By MUQWISHI]▋ INTRODUCTION:
The “Portfolio Index Generator” simplifies the process of building a custom portfolio management index, allowing investors to input a list of preferred holdings from global securities and customize the initial investment weight of each security. Furthermore, it includes an option for rebalancing by adjusting the weights of assets to maintain a desired level of asset allocation. The tool serves as a comprehensive approach for tracking portfolio performance, conducting research, and analyzing specific aspects of portfolio investment. The output includes an index value, a table of holdings, and chart plotting, providing a deeper understanding of the portfolio's historical movement.
_______________________
▋ OVERVIEW:
The image can be taken as an example of building a custom portfolio index. I created this index and named it “My Portfolio Performance”, which comprises several global companies and crypto assets.
_______________________
▋ OUTPUTS:
The output can be divided into 4 sections:
1. Portfolio Index Title (Name & Value).
2. Portfolio Specifications.
3. Portfolio Holdings.
4. Portfolio Index Chart.
1. Portfolio Index Title, displays the index name at the top, and at the bottom, it shows the index value, along with the chart timeframe, e.g., daily change in points and percentage.
2. Portfolio Specifications, displays the essential information on portfolio performance, including the investment date range, initial capital, returns, assets, and equity.
3. Portfolio Holdings, a list of the holding securities inside a table that contains the ticker, average entry price, last price, return percentage of the portfolio's initial capital, and customized weighted percentage of the portfolio. Additionally, a tooltip appears when the user passes the cursor over a ticker's cell, showing brief information about the company, such as the company's name, exchange market, country, sector, and industry.
4. Index Chart, display a plot of the historical movement of the index in the form of a bar, candle, or line chart.
_______________________
▋ INDICATOR SETTINGS:
Section(1): Style Settings
(1) Naming the index.
(2) Table location on the chart and cell size.
(3) Sorting Holdings Table. By securities’ {Return(%) Portfolio, Weight(%) Portfolio, or Ticker Alphabetical} order.
(4) Choose the type of index: {Equity or Return (%)}, and the plot type for the index: {Candle, Bar, or Line}.
(5) Positive/Negative colors.
(6) Table Colors (Title, Cell, and Text).
(7) To show/hide any indicator’s components.
Section(2): Performance Settings
(1) Calculation window period: from DateTime to DateTime.
(2) Initial Capital and specifying currency.
(3) Option to enable portfolio rebalancing in {Monthly, Quarterly, or Yearly} intervals.
Section(3): Portfolio Holdings
(1) Enable and count security in the investment portfolio.
(2) Initial weight of security. For example, if the initial capital is $100,000 and the weight of XYZ stock is 4%, the initial value of the shares would be $4,000.
(3) Select and add up to 30 symbols that interested in.
Please let me know if you have any questions.
[KF] Sector & Industry RemappingThis script remaps TradingView's sector and industry categories to standard classifications and displays them in the top-right corner of the chart making it easy to quickly identify a security's sector and industry. This tool is useful for traders and analysts who prefer standard industry classifications while using TradingView's charts.
BB Position CalculatorPosition Size Calculator Instructions
Overview
The Position Size Calculator is designed to help traders automatically determine the appropriate lot size based on the dollar amount they are willing to risk. It includes features for automatic lot sizing, fixed lot risk calculations, take profit calculations (both automatic and fixed), max run-up, and max drawdown. Calculated values are displayed in ticks, points, and USD.
Key Features
• Automatic Lot Sizing: Automatically calculates lot size based on the amount of money you are willing to risk.
• Fixed Lot Risk Calculations: Provides risk calculations for fixed lot sizes.
• Take Profit Calculations: Offers both automatic and fixed take profit calculations.
• Max Run-Up and Max Drawdown: Monitors and displays the maximum run-up and drawdown of your trade.
• Detailed Metrics: Displays all calculated values in ticks, points, and USD.
Setup Instructions
1. Add and Remove for Each Position: The calculator is designed to be added to your chart for each new position. Once your preferences are set the first time, save them as your default to retain your settings for future use.
2. Adding the Indicator to Favorites:
• Use the TradingView keyboard shortcut “/” then type “pos.”
• Use the arrow key to select the Position Size Calculator and press enter.
• Close the indicator selection pop-up.
3. Setting the Trigger Price:
• A blue pop-up labeled “SET TRIGGER PRICE” will appear at the bottom of the chart.
• Click on the chart at the price level where you want to enter the trade.
4. Setting the Stop Loss:
• The pop-up will change to “SET STOP LOSS.”
• Click on the chart at the price level where your stop loss will be set.
5. Setting the Take Profit:
• The pop-up will change to “SET TAKE PROFIT.”
• Click on the chart at the price level where you want to take profit. If you have selected the option to overwrite with a set risk/reward ratio (R:R), the calculation will use this price level.
6. Setting the Trade Window Start:
• The pop-up will change to “SET TRADE WINDOW START.”
• Click on the bar in time where you want the indicator to start monitoring for price to trigger the position.
7. Adjusting the Position:
• Clicking on any part of the indicator will display draggable lines, allowing you to fine-tune the position that was previously plotted by the first four chart clicks.
Additional Notes
• Compatibility: This calculator has only been tested with futures trading.
• Customization: Once your preferences are set, save them as your default to make setup quicker for future trades.
• Support: If you have any questions or feature requests, please feel free to reach out.
SL ManagerSTOP LOSS MANAGER
Overview:
The "SL Manager" indicator is designed to assist traders in managing their stop loss (SL) and take profit (TP) levels for both long and short positions. This tool helps you visualize intermediate levels, enhancing your trading decisions by providing crucial information on the chart.
Usage:
This indicator is particularly useful for traders who want to manage their trades more effectively by visualizing potential adjustment points for their stop loss and take profit levels. It helps in making informed decisions to maximize profits and minimize risks by providing clear levels to take partial profits and adjust stop losses.
Features:
Position Input: Select between "long" and "short" positions.
Entry Price: Specify the entry price of your trade.
Take Profit: Define the price level at which you want to take profit.
Stop Loss: Set the stop loss price level to manage your risk.
Intermediate Levels:
For both long and short positions, the indicator calculates and plots the following intermediate levels:
50% Take Profit (TP 50%): Midway between the entry price and the take profit level, where you can take partial profits and move your SL up to the 25% mark.
75% Take Profit (TP 75%): Three-quarters of the way from the entry price to the take profit level, where you can take partial profits and move your SL to breakeven.
Stop Loss Move to 25% (SL Move to 25%): A level where the stop loss can be adjusted to lock in profits.
Visualization:
The indicator plots the calculated levels directly on the chart, provided the data for the current day is available. Different color codes and line styles distinguish between the various levels:
TP 50% and TP 75% are plotted in green.
SL Move to 25% is plotted in red .
Entry/Breakeven is plotted in blue.
Position Size CalculatorThe Position Size Calculator (PSC) is a comprehensive tool designed to assist traders in managing their trades risk by accurately calculating the optimal position size based on account settings, trade levels, and risk management parameters. This indicator helps traders make informed decisions by providing critical information about potential profit and loss , risk-reward ratio (RRR) , and position size (PS) .
█ Key Features
• Customizable Account Settings: Define your account size , currency , risk tolerance , and commission structure to personalize the calculations.
• Real-Time Trade Levels: Easily input your entry , stop loss , and take profit prices directly on the chart for immediate calculations.
• Visual Indicators: Clearly see your entry, stop loss, and take profit levels with customizable colors and labels.
• Comprehensive Position Information: View detailed information about your position, including potential profit and loss , risk-reward ratio , and position size .
• Currency Conversion: Automatically convert prices to your account currency, making it easy to manage trades in different markets.
• Hide Metrics : Choose which metrics to display to avoid emotional influence on your trading decisions (e.g., hiding PnL).
█ Conclusion
The Position Size Calculator is an essential tool for traders looking to optimize their trading strategies and manage risk effectively . By providing detailed calculations and visual indicators, this tool helps you make informed decisions, improving your overall trading performance.
█ Important
• Ensure that your stop loss and take profit levels are correctly set relative to your entry price to avoid errors.
• The default commission setting considers both entry and exit commissions. Adjust accordingly if only one commission is applicable.
Consider using this tool to manage every trade risk correctly and prevent significant drawdowns.
Hope you like it. Happy trading!
SP500 Earnings Yield Spread: SP500 vs 3 Month & 10 Year TreasuryAdd the SP500 ttm Earnings Yield Spreads vs the 3 Month and 10 Year Treasury Rates.
Short Spread = SP500 E/P ttm - 3 Month Treasury Rate
Long Spread = SP500 E/P ttm - 10 Year Treasury Rate
Symbol "SP500_EARNINGS_YIELD_MONTH" as the SP500 Earnings Yield
Symbol "US03MY" as the 3 Month Treasury Rate
Symbol "US10Y" as the 10 Year Treasury Rate
Based on research suggesting Earnings Yield and Interest Rates may have predictive power of future returns:
- Market-Timing Strategies That Worked? - Pu Shen
- Valuation Ratios and the Long-Run Stock Market Outlook - Campbell and Shiller
Inputs:
Short Term Spread - Line for Short Term Spread
Long Term Spread - Line for Long Term Spread
Zero Line - Horizontal line at 0
Color Lines Based on Spread - Color the spreads green/red if spread is positive/negative
Short 10th PCT - Line for Short Term Spread 10th percentile of historical values
Long 10th PCT - Line for Long Term Spread 10th percentile of historical values
Shade Below 10 PCT: Spread Must be Negative - Requirement the spread is negative to shade background
Shade Background Below Short 10th Percentile - Shade the background if the Short Term Spread is below its 10th percentile. (and spread is negative if input above chosen)
Shade Background Below Long 10th Percentile - Shade the background if the Long Term Spread is below its 10th percentile. (and spread is negative if input above chosen)
Several Fundamentals in One [aep]
**Financial Ratios Indicator**
This comprehensive Financial Ratios Indicator combines various essential metrics to help traders and investors evaluate the financial health of companies at a glance. The following categories are included:
### Valuation Ratios
- **P/B Ratio (Price to Book Ratio)**: Assesses if a stock is undervalued or overvalued by comparing its market price to its book value.
- **P/E Ratio TTM (Price to Earnings Ratio Trailing Twelve Months)**: Indicates how many years of earnings would be needed to pay the current stock price by comparing the stock price to earnings per share over the last twelve months.
- **P/FCF Ratio TTM (Price to Free Cash Flow Ratio Trailing Twelve Months)**: Evaluates a company's ability to generate free cash flow by comparing the market price to free cash flow per share over the last twelve months.
- **Tobin Q Ratio**: Indicates whether the market is overvaluing or undervaluing a company’s assets by comparing market value to replacement cost.
- **Piotroski F-Score (0-9)**: A scoring system that identifies financially strong companies based on fundamental metrics.
### Efficiency
- **Net Margin % TTM**: Measures profitability by calculating the percentage of revenue that becomes net profit after all expenses and taxes.
- **Free Cashflow Margin %**: Indicates a company’s efficiency in generating free cash flow from its revenues by showing the percentage of revenue that translates into free cash flow.
- **ROE%, ROIC%, ROA%**: Evaluate a company’s efficiency in generating profits from equity, invested capital, and total assets, respectively.
### Liquidity Metrics
- **Debt to Equity Ratio**: Shows the level of debt relative to equity, helping assess financial leverage.
- **Current Ratio**: Measures a company's ability to pay short-term debts by comparing current assets to current liabilities.
- **Long Term Debt to Assets**: Evaluates the level of long-term debt in relation to total assets.
### Dividend Policy
- **Retention Ratio % TTM**: Indicates the proportion of earnings reinvested in the company instead of distributed as dividends.
- **Dividend/Earnings Ratio % TTM**: Measures the percentage of earnings paid out as dividends to shareholders.
- **RORE % TTM (Return on Retained Earnings)**: Assesses how effectively a company utilizes retained earnings to generate additional profits.
- **Dividend Yield %**: Indicates the dividend yield of a stock by comparing annual dividends per share to the current stock price.
### Growth Ratios
- **EPS 1yr Growth %**: Measures the percentage growth of earnings per share over the last year.
- **Revenue 1yr Growth %**: Evaluates the percentage growth of revenue over the last year.
- **Sustainable Growth Rate**: Indicates the growth rate a company can maintain without increasing debt, assessing sustainable growth using internal resources.
Utilize this indicator to streamline your analysis of financial performance and make informed trading decisions.
CAGR - Candle based BackTesterThe "CAGR - Candle based BackTester" is a tool for traders and investors seeking precise insights into individual candle performance!
Do you want to backtest based on candles and understand their CAGR? Curious about the average CAGR of all candles? Interested in comparing how an individual candle performs against others? Then this tool is your go-to solution.
How It Works:
Candle Selection: Specify a start date, and watch as the script tracks investments from that point forward.
Dynamic Calculations: Experience real-time CAGR calculations that adapt as market conditions evolve.
CAGR Display: At the final candle, gain insights into individual CAGR, average CAGR of all candles, alpha (difference), and outperformance percentage—all conveniently displayed for informed decision-making.
Key Features:
Accurate Candle-based CAGR Calculation: Gain clarity on investment performance with precise CAGR metrics.
Lumpsum Investment Tracking: Track lumpsum investments seamlessly with detailed share and investment calculations.
Outperformance Metrics: Measure how your investment performs relative to others with dedicated outperformance metrics.
User-Friendly Visualization: Access intuitive charts and visuals that simplify complex financial data.
ICT Market Structure Screener (Zeiierman)█ Overview
The ICT Market Structure Screener (Zeiierman) is designed to identify and display key market structure levels and patterns based on Smart Money Concepts. It highlights bullish and bearish structures, premium and discount levels, and generates alerts for significant market structure changes, making it a valuable tool for traders looking to understand institutional trading behaviors and market trends. A key feature of this indicator is its screener function, which allows traders to monitor multiple symbols simultaneously. This feature provides a consolidated view of the market structure for various assets, making it easier to identify trading opportunities across a diverse portfolio.
█ How It Works
The ICT Market Structure Screener operates by identifying high and low pivot points within a specified period, then analyzing these pivots to determine changes in market structure. The indicator tracks price movements and categorizes them into bullish or bearish structures, indicating potential trend reversals or continuations. By plotting premium and discount levels, it helps traders identify overbought and oversold conditions. The indicator also provides real-time updates and alerts for significant changes in the market structure.
█ Terminology
ChoCH (Change of Character): Indicates a potential reversal in market direction. It is identified when the price breaks a significant high or low, suggesting a shift from a bullish to bearish trend or vice versa.
SMS (Smart Money Shift): Represents the transition phase in market structure where smart money begins accumulating or distributing assets. It typically follows a BMS and indicates the start of a new trend.
BMS (Bullish/Bearish Market Structure): Confirms the trend direction. Bullish Market Structure (BMS) confirms an uptrend, while Bearish Market Structure (BMS) confirms a downtrend. It is characterized by a series of higher highs and higher lows (bullish) or lower highs and lower lows (bearish).
Premium: A zone where the price is considered overbought. It is calculated as the upper range of the current market structure and indicates a potential area for selling or shorting.
Mid Range: The midpoint between the high and low of the market structure. It often acts as a support or resistance level, helping traders identify potential reversal or continuation points.
Discount: A zone where the price is considered oversold. It is calculated as the lower range of the current market structure and indicates a potential area for buying or going long.
█ How to Use
The ICT Market Structure Screener allows traders to follow smart money moves in the market more effectively. By identifying key market levels and monitoring bullish and bearish structures, traders can easily spot trend changes and strong trends. The indicator's premium and discount levels help identify overbought and oversold conditions, providing valuable entry and exit points. Alerts for ChoCH, SMS, and BMS keep traders informed about significant market changes, enabling real-time adjustments to trading strategies.
The screener functionality is particularly valuable for monitoring multiple markets simultaneously. The screener table displays critical information such as current price, trend direction, signal type, and premium/discount levels for each symbol. This makes it easier to track the market structure of various assets at a glance and quickly identify trading opportunities across different markets.
Example Strategies:
⚪ Trend Following: Use the indicator to identify the current market trend (bullish or bearish) and trade in the direction of the trend. Enter trades on pullbacks to premium (for shorts) or discount (for longs) levels.
⚪ Reversal Trading: Look for ChoCH signals to identify potential trend reversals. Enter trades when the price breaks a significant high or low and confirms a change in market structure, or wait for a retest of the nearest Orderblock that was formed.
⚪ Support and Resistance: Utilize the mid-range, premium, and discount levels as support and resistance zones. Enter trades when the price approaches these levels and shows signs of reversal or continuation.
⚪ Multi-Symbol Analysis: Use the screener table to monitor multiple symbols and quickly assess their market structure. This helps in diversifying trading opportunities and managing a portfolio of assets efficiently.
█ Settings
Period: The pivot period for calculating the structure. Increasing the period captures broader trends, making the structure more representative of long-term movements. Decreasing the period focuses on shorter-term trends, increasing sensitivity.
Response: Enabling this option uses the response period instead of the pivot period, providing more flexibility in capturing short-term or long-term structures. The period for the response, which determines the structure's sensitivity. Increasing the response period smoothens the structure, making it less reactive to short-term fluctuations. Decreasing the response period makes the structure more responsive to short-term changes.
Structure Display: Choose between displaying the active range or the previous range. 'Active Range' shows real-time premium, discount, and mid-range levels based on the current structure. 'Previous Range' displays past ranges, useful for analyzing historical support/resistance levels.
Ticker Symbols: List of symbols to include in the screener. Enabling the option includes the symbol in the screener, allowing the user to track its structure. Disabling it excludes the symbol from the screener, reducing the number of tracked symbols.
-----------------
Disclaimer
The information contained in my Scripts/Indicators/Ideas/Algos/Systems does not constitute financial advice or a solicitation to buy or sell any securities of any type. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
My Scripts/Indicators/Ideas/Algos/Systems are only for educational purposes!
Nebula SAR Echo📈 Overview:
The "Nebula SAR Echo" is a sophisticated technical analysis tool designed for traders seeking enhanced trend detection. This indicator combines the robust Parabolic SAR mechanism with gradient color coding to provide clear visual insights into market trends.
🎯 Key Features:
Advanced Parabolic SAR Calculation:
Utilizes dynamic coefficients for more responsive and accurate trend detection.
Highlights trend reversals with visual markers for immediate identification.
Gradient Color Coding:
Gradient colors dynamically reflect the strength and direction of the trend.
Bullish trends are represented in shades of green, while bearish trends are shown in shades of red.
User-Friendly Customization:
Easily adjustable parameters for acceleration factors and gradient color use.
💡 Benefits:
Enhanced Decision Making:
Combines real-time trend analysis to assist traders in making more informed decisions.
Visual Clarity:
Clear visual markers and gradient color coding simplify the interpretation of market trends.
Helps traders quickly identify key turning points and potential future price paths.
🔍 Use Cases:
Trend Identification:
Ideal for identifying ongoing trends and potential reversals in various market conditions.
Useful for both short-term trading strategies and long-term investment planning.
Risk Management:
Gradient color coding aids in assessing trend strength and potential volatility.
Traders can set more precise stop-loss and take-profit levels based on the trend strength.
⚙️ How to Use:
1. Parameter Setup:
Set the desired acceleration factors (start, increment, and max) for the Parabolic SAR.
Enable or disable gradient colors based on personal preference.
2. Interpretation:
Use the SAR values and gradient colors to gauge current market trends.
3. Alerts:
Set up alert conditions for bullish and bearish reversals to stay notified of significant market changes.
🔹 Conclusion:
The "Nebula SAR Echo" is a versatile and powerful tool for traders who require an in-depth analysis of market trends. By leveraging the advanced Parabolic SAR calculation and gradient color coding, this indicator provides a comprehensive view of market conditions, making it an indispensable addition to any trader's toolkit.
Easy Scalping Lot Calculator for ForexThe calculator was created to make it easier to calculate the lot size on Forex. I planned to use it for the following pairs: AUDCAD, AUDCHF, AUDJPY, AUDUSD, EURAUD, EURCAD, EURCHF, EURGBP, EURJPY, EURNZD, EURUSD, GBPCHF, GBPJPY, GBPUSD, NZDUSD, USDCAD, USDCHF, USDJPY, XAUUSD.
The indicator is a table that shows the calculation of the lot for a predetermined stop loss.
For example, you are planning a trade, have calculated a stop loss of 15 points, and by checking the table you understand approximately what lot you need to use to limit your risk.
In the settings you can change the risk and also determine the stop loss value in points.
The calculator does not take into account the spread in the calculations.
There are websites where you can accurately calculate the lot, but if you trade on small time frames this is not suitable for you.
The calculator uses the formula:
Lot size = maximum risk / stop loss (in pips) / minimum pip value x minimum trading lot.
Position Size Calculator for ContractDescription:
Position Size Calculator is a versatile Pine Script tool designed to help traders manage their risk and position sizing effectively. This script calculates essential trading metrics and visualizes them directly on your chart, helping you make informed trading decisions.
Features:
- Account Size & Risk Management:
- Account Size: Input your total account balance to calculate position sizes.
- Maximum Risk: Define how much of your account you are willing to risk per trade in dollars.
- Pip Value: Set the value of a single pip for one contract, which is crucial for calculating risk
and position size.
Trade Setup Visualization:
- Entry Price: Specify the price at which you plan to enter the trade.
- Stop Loss: Define your stop loss level to manage your risk.
- Take Profit: Set your target profit level for the trade.
- Visualize the Entry, Stop Loss, and Take Profit levels on your chart with customizable line
colors and text sizes.
- View the distance in pips between the Entry, Stop Loss, and Take Profit levels.
Position Size Calculation:
- Calculates the number of contracts to open based on your risk tolerance and the pip value.
- Displays the maximum number of contracts you can open given your risk parameters.
Customizable Table Display:
- Table Position: Choose the position of the summary table on the chart (Top-Left, Top-Right,
Bottom-Left, Bottom-Right, etc.).
- Table Text Size: Adjust the text size for the summary table.
- Table Background Color: Set the background color for the summary table.
- Table Border Color: Customize the border color of the summary table.
How to Use:
1- Input your Account Size: Enter your current account balance.
2- Set Maximum Risk and Pip Value: Define how much you're willing to risk per trade and the
pip value for your contract.
3- Define Trade Levels: Input your desired Entry Price, Stop Loss, and Take Profit levels.
4- Customize Visuals: Adjust the line styles and table settings to fit your preferences.
5- View Calculations: The script will display the distance in pips and the calculated position
size directly on your chart.
Example Usage:
Example to calculate the value of 1 pips with 1 contract:
Inputs:
Account Size: Your total trading account balance.
Maximum Risk: Risk amount per trade in dollars.
Pip Value: Value of one pip for a single contract.
Entry Price: The price at which you plan to enter the trade.
Stop Loss: The level at which you will exit the trade to cut losses.
Take Profit: The target price to lock in profits.
Line Text Size: Size of the text for the Entry, Stop Loss, and Take Profit lines.
Line Extend: Option to extend the lines for visual clarity.
Table Position: Position of the summary table on the chart.
Table Text Size: Size of the text in the summary table.
Table Background Color: Background color of the summary table.
Table Border Color: Border color of the summary table.
Visuals:
Entry Price, Stop Loss, and Take Profit levels are clearly marked on the chart.
Summary Table with important trade metrics displayed.
[INVX] Trailing StopDescription:
The Adjustable Trailing Stop Indicator is a practical tool designed to enhance your trading strategy by allowing for automatic modifications of stop-loss orders according to your specified parameters. This indicator provides a dynamic alternative to the traditional static stop-loss orders, assisting in managing your potential profits and curbing possible losses.
Features and Functionality:
The Trailing Stop Indicator provides three main inputs for customization:
"Trailing Stop Start Date" : This input enables you to set the start date for the trailing stop. From this date forward, the indicator begins tracking price changes and adjusts the stop-loss order in response.
"Trigger Delta (%)" : This represents the percentage for the trailing stop. It denotes the set percentage at which the stop order adjusts.
"Order" : This input determines whether the trailing stop applies to a Buy or Sell order. Depending on the selection, the indicator adjusts the stop price as the price escalates (for Sell order) or declines (for Buy order).
How Does the Trailing Stop Indicator Work?
The Trailing Stop Indicator functions by dynamically adjusting the stop price in line with market fluctuations. If the market price rises (for Sell order), the stop price automatically ascends, securing potential profits. In a declining market (for Buy order), the stop price descends according to the market.
This indicator eliminates the need for constant manual adjustments, reducing the impact of emotional trading and helping traders maintain their risk management strategy. By using this tool, traders can implement a more disciplined and systematic approach to trading.
BTC outperform atrategy### Code Description
This Pine Script™ code implements a simple trading strategy based on the relative prices of Bitcoin (BTC) on a weekly and a three-month basis. The script plots the weekly and three-month closing prices of Bitcoin on the chart and generates trading signals based on the comparison of these prices. The code can also be applied to Ethereum (ETH) with similar effectiveness.
### Explanation
1. **Inputs and Variables**:
- The user selects the trading symbol (default is "BINANCE:BTCUSDT").
- `weeklyPrice` retrieves the closing price of the selected symbol on a weekly interval.
- `monthlyPrice` retrieves the closing price of the selected symbol on a three-month interval.
2. **Plotting Data**:
- The weekly price is plotted in blue.
- The three-month price is plotted in red.
3. **Trading Conditions**:
- A long position is suggested if the weekly price is greater than the three-month price.
- A short position is suggested if the three-month price is greater than the weekly price.
4. **Strategy Execution**:
- If the long condition is met, the strategy enters a long position.
- If the short condition is met, the strategy enters a short position.
This script works equally well for Ethereum (ETH) by changing the symbol input to "BINANCE:ETHUSDT" or any other desired Ethereum trading pair.
Analyst Table (Zeiierman)█ Overview
The Analyst Table (Zeiierman) provides a comprehensive visual representation of analyst estimates and recommendations for any stock. This indicator displays crucial analyst data, including the highest, average, and lowest price targets, directly on the price chart. Additionally, it features a well-organized table summarizing various types of analyst recommendations, offering traders valuable insights into market sentiment and expectations. This tool is ideal for traders seeking a quick overview of analyst opinions and recommendations on specific stocks.
█ How It Works
The indicator works by retrieving analyst data such as price targets and recommendations from the TradingView data feed. It visually represents these estimates on the chart and creates a structured table for easy reference, consolidating all the information in an organized format.
Key Components:
High Estimate Line: A dotted line representing the highest price target.
Low Estimate Line: A dotted line representing the lowest price target.
Target Estimate Box: A box representing the range between the average and median price targets.
Analyst Table: A table displaying detailed information about various analyst recommendations and price targets.
█ How to Use
Traders can use this indicator to gain insights into the expectations of financial analysts regarding the future performance of an asset. By observing the highest, lowest, and average price targets, traders can assess the range of possible future prices as predicted by analysts. The recommendation table helps in understanding the general sentiment among analysts, whether it's bullish, bearish, or neutral.
Visual Analysis: Use the visual indicators to quickly gauge where the current price stands relative to analyst targets.
Sentiment Assessment: Refer to the table to understand the distribution of buy, hold, and sell recommendations.
█ Settings
The indicator settings allow users to enable or disable different target lines, select colors for the lines and table cells, and choose the position and size of the analyst table on the chart.
-----------------
Disclaimer
The information contained in my Scripts/Indicators/Ideas/Algos/Systems does not constitute financial advice or a solicitation to buy or sell any securities of any type. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
My Scripts/Indicators/Ideas/Algos/Systems are only for educational purposes!
Long/Short Entry with Customizable TP/SLThis TradingView indicator is designed to help traders visualize potential trade entries along with their corresponding stop-loss (SL) and take-profit (TP) levels. It offers a high degree of customization, allowing users to:
Choose Entry Type: Select whether the anticipated trade is a Long or Short position.
Set Entry Price: Specify the exact price level at which you intend to enter the trade.
Customize TP/SL:
Enable/Disable: Choose whether to include a stop-loss (SL) and up to five take-profit (TP) levels.
Distance: Set the distance (in price points) for each SL and TP level from the entry price.
Add/Update Trade: Clicking the "Add/Update Trade" button will plot the entry line, SL line (if enabled), and TP lines (if enabled) on the chart, along with their corresponding labels. The lines and boxes will start two candles before the current bar and extend into the future.
Reset Trade: Clicking the "Reset Trade" button will clear all the lines, boxes, and labels from the chart, allowing you to start fresh with a new trade idea.
Visual Cues:
The indicator uses color-coded lines and boxes to distinguish between entry, SL, and TP levels.
Labels are provided next to each line, displaying the type of level (e.g., "Entry," "SL," "TP1") and its corresponding price.
Key Features:
Highly Customizable: Tailor the indicator to your specific trading style and risk management preferences.
Visual Clarity: Clearly visualize potential trade setups and their outcomes.
Easy to Use: The intuitive interface makes it simple to add, update, and reset trades.
Flexibility: Supports both long and short positions.
Limitations:
The indicator is designed for visualization and planning purposes only. It does not automatically execute trades.
The simulated "Add Trade" and "Reset Trade" buttons require manual unchecking after each click.
Rolling Correlation with Bitcoin V1.1 [ADRIDEM]Overview
The Rolling Correlation with Bitcoin script is designed to offer a comprehensive view of the correlation between the selected ticker and Bitcoin. This script helps investors understand the relationship between the performance of the current ticker and Bitcoin over a rolling period, providing insights into their interconnected behavior. Below is a detailed presentation of the script and its unique features.
Unique Features of the New Script
Bitcoin Comparison : Allows users to compare the correlation of the current ticker with Bitcoin, providing an analysis of their relationship.
Customizable Rolling Window : Enables users to set the length for the rolling window, adapting to different market conditions and timeframes. The default value is 252 bars, which approximates one year of trading days, but it can be adjusted as needed.
Smoothing Option : Includes an option to apply a smoothing simple moving average (SMA) to the correlation coefficient, helping to reduce noise and highlight trends. The smoothing length is customizable, with a default value of 4 bars.
Visual Indicators : Plots the smoothed correlation coefficient between the current ticker and Bitcoin, with distinct colors for easy interpretation. Additionally, horizontal lines help identify key levels of correlation.
Dynamic Background Color : Adds dynamic background colors to highlight areas of strong positive and negative correlations, enhancing visual clarity.
Originality and Usefulness
This script uniquely combines the analysis of rolling correlation for a current ticker with Bitcoin, providing a comparative view of their relationship. The inclusion of a customizable rolling window and smoothing option enhances its adaptability and usefulness in various market conditions.
Signal Description
The script includes several features that highlight potential insights into the correlation between the assets:
Rolling Correlation with Bitcoin : Plotted as a red line, this represents the smoothed rolling correlation coefficient between the current ticker and Bitcoin.
Horizontal Lines and Background Color : Lines at -0.5, 0, and 0.5 help to quickly identify regions of strong negative, weak, and strong positive correlations.
These features assist in identifying the strength and direction of the relationship between the current ticker and Bitcoin.
Detailed Description
Input Variables
Length for Rolling Window (`length`) : Defines the range for calculating the rolling correlation coefficient. Default is 252.
Smoothing Length (`smoothing_length`) : The number of periods for the smoothing SMA. Default is 4.
Bitcoin Ticker (`bitcoin_ticker`) : The ticker symbol for Bitcoin. Default is "BINANCE:BTCUSDT".
Functionality
Correlation Calculation : The script calculates the daily returns for both Bitcoin and the current ticker and computes their rolling correlation coefficient.
```pine
bitcoin_close = request.security(bitcoin_ticker, timeframe.period, close)
bitcoin_dailyReturn = ta.change(bitcoin_close) / bitcoin_close
current_dailyReturn = ta.change(close) / close
rolling_correlation = ta.correlation(current_dailyReturn, bitcoin_dailyReturn, length)
```
Smoothing : A simple moving average is applied to the rolling correlation coefficient to smooth the data.
```pine
smoothed_correlation = ta.sma(rolling_correlation, smoothing_length)
```
Plotting : The script plots the smoothed rolling correlation coefficient and includes horizontal lines for key levels.
```pine
plot(smoothed_correlation, title="Rolling Correlation with Bitcoin", color=color.rgb(255, 82, 82, 50), linewidth=2)
h_neg1 = hline(-1, "-1 Line", color=color.gray)
h_neg05 = hline(-0.5, "-0.5 Line", color=color.red)
h0 = hline(0, "Zero Line", color=color.gray)
h_pos05 = hline(0.5, "0.5 Line", color=color.green)
h1 = hline(1, "1 Line", color=color.gray)
fill(h_neg1, h_neg05, color=color.rgb(255, 0, 0, 90), title="Strong Negative Correlation Background")
fill(h_neg05, h0, color=color.rgb(255, 165, 0, 90), title="Weak Negative Correlation Background")
fill(h0, h_pos05, color=color.rgb(255, 255, 0, 90), title="Weak Positive Correlation Background")
fill(h_pos05, h1, color=color.rgb(0, 255, 0, 90), title="Strong Positive Correlation Background")
```
How to Use
Configuring Inputs : Adjust the rolling window length and smoothing length as needed. Ensure the Bitcoin ticker is set to the desired asset for comparison.
Interpreting the Indicator : Use the plotted correlation coefficient and horizontal lines to assess the strength and direction of the relationship between the current ticker and Bitcoin.
Signal Confirmation : Look for periods of strong positive or negative correlation to identify potential co-movements or divergences. The background colors help to highlight these key levels.
This script provides a detailed comparative view of the correlation between the current ticker and Bitcoin, aiding in more informed decision-making by highlighting the strength and direction of their relationship.