Rolling Sortino Ratio with Ref Ticker V1.0 [ADRIDEM]Overview
The Rolling Sortino Ratio with Ref Ticker script is designed to offer a comprehensive view of the Sortino ratios for a selected reference ticker and the current ticker. This script helps investors compare risk-adjusted returns between two assets over a rolling period, providing insights into their relative performance and risk. Below is a detailed presentation of the script and its unique features.
Unique Features of the New Script
Reference Ticker Comparison : Allows users to compare the Sortino ratio of the current ticker with a reference ticker, providing a relative performance analysis. Default ticker is BTCUSDT but can be changed.
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 Sortino ratios, helping to reduce noise and highlight trends. The smoothing length is customizable, with a default value of 4 bars.
Visual Indicators : Plots the smoothed Sortino ratios for both the reference ticker and the current ticker, with distinct colors for easy comparison. Additionally, horizontal lines and a shaded background help identify key levels.
Dynamic Background Color : Adds a gray-blue transparent background between the Sortino ratio levels of 0 and 1, highlighting the critical region where risk-adjusted returns are assessed.
Originality and Usefulness
This script uniquely combines the analysis of Sortino ratios for a reference ticker and the current ticker, providing a comparative view of their risk-adjusted returns. 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 risk-adjusted returns of the assets:
Reference Ticker Sortino Ratio : Plotted as a red line, this represents the smoothed Sortino ratio for the user-selected reference ticker.
Current Ticker Sortino Ratio : Plotted as a white line, this represents the smoothed Sortino ratio for the current ticker.
Horizontal Lines and Background Color : Lines at 0 and 1, along with a shaded background between these levels, help to quickly identify the regions of positive and strong risk-adjusted returns.
These features assist in identifying relative performance differences and confirming the strength or weakness of risk-adjusted returns between the two tickers.
Detailed Description
Input Variables
Length for Rolling Window (`length`) : Defines the range for calculating the rolling Sortino ratio. Default is 252.
Smoothing Length (`smoothing_length`) : The number of periods for the smoothing SMA. Default is 4.
Annual Risk-Free Rate (`riskFreeRate`) : The annual risk-free rate used in the Sortino ratio calculation. Default is 0.02 (2%).
Reference Ticker (`ref_ticker`) : The ticker symbol for the reference asset. Default is "BINANCE:BTCUSDT".
Functionality
Sortino Ratio Calculation : The script calculates the daily returns, mean return, and downside deviation for both the reference ticker and the current ticker. These values are used to compute the annualized Sortino ratio.
```pine
ref_dailyReturn = ta.change(ref_close) / ref_close
ref_meanReturn = ta.sma(ref_dailyReturn, length)
ref_downsideDeviation = ta.stdev(math.min(ref_dailyReturn, 0), length)
ref_annualizedReturn = ref_meanReturn * length
ref_annualizedDownsideDev = ref_downsideDeviation * math.sqrt(length)
ref_sortinoRatio = (ref_annualizedReturn - riskFreeRate) / ref_annualizedDownsideDev
```
Smoothing : A simple moving average is applied to the Sortino ratios to smooth the data.
```pine
smoothed_ref_sortinoRatio = ta.sma(ref_sortinoRatio, smoothing_length)
smoothed_current_sortinoRatio = ta.sma(current_sortinoRatio, smoothing_length)
```
Plotting : The script plots the smoothed Sortino ratios for both the reference ticker and the current ticker, along with horizontal lines and a shaded background.
```pine
plot(smoothed_ref_sortinoRatio, title="Ref Ticker Sortino Ratio", color=color.rgb(255, 82, 82, 50), linewidth=2)
plot(smoothed_current_sortinoRatio, title="Current Ticker Sortino Ratio", color=color.white, linewidth=2)
h0 = hline(0, "Zero Line", color=color.gray)
h1 = hline(1, "One Line", color=color.gray)
fill(h0, h1, color=color.rgb(33, 150, 243, 90), title="Background")
```
How to Use
Configuring Inputs : Adjust the detection length, smoothing length, and risk-free rate as needed. Set the reference ticker to the desired asset for comparison.
Interpreting the Indicator : Use the plotted Sortino ratios and background shading to assess the relative risk-adjusted returns of the reference and current tickers.
Signal Confirmation : Look for differences in the Sortino ratios to identify potential performance advantages or weaknesses. The background shading helps to highlight key levels of risk-adjusted returns.
This script provides a detailed comparative view of risk-adjusted returns, aiding in more informed decision-making by highlighting key differences between the reference ticker and the current ticker.
Управление портфелем
Rolling Sharpe Ratio with Ref Ticker V1.0 [ADRIDEM]Overview
The Rolling Sharpe Ratio with Ref Ticker script is designed to offer a comprehensive view of the Sharpe ratios for a selected reference ticker and the current ticker. This script helps investors compare risk-adjusted returns between two assets over a rolling period, providing insights into their relative performance and risk. Below is a detailed presentation of the script and its unique features.
Unique Features of the New Script
Reference Ticker Comparison : Allows users to compare the Sharpe ratio of the current ticker with a reference ticker, providing a relative performance analysis. Default ticker is BTCUSDT but can be changed.
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 Sharpe ratios, helping to reduce noise and highlight trends. The smoothing length is customizable, with a default value of 4 bars.
Visual Indicators : Plots the smoothed Sharpe ratios for both the reference ticker and the current ticker, with distinct colors for easy comparison. Additionally, horizontal lines and a shaded background help identify key levels.
Dynamic Background Color : Adds a gray-blue transparent background between the Sharpe ratio levels of 0 and 1, highlighting the critical region where risk-adjusted returns are assessed.
Originality and Usefulness
This script uniquely combines the analysis of Sharpe ratios for a reference ticker and the current ticker, providing a comparative view of their risk-adjusted returns. 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 risk-adjusted returns of the assets:
Reference Ticker Sharpe Ratio : Plotted as a red line, this represents the smoothed Sharpe ratio for the user-selected reference ticker.
Current Ticker Sharpe Ratio : Plotted as a white line, this represents the smoothed Sharpe ratio for the current ticker.
Horizontal Lines and Background Color : Lines at 0 and 1, along with a shaded background between these levels, help to quickly identify the regions of positive and strong risk-adjusted returns.
These features assist in identifying relative performance differences and confirming the strength or weakness of risk-adjusted returns between the two tickers.
Detailed Description
Input Variables
Length for Rolling Window (`length`) : Defines the range for calculating the rolling Sharpe ratio. Default is 252.
Smoothing Length (`smoothing_length`) : The number of periods for the smoothing SMA. Default is 4.
Annual Risk-Free Rate (`riskFreeRate`) : The annual risk-free rate used in the Sharpe ratio calculation. Default is 0.02 (2%).
Reference Ticker (`ref_ticker`) : The ticker symbol for the reference asset. Default is "BINANCE:BTCUSDT".
Functionality
Sharpe Ratio Calculation : The script calculates the daily returns, mean return, and standard deviation for both the reference ticker and the current ticker. These values are used to compute the annualized Sharpe ratio.
```pine
ref_dailyReturn = ta.change(ref_close) / ref_close
ref_meanReturn = ta.sma(ref_dailyReturn, length)
ref_stdDevReturn = ta.stdev(ref_dailyReturn, length)
ref_annualizedReturn = ref_meanReturn * length
ref_annualizedStdDev = ref_stdDevReturn * math.sqrt(length)
ref_sharpeRatio = (ref_annualizedReturn - riskFreeRate) / ref_annualizedStdDev
```
Smoothing : A simple moving average is applied to the Sharpe ratios to smooth the data.
```pine
smoothed_ref_sharpeRatio = ta.sma(ref_sharpeRatio, smoothing_length)
smoothed_current_sharpeRatio = ta.sma(current_sharpeRatio, smoothing_length)
```
Plotting : The script plots the smoothed Sharpe ratios for both the reference ticker and the current ticker, along with horizontal lines and a shaded background.
```pine
plot(smoothed_ref_sharpeRatio, title="Ref Ticker Sharpe Ratio", color=color.rgb(255, 82, 82, 50), linewidth=2)
plot(smoothed_current_sharpeRatio, title="Current Ticker Sharpe Ratio", color=color.white, linewidth=2)
h0 = hline(0, "Zero Line", color=color.gray)
h1 = hline(1, "One Line", color=color.gray)
fill(h0, h1, color=color.rgb(33, 150, 243, 90), title="Background")
```
How to Use
Configuring Inputs : Adjust the detection length, smoothing length, and risk-free rate as needed. Set the reference ticker to the desired asset for comparison.
Interpreting the Indicator : Use the plotted Sharpe ratios and background shading to assess the relative risk-adjusted returns of the reference and current tickers.
Signal Confirmation : Look for differences in the Sharpe ratios to identify potential performance advantages or weaknesses. The background shading helps to highlight key levels of risk-adjusted returns.
This script provides a detailed comparative view of risk-adjusted returns, aiding in more informed decision-making by highlighting key differences between the reference ticker and the current ticker.
High Probability OS/OB {DCAquant}DCAquant - High Probability OS/OB
The DCAquant - High Probability OS/OB Pine Script is a sophisticated indicator that provides insights into overbought (OB) and oversold (OS) conditions based on Hull Moving Averages (HMA) and Volume Weighted Moving Averages (VWMA). Here's a detailed breakdown of its functionality:
-------------------------------------------------------------------------------------
THIS INDICATOR IS ONLY WRITTEN FOR BTC, ETH and TOTAL!!!!!!!!!!!!!
-------------------------------------------------------------------------------------
Functionality
The script identifies high-probability OB and OS zones by combining multiple moving averages (MAs).
1. Volume Weighted Moving Average (VWMA)
The VWMA function computes the VWMA over a specified length, incorporating both the price and volume.
2. Hull Moving Average with Volume Weight (HMA-VW)
The hullma_vw function calculates the HMA using the VWMA. This involves:
Computing VWMAs over the full length and half-length.
Using these VWMAs to derive the HMA-VW through a weighted approach.
5. Standard Hull Moving Average (HMA)
The hull function computes the HMA using the standard weighted moving average (WMA).
4. Smoothed HMA-VW
This is an Exponential Moving Average (EMA) of the HMA-VW to smooth out short-term fluctuations.
How this works
First, the distance between the 2 MA's is calculated.
The distance is scored against the average price of the last 100 days.
By getting this score we can calculate extremes
The Extremes are categorized into 4 levels. The transparency of the background color distinguishes these 4 levels.
Only the MOST extremes are plotted ON THE CHART. Within the indicator, all 4 levels are plotted.
Usage
Extreme Buy zone: Consider entering the market when the indicator shows deep negative values (oversold). These are highlighted with a cyan background, with increasing opacity indicating stronger buy signals (Level 4 Zones).
Extreme Sell Zone: Consider exiting the market when the indicator shows high positive values (overbought). These are highlighted with a magenta background, with increasing opacity indicating stronger sell signals (Level 4 Zones).
Disclaimer
This indicator should not be used in isolation. It is recommended to use this as part of a systematic approach, incorporating other tools and analysis methods to confirm signals and make well-informed trading decisions.
Wolf DCA CalculatorThe Wolf DCA Calculator is a powerful and flexible indicator tailored for traders employing the Dollar Cost Averaging (DCA) strategy. This tool is invaluable for planning and visualizing multiple entry points for both long and short positions. It also provides a comprehensive analysis of potential profit and loss based on user-defined parameters, including leverage.
Features
Entry Price: Define the initial entry price for your trade.
Total Lot Size: Specify the total number of lots you intend to trade.
Percentage Difference: Set the fixed percentage difference between each DCA point.
Long Position: Toggle to switch between long and short positions.
Stop Loss Price: Set the price level at which you plan to exit the trade to minimize losses.
Take Profit Price: Set the price level at which you plan to exit the trade to secure profits.
Leverage: Apply leverage to your trade, which multiplies the potential profit and loss.
Number of DCA Points: Specify the number of DCA points to strategically plan your entries.
How to Use
1. Add the Indicator to Your Chart:
Search for "Wolf DCA Calculator" in the TradingView public library and add it to your chart.
2. Configure Inputs:
Entry Price: Set your initial trade entry price.
Total Lot Size: Enter the total number of lots you plan to trade.
Percentage Difference: Adjust this to set the interval between each DCA point.
Long Position: Use this toggle to choose between a long or short position.
Stop Loss Price: Input the price level at which you plan to exit the trade to minimize losses.
Take Profit Price: Input the price level at which you plan to exit the trade to secure profits.
Leverage: Set the leverage you are using for the trade.
Number of DCA Points: Specify the number of DCA points to plan your entries.
3. Analyze the Chart:
The indicator plots the DCA points on the chart using a stepline style for clear visualization.
It calculates the average entry point and displays the potential profit and loss based on the specified leverage.
Labels are added for each DCA point, showing the entry price and the lots allocated.
Horizontal lines mark the Stop Loss and Take Profit levels, with corresponding labels showing potential loss and profit.
Benefits
Visual Planning: Easily visualize multiple entry points and understand how they affect your average entry price.
Risk Management: Clearly see your Stop Loss and Take Profit levels and their impact on your trade.
Customizable: Adapt the indicator to your specific strategy with a wide range of customizable parameters.
[MAD] Entrytool / Bybit-LinearThis indicator, "Entry Tool," was coded at request for Sandmann .
It is designed to provide traders with real-time feedback for strategizing entries, exits, and liquidation levels for trades initiated at that given moment.
The tool visualizes average entry prices, stop-loss levels, multiple take-profit targets, and potential liquidation prices, offering a comprehensive overview of possible trade outcomes. It aids traders in pre-planning their trades by visually simulating the impact of different trading decisions directly on the live chart. Each setting and parameter can be customized to align with individual trading strategies and risk tolerances, making this tool versatile for various trading styles, including day trading, swing trading, and position trading.
------------------------------
Steps to Use the Indicator:
1. Basic Setup:
Setup Type: Choose between "Long" or "Short" to set the direction of the trade.
Leverage: Adjust the leverage to understand its impact on your potential returns and liquidation price.
Tracking follows the close price, alternative you can enter a specific price.
2. Position Setup:
Initial Entry Amount: Set the starting amount for the trade.
Distance: First Increment Percentage from Entry price
Amount: Define the increase for the first incremental addition to the position and specify the amount to be added.
Distance: Second Increment Percentage from Entry
Amount: Set the increase for the second incremental addition and the corresponding amount.
3. Risk Management:
Stop-Loss (SL) Percentage: Set the percentage below or above the average entry price at which the position should be closed to minimize losses.
Take-Profit (TP) Percentages: Define up to four different profit target levels by specifying the percentage above or below the average entry price.
4. Visual Settings:
Box Colors: Customize the colors of the boxes that represent long and short positions to differentiate easily on the chart.
Box Extension: Determine the length by which the box extends beyond the current bar, which helps in visualizing the potential price movement.
Line Colors and Extensions: Select colors for various lines such as the Average Entry Line, Stop-Loss Line, Take-Profit Lines, and Liquidations Line. Adjust the length of these lines for better visibility.
Label Settings: Configure the distance of labels from their corresponding lines and set the font size for better readability.
5. Additional Features:
Liquidation Price Visualization: This new feature calculates and displays the liquidation price based on the current leverage and margin settings, giving traders a critical insight into their risk exposure.
Interactive Drag Point: Adjust the start price manually by dragging the point on the chart, which dynamically updates entry and exit levels as well as risk metrics.
Detailed Leverage Data Array: Input different scenarios with specific leverage, initial margin, and maintenance rates to see how these factors impact potential liquidation points.
6. Informations about leverage calculation
The data used are fetched from Bybit for Linear pairs to calculate the liquidations like in their documentation.
Keep in mind that other exchanges may calulate based on another formular.
Dynamic Date and Price Tracker with Entry PriceThe Dynamic Date and Price Tracker indicator is a simple tool designed for traders to visualize and monitor their trade's progress in real-time from a specified starting point.
This tool provides an intuitive graphical representation of your trade's profitability based on a custom entry date and price.
Features:
-Starting Date Selection: Choose a specific starting date, after which the indicator begins tracking your trade's performance.
-Custom Entry Price: Input a starting price to accurately reflect your actual entry price for performance tracking across different timeframes.
-Real-Time Tracking: As new bars form, the indicator automatically adjusts a dynamic line to the current closing price.
-Profit/Loss Color Coding: The dynamic line color changes based on whether the current price is above (green for profit) or below (red for loss) your specified entry price.
-Performance Label: A real-time label displays the absolute and percentage change in price since your initial entry, color-coded for positive (green) or negative (red) performance.
-Entry Price Line: The horizontal line marks your starting price for easy visual comparison.
Liquidations [ChartPrime]Liquidations Indicator:
The Liquidations indicator is a powerful tool designed to help traders identify significant liquidation levels in financial markets. By analyzing volume data over a specified lookback period, the indicator highlights potential areas where market participants with high leverage positions may face liquidation, providing valuable insights into market dynamics.
Usage:
Traders can use the Liquidations indicator to:
◈ Identify liquidity grab opportunities: Liquidation levels often attract price action as market participants with leveraged positions face the risk of forced liquidation. Traders can anticipate price movements as the market aims to trigger these stops, potentially leading to rapid price movements or reversals.
◈ Confirm trend strength: A cluster of liquidation levels in the same direction as the prevailing trend may confirm the strength of the trend, while divergences between liquidation levels and price movements may signal potential trend reversals.
Settings:
◈ Previous Value Bars Back: Specifies the number of previous bars used in calculating the liquidation levels.
◈ Show Leverage: Allows users to selectively display liquidation levels for different leverage multiples, including 5x, 10x, 25x, 50x, and 100x.
◈ Liquidation Levels Width: Sets the width of the lines representing liquidation levels on the chart.
◈ Short Liquidations Color: Specifies the color of the lines representing short liquidation levels.
◈ Long Liquidations Color: Specifies the color of the lines representing long liquidation levels.
◈ Bar Color: Sets the color of the background bar when the indicator is active.
Visual Representation:
◈ Liquidation levels are plotted as horizontal lines on the chart, with different colors representing short and long liquidation levels.
◈ Each liquidation level is labeled with the corresponding leverage multiple (e.g., 5x, 10x, etc.).
A dashboard displays the active liquidation levels for each leverage multiple, allowing traders to quickly assess the current market conditions.
◈ Time Window allows users to cut off unnecessary part of the chart and concentrate on a current active part of the chart to make better trading decisions:
Interpretation:
Market participants tend to place stop-loss orders near liquidation levels , creating clusters of pending orders. As price approaches these levels, it may trigger a cascade of stop-loss orders, providing liquidity for market orders and potentially leading to rapid price movements in the opposite direction.
Traders can anticipate price reversals or accelerations as price interacts with liquidation levels, using them as reference points for identifying potential entry or exit opportunities.
Note:
While the Liquidations indicator provides valuable insights into market dynamics, traders should use it in conjunction with other technical analysis tools and risk management strategies to make informed trading decisions.
Tic Tac Toe Game [TradeDots]Feeling bored with trading?
Time to inject some fun into your decision-making process with our Tic Tac Toe Indicator!
The Tic Tac Toe game transforms your chart into a competitive playground where trading pairs face off in a classic game of Tic Tac Toe.
HOW TO PLAY
Our Tic Tac Toe game invites you to pit one trading pair against another directly on your chart. Choose the competitors and watch as they battle it out in a traditional grid setup.
Navigate to settings and select your competitor pair.
Choose who kicks off the game.
After the close of each new bar, the algorithm will utilize the closing prices of both symbols. These numbers feed into a random number generator which alternates the turns for placing marks on the grid.
The game progresses until one pair aligns three consecutive symbols and wins, or the board fills up. After that, the game resets every three bars, offering continual engagement during active market hours.
MANUAL PLAYING MODE
Currently, due to PineScript's limitations, a fully interactive manual mode is not supported, as all previous data will be lost with each new user input, preventing the replication of existing game states.
However, users can input a sequence at the start, guiding the placement of symbols throughout the game.
Stay tuned for future updates!
Futures Risk CalculatorThe "Futures Risk Calculator" is designed to assist traders in calculating the number of contracts to risk based on their account size, risk percentage, and stop loss level. This script provides a convenient way for traders to determine their position size in futures or other instruments where contracts are used.
The script prompts users to input their account size, risk percentage, entry price, and stop loss price. It then calculates the stop size in points, risk in dollars, and the number of contracts to risk. These calculations are based on standard risk management principles commonly used in trading.
The script plots the entry and stop loss lines on the chart for visual reference. Additionally, it displays a label in the top-right corner of the chart, showing the calculated number of contracts to risk. The label updates dynamically as the input values or market conditions change.
Originality and Usefulness:
This script is original and adds value to the TradingView community by providing traders with a practical tool for managing risk in their trading strategies. It is focusing on risk management, an essential aspect of successful trading.
By automating the calculation process, the script saves traders time and reduces the potential for manual errors. It encourages traders to adopt disciplined risk management practices, which are crucial for long-term profitability and capital preservation.
How to Use:
Input your account size, risk percentage, entry price, and stop loss price in the script settings.
Enter the pip size according to the instrument you are using (by default its's based for NASDAQ)
The script will automatically calculate the number of contracts to risk based on the provided inputs.
The entry and stop loss lines will be plotted on the chart for visual reference.
The calculated number of contracts to risk will be displayed in the top-right corner of the chart.
By following these steps, traders can effectively manage their risk exposure and make informed decisions when entering trades.
Candle Strength based on Relative Strength of EMAOverview:
The EMA-Based Relative Strength Labels indicator provides a dynamic method to visualize the strength of price movements relative to an Exponential Moving Average (EMA). By comparing the current price to the EMA, it assigns labels (A, B, C for bullish and X, Y, Z for bearish) to candles, indicating the intensity of bullish or bearish behavior.
Key Features:
Dynamic EMA Comparison: The indicator calculates the difference between the current price and the EMA, expressing it as a percentage to determine relative strength.
Configurable Thresholds: Users can set custom thresholds for strong, moderate, and low bullish or bearish movements, allowing for tailored analysis based on personal trading strategy or market behavior.
Clear Visual Labels: Each candle is labeled directly on the chart, making it easy to spot significant price movements at a glance.
Usage:
Trend Confirmation: The labels help confirm the prevailing trend's strength, aiding traders in decision-making regarding entry or exit points.
Risk Management: By identifying the strength of the price movements, traders can better manage stop-loss placements and avoid potential false breakouts.
Strategy Development: Incorporate the indicator into trading systems to enhance strategies that depend on trend strength and momentum.
How It Works:
The script calculates the EMA of the closing prices and measures the relative strength of each candle to this average.
Bullish candles above the EMA and bearish candles below the EMA are further analyzed to determine their strength based on predefined percentage thresholds.
Labels 'A', 'B', and 'C' are assigned for varying degrees of bullish strength, while 'X', 'Y', and 'Z' denote levels of bearish intensity.
Customization:
Users can adjust the EMA period and modify the strength thresholds for both bullish and bearish conditions to suit different instruments and timeframes.
Best Practices:
Combine this indicator with volume analysis and other technical tools for comprehensive market analysis.
Regularly update the thresholds based on market volatility and personal risk tolerance to maintain the effectiveness of the labels.
RSI Multi Strategies With Overlay SignalsHello everyone,
In this indicator, you will find 6 different entry and exit signals based on the RSI :
Entry into overbought and oversold zones
Exit from overbought and oversold zones
Crossing the 50 level
RSI cross RSI MA below or above the 50 level
RSI cross RSI MA in the overbought or oversold zones
RSI Divergence
With the signals identified, you can create your own strategy . (If you have any suggestions, please mention them in the comments).
Beyond these signals, you can set SL (Stop Loss) and TP (Take Profit) levels to better manage your positions.
SL Methods:
Percentage: The stop loss is determined by the percentage you specify.
ATR : The stop level is determined based on the Average True Range (ATR).
TP Methods:
Percentage: The take profit is determined by the percentage you specify.
RR ( Risk Reward ): The take profit level is determined based on the distance from the stop level.
You can mix and match these options as you like.
What makes the indicator unique and effective is its ability to display the RSI in the bottom chart and the signals, SL (Stop Loss), and TP (Take Profit) levels in the overlay chart simultaneously. This feature allows you to manage your trading quickly and easily without the need for using two separate indicators.
Let's try out a few strategies together.
My entry signal: RSI Entered OS (Oversold) Zone
My exit signal: RSI Entered OB (Overbought) Zone
I'm not using a stoploss for this strategy ("Fortune favors the brave").
Let's keep ourselves safe by adding a stop loss.
I'm adding an ATR-based stop loss.
I think it's better now.
If you have any questions or suggestions about the indicator, you can contact me.
Cheers
Mag7 IndexThis is an indicator index based on cumulative market value of the Magnificent 7 (AAPL, MSFT, NVDA, TSLA, META, AMZN, GOOG). Such an indicator for the famous Mag 7, against which your main security can be benchmarked, was missing from the TradingView user library.
The index bar values are calculated by taking the weighted average of the 7 stocks, relative to their market cap. Explicitly, we are multiplying each bar period's total outstanding stock amount by the OHLC of that period for each stock and dividing that value by the combined sum of outstanding stock for the 7 corporations. OHLC is taken for the extended trading session.
The index dynamically adjusts with respect to the chosen main security and the bars/line visible in the chart window; that is, the first close value is normalized to the main security's first close value. It provides recalculation of the performance in that chart window as you scroll (this isn't apparent in the demo chart above this description).
It can be useful for checking market breadth, or benchmarking price performance of the individual stock components that comprise the Magnificent 7. I prefer comparing the indicator to the Nasdaq Composite Index (IXIC) or S&P500 (SPX), but of course you can make comparisons to any security or commodity.
Settings Input Options:
1) Bar vs. Line - view as OHLC colored bars or line chart. Line chart color based on close above or below the previous period close as green or red line respectively.
2) % vs Regular - the final value for the window period as % return for that window or index value
3) Turn on/off - bottom right tile displaying window-period performance
Inspired by the simpler NQ 7 Index script by @RaenonX but with normalization to main security at start of window and additional settings input options.
Please provide feedback for additional features, e.g., if a regular/extended session option is useful.
Trailing Management (Zeiierman)█ Overview
The Trailing Management (Zeiierman) indicator is designed for traders who seek an automated and dynamic approach to managing trailing stops. It helps traders make systematic decisions regarding when to enter and exit trades based on the calculated risk-reward ratio. By providing a clear visual representation of trailing stop levels and risk-reward metrics, the indicator is an essential tool for both novice and experienced traders aiming to enhance their trading discipline.
The Trailing Management (Zeiierman) indicator integrates a Break-Even Curve feature to enhance its utility in trailing stop management and risk-reward optimization. The Break-Even Curve illuminates the precise point at which a trade neither gains nor loses value, offering clarity on the risk-reward landscape. Furthermore, this precise point is calculated based on the required win rate and the risk/reward ratio. This calculation aids traders in understanding the type of strategy they need to employ at any given time to be profitable. In other words, traders can, at any given point, assess the kind of strategy they need to utilize to make money, depending on the price's position within the risk/reward box.
█ How It Works
The indicator operates by computing the highest high and the lowest low over a user-defined period and then applying this information to determine optimal trailing stop levels for both long and short positions.
Directional Bias:
It establishes the direction of the market trend by comparing the index of the highest high and the lowest low within the lookback period.
Bullish
Bearish
Trailing Stop Adjustment:
The trailing stops are adjusted using one of three methods: an automatic calculation based on the median of recent peak differences, pivot points, or a fixed percentage defined by the user.
The Break-Even Curve:
The Break-Even Curve, along with the risk/reward ratio, is determined through the trailing method. This approach utilizes the current closing price as a hypothetical entry point for trades. All calculations, including those for the curve, are based on this current closing price, ensuring real-time accuracy and relevance. As market conditions fluctuate, the curve dynamically adjusts, offering traders a visual benchmark that signifies the break-even point. This real-time adjustment provides traders with an invaluable tool, allowing them to visually track how shifts in the market could impact the point at which their trades neither gain nor lose value.
Example:
Let's say the price is at the midpoint of the risk/reward box; this means that the risk/reward ratio should be 1:1, and the minimum win rate is 50% to break even.
In this example, we can see that the price is near the stop-loss level. If you are about to take a trade in this area and would respect your stop, you only need to have a minimum win rate of 11% to earn money, given the risk/reward ratio, assuming that you hold the trade to the target.
In other words, traders can, at any given point, assess the kind of strategy they need to employ to make money based on the price's position within the risk/reward box.
█ How to Use
Market Bias:
When using the Auto Bias feature, the indicator calculates the underlying market bias and displays it as either bullish or bearish. This helps traders align their trades with the underlying market trend.
Risk Management:
By observing the plotted trailing stops and the risk-reward ratios, traders can make strategic decisions to enter or exit positions, effectively managing the risk.
Strategy selection:
The Break-Even Curve is a powerful tool for managing risk, allowing traders to visualize the relationship between their trailing stops and the market's price movements. By understanding where the break-even point lies, traders can adjust their strategies to either lock in profits or cut losses.
Based on the plotted risk/reward box and the location of the price within this box, traders can easily see the win rate required by their strategy to make money in the long run, given the risk/reward ratio.
Consider this example: The market is bullish, as indicated by the bias, and the indicator suggests looking into long trades. The price is near the top of the risk/reward box, which means entering the market right now carries a huge risk, and the potential reward is very low. To take this trade, traders must have a strategy with a win rate of at least 90%.
█ Settings
Trailing Method:
Auto: The indicator calculates the trailing stop dynamically based on market conditions.
Pivot: The trailing stop is adjusted to the highest high (long positions) or lowest low (short positions) identified within a specified lookback period. This method uses the pivotal points of the market to set the trailing stop.
Percentage: The trailing stop is set at a fixed percentage away from the peak high or low.
Trailing Size (prd):
This setting defines the lookback period for the highest high and lowest low, which affects the sensitivity of the trailing stop to price movements.
Percentage Step (perc):
If the 'Percentage' method is selected, this setting determines the fixed percentage for the trailing stop distance.
Set Bias (bias):
Allows users to set a market bias which can be Bullish, Bearish, or Auto, affecting how the trailing stop is adjusted in relation to the market trend.
-----------------
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!
Equity CurveAn equity curve is a graphical representation of the change in the value of a trading account over a time period. The equity curve is a direct reflection of a trading strategy's effectiveness. A consistently upward-trending equity curve indicates a successful strategy, while a flat or declining curve may signal the need for adjustment.
This indicator takes traders daily account values as a comma separated list, and creates an equity curve and simple moving average of the equity curve. This serves as a mirror reflecting the outcome of past actions and decisions, guiding traders in fine-tuning their strategies, managing risk more effectively, and ultimately striving towards a consistently profitable trading journey.
New equity values should be added to the end of the current list. A space or no space after the comma has no effect.
Importance of the Equity Curve
Strategy Evaluation: The equity curve is a direct reflection of a trading strategy's effectiveness over time. A consistently upward-trending equity curve indicates a successful strategy, while a flat or declining curve may signal the need for adjustment.
Risk Management: Monitoring the equity curve helps traders to see the impact of their risk management practices. Sudden drops in equity could highlight instances of excessive risk-taking or inadequate stop-loss settings.
Performance Benchmarks: Comparing the equity curve against benchmarks or desired performance goals allows traders to assess if they are meeting, exceeding, or falling short of their trading objectives.
Psychology: Trading is as much about psychology as it is about strategy. A visual representation of one's equity curve helps maintain discipline, encouraging adherence to a trading plan during downturns and preventing overconfidence during upswings.
Having this data visually allows traders to see which category of trader they fall into.
Unprofitable
Boom or Bust
Profitable
Statistical Data
The indicator not only plots the equity curve and moving average, but includes the option to display the highest value reached by the equity curve, the percentage difference from the peak, and performance over selected periods (All Time, YTD, QTD, MTD, WTD).
Historical Analysis
The Equity Curve Indicator is not just a tool for real-time monitoring of trading performance; it also serves as a powerful instrument for conducting historical analysis. By analyzing the equity curve in conjunction with historical market conditions, traders can identify patterns or triggers that resulted in significant gains or losses.
For example, the chart below shows the equity curve overlaid on periods of net new highs / lows. The equity curve experienced declines while the market was showing net new lows or choppy periods (represented by a red or white background), while most of the equity gains were made while net new highs were present (green background).
This retrospective analysis helps in understanding how different market conditions impact trading strategies and performance.
Trading the Equity Curve
All trading strategies produce an equity curve that has winning and losing periods. In the example above, the trader could introduce a simple rule to lighten up on long positions or move to cash during periods of net new lows.
Another simple rule could be introduced to stop trading if the equity curve falls below the moving average, until favorable market conditions return again.
This indicator is intended to be used on the daily timeframe.
Danger Signals from The Trading MindwheelThe " Danger Signals " indicator, a collaborative creation from the minds at Amphibian Trading and MARA Wealth, serves as your vigilant lookout in the volatile world of stock trading. Drawing from the wisdom encapsulated in "The Trading Mindwheel" and the successful methodologies of legends like William O'Neil and Mark Minervini, this tool is engineered to safeguard your trading journey.
Core Features:
Real-Time Alerts: Identify critical danger signals as they emerge in the market. Whether it's a single day of heightened risk or a pattern forming, stay informed with specific danger signals and a tally of signals for comprehensive decision-making support. The indicator looks for over 30 different signals ranging from simple closing ranges to more complex signals like blow off action.
Tailored Insights with Portfolio Heat Integration: Pair with the "Portfolio Heat" indicator to customize danger signals based on your current positions, entry points, and stops. This personalized approach ensures that the insights are directly relevant to your trading strategy. Certain signals can have different meanings based on where your trade is at in its lifecycle. Blow off action at the beginning of a trend can be viewed as strength, while after an extended run could signal an opportunity to lock in profits.
Forward-Looking Analysis: Leverage the 'Potential Danger Signals' feature to assess future risks. Enter hypothetical price levels to understand potential market reactions before they unfold, enabling proactive trade management.
The indicator offers two different modes of 'Potential Danger Signals', Worst Case or Immediate. Worst Case allows the user to input any price and see what signals would fire based on price reaching that level, while the Immediate mode looks for potential Danger Signals that could happen on the next bar.
This is achieved by adding and subtracting the average daily range to the current bars close while also forecasting the next values of moving averages, vwaps, risk multiples and the relative strength line to see if a Danger Signal would trigger.
User Customization: Flexibility is at your fingertips with toggle options for each danger signal. Tailor the indicator to match your unique trading style and risk tolerance. No two traders are the same, that is why each signal is able to be turned on or off to match your trading personality.
Versatile Application: Ideal for growth stock traders, momentum swing traders, and adherents of the CANSLIM methodology. Whether you're a novice or a seasoned investor, this tool aligns with strategies influenced by trading giants.
Validation and Utility:
Inspired by the trade management principles of Michael Lamothe, the " Danger Signals " indicator is more than just a tool; it's a reflection of tested strategies that highlight the importance of risk management. Through rigorous validation, including the insights from "The Trading Mindwheel," this indicator helps traders navigate the complexities of the market with an informed, strategic approach.
Whether you're contemplating a new position or evaluating an existing one, the " Danger Signals " indicator is designed to provide the clarity needed to avoid potential pitfalls and capitalize on opportunities with confidence. Embrace a smarter way to trade, where awareness and preparation open the door to success.
Let's dive into each of the components of this indicator.
Volume: Volume refers to the number of shares or contracts traded in a security or an entire market during a given period. It is a measure of the total trading activity and liquidity, indicating the overall interest in a stock or market.
Price Action: the analysis of historical prices to inform trading decisions, without the use of technical indicators. It focuses on the movement of prices to identify patterns, trends, and potential reversal points in the market.
Relative Strength Line: The RS line is a popular tool used to compare the performance of a stock, typically calculated as the ratio of the stock's price to a benchmark index's price. It helps identify outperformers and underperformers relative to the market or a specific sector. The RS value is calculated by dividing the close price of the chosen stock by the close price of the comparative symbol (SPX by default).
Average True Range (ATR): ATR is a market volatility indicator used to show the average range prices swing over a specified period. It is calculated by taking the moving average of the true ranges of a stock for a specific period. The true range for a period is the greatest of the following three values:
The difference between the current high and the current low.
The absolute value of the current high minus the previous close.
The absolute value of the current low minus the previous close.
Average Daily Range (ADR): ADR is a measure used in trading to capture the average range between the high and low prices of an asset over a specified number of past trading days. Unlike the Average True Range (ATR), which accounts for gaps in the price from one day to the next, the Average Daily Range focuses solely on the trading range within each day and averages it out.
Anchored VWAP: AVWAP gives the average price of an asset, weighted by volume, starting from a specific anchor point. This provides traders with a dynamic average price considering both price and volume from a specific start point, offering insights into the market's direction and potential support or resistance levels.
Moving Averages: Moving Averages smooth out price data by creating a constantly updated average price over a specific period of time. It helps traders identify trends by flattening out the fluctuations in price data.
Stochastic: A stochastic oscillator is a momentum indicator used in technical analysis that compares a particular closing price of an asset to a range of its prices over a certain period of time. The theory behind the stochastic oscillator is that in a market trending upwards, prices will tend to close near their high, and in a market trending downwards, prices close near their low.
While each of these components offer unique insights into market behavior, providing sell signals under specific conditions, the power of combining these different signals lies in their ability to confirm each other's signals. This in turn reduces false positives and provides a more reliable basis for trading decisions
These signals can be recognized at any time, however the indicators power is in it's ability to take into account where a trade is in terms of your entry price and stop.
If a trade just started, it hasn’t earned much leeway. Kind of like a new employee that shows up late on the first day of work. It’s less forgivable than say the person who has been there for a while, has done well, is on time, and then one day comes in late.
Contextual Sensitivity:
For instance, a high volume sell-off coupled with a bearish price action pattern significantly strengthens the sell signal. When the price closes below an Anchored VWAP or a critical moving average in this context, it reaffirms the bearish sentiment, suggesting that the momentum is likely to continue downwards.
By considering the relative strength line (RS) alongside volume and price action, the indicator can differentiate between a normal retracement in a strong uptrend and a when a stock starts to become a laggard.
The integration of ATR and ADR provides a dynamic framework that adjusts to the market's volatility. A sudden increase in ATR or a character change detected through comparing short-term and long-term ADR can alert traders to emerging trends or reversals.
The "Danger Signals" indicator exemplifies the power of integrating diverse technical indicators to create a more sophisticated, responsive, and adaptable trading tool. This approach not only amplifies the individual strengths of each indicator but also mitigates their weaknesses.
Portfolio Heat Indicator can be found by clicking on the image below
Danger Signals Included
Price Closes Near Low - Daily Closing Range of 30% or Less
Price Closes Near Weekly Low - Weekly Closing Range of 30% or Less
Price Closes Near Daily Low on Heavy Volume - Daily Closing Range of 30% or Less on Heaviest Volume of the Last 5 Days
Price Closes Near Weekly Low on Heavy Volume - Weekly Closing Range of 30% or Less on Heaviest Volume of the Last 5 Weeks
Price Closes Below Moving Average - Price Closes Below One of 5 Selected Moving Averages
Price Closes Below Swing Low - Price Closes Below Most Recent Swing Low
Price Closes Below 1.5 ATR - Price Closes Below Trailing ATR Stop Based on Highest High of Last 10 Days
Price Closes Below AVWAP - Price Closes Below Selected Anchored VWAP (Anchors include: High of base, Low of base, Highest volume of base, Custom date)
Price Shows Aggressive Selling - Current Bars High is Greater Than Previous Day's High and Closes Near the Lows on Heaviest Volume of the Last 5 Days
Outside Reversal Bar - Price Makes a New High and Closes Near the Lows, Lower Than the Previous Bar's Low
Price Shows Signs of Stalling - Heavy Volume with a Close of Less than 1%
3 Consecutive Days of Lower Lows - 3 Days of Lower Lows
Close Lower than 3 Previous Lows - Close is Less than 3 Previous Lows
Character Change - ADR of Last Shorter Length is Larger than ADR of Longer Length
Fast Stochastic Crosses Below Slow Stochastic - Fast Stochastic Crosses Below Slow Stochastic
Fast & Slow Stochastic Curved Down - Both Stochastic Lines Close Lower than Previous Day for 2 Consecutive Days
Lower Lows & Lower Highs Intraday - Lower High and Lower Low on 30 Minute Timeframe
Moving Average Crossunder - Selected MA Crosses Below Other Selected MA
RS Starts Curving Down - Relative Strength Line Closes Lower than Previous Day for 2 Consecutive Days
RS Turns Negative Short Term - RS Closes Below RS of 7 Days Ago
RS Underperforms Price - Relative Strength Line Not at Highs, While Price Is
Moving Average Begins to Flatten Out - First Day MA Doesn't Close Higher
Price Moves Higher on Lighter Volume - Price Makes a New High on Light Volume and 15 Day Average Volume is Less than 50 Day Average
Price Hits % Target - Price Moves Set % Higher from Entry Price
Price Hits R Multiple - Price hits (Entry - Stop Multiplied by Setting) and Added to Entry
Price Hits Overhead Resistance - Price Crosses a Swing High from a Monthly Timeframe Chart from at Least 1 Year Ago
Price Hits Fib Level - Price Crosses a Fib Extension Drawn From Base High to Low
Price Hits a Psychological Level - Price Crosses a Multiple of 0 or 5
Heavy Volume After Significant Move - Above Average and Heaviest Volume of the Last 5 Days 35 Bars or More from Breakout
Moving Averages Begin to Slope Downward - Moving Averages Fall for 2 Consecutive Days
Blow Off Action - Highest Volume, Largest Spread, Multiple Gaps in a Row 35 Bars or More Post Breakout
Late Buying Frenzy - ANTS 35 Bars or More Post Breakout
Exhaustion Gap - Gap Up 5% or Higher with Price 125% or More Above 200sma
Simple Position SizerSimple Position Sizer is designed to calculate optimal position sizes based on a defined risk percentage and stop-loss level. It offers two modes for determining position size: using the current close price or a specified entry price. The script provides key trade details such as entry price, stop-loss level, quantity to trade, total cost, and risk amount in monetary terms, alongside visual indications of these parameters through colored lines and labels on the chart. Users can customize account size, risk per trade percentage, and entry and stop-loss levels directly within the settings.
Usage Scenario:
A trader looking to enter a position would first decide whether the entry is based on the current closing price or a predetermined level. After setting the stop-loss level and specifying the risk per trade as a percentage of the account size, the script calculates the number of shares or contracts to purchase. It also computes the total cost of the position and displays the potential loss if the stop-loss is triggered, allowing the trader to understand the risk involved before entering the trade.
Visual Indicators:
Green indicators suggest a long setup where the entry level is above the stop-loss, indicating bullish entry.
Red indicators signal a short setup where the entry level is below the stop-loss, reflecting bearish entry
Blue lines represent the entry level when specified by the trader, providing a visual cue for planned entries.
Temporal Value Tracker: Inception-to-Present Inflation Lens!What we're looking at here is a chart that does more than just display the price of gold. It offers us a time-traveling perspective on value. The blue line, that's our nominal price—it's the straightforward market price of gold over time. But it's the red line that takes us on a deeper journey. This line adjusts the nominal price for inflation, showing us the real purchasing power of gold.
Now, when we talk about 'real value,' we're not just philosophizing. We're anchoring our prices to a point in time when the journey began—let's say when gold trading started on the markets, or any inception point we choose. By 'shadowing' certain years—say, from the 1970s when the gold standard was abandoned—we can adjust this chart to reflect what the inflation-adjusted price means since that key moment in history.
By doing so, we're effectively isolating our view to start from that pivotal year, giving us insight into how gold, or indeed any asset, has held up against the backdrop of economic changes, policy shifts, and the inevitable rise in the cost of living. If you're analyzing a stock index like the S&P 500, you might begin your inflation-adjusted view from the index's inception date, which allows you to measure the true growth of the market basket from the moment it started.
This adjustment isn't just academic. It influences how we perceive value and growth. Consider a period where the nominal price skyrockets. We might toast to our brilliance in investment! But if the inflation-adjusted line lags, what we're seeing is nominal growth without real gains. On the other hand, if our red line outpaces the blue even during stagnant market periods, we're witnessing real growth—our asset is outperforming the eroding effects of inflation.
Every asset class can be evaluated this way. Stocks, bonds, real estate—they all have their historical narratives, and inflation adjustment tells us if these stories are tales of genuine growth or illusions masked by inflation.
So, as informed traders and investors, we need to keep our eyes on this inflation-adjusted line. It's our measure against the silent thief that is inflation. It ensures we're not just keeping up with the Joneses of the market, but actually outpacing them, building real wealth over time
[S1B] Leverage Take-Profit-LinesShort Description:
The Leverage Take-Profit-Lines indicator assists traders in setting take-profit and stop-loss levels based on leverage, entry price, and risk percentage. It draws horizontal lines representing various take-profit levels and the stop-loss level on the chart, aiding traders in visually identifying potential exit points and managing risk.
Detailed Description:
The Leverage Take-Profit-Lines indicator is designed to provide traders with a visual representation of take-profit and stop-loss levels tailored to their leverage, entry price, and risk preferences.
Key Features:
Customizable Parameters: Traders can adjust parameters such as leverage, entry price, risk percentage, and whether to extend lines to suit their trading strategy.
Take-Profit Levels: The indicator calculates and draws horizontal lines representing different take-profit levels based on the specified percentage of leverage-adjusted entry price.
Stop-Loss Level: It calculates and displays the stop-loss level based on the specified risk percentage and leverage, helping traders manage risk effectively.
Visual Representation: The indicator visually highlights take-profit and stop-loss levels on the chart, facilitating quick decision-making for traders.
Usage Guide:
Setting Parameters: Adjust the input parameters including leverage, entry price, risk percentage, and other settings according to your trading strategy.
Interpreting Lines: Horizontal lines are drawn on the chart representing take-profit levels (TP1, TP2, TP3, TP4) and the stop-loss level. These lines indicate potential exit points and risk management levels.
As an example the TP1 can be used to sell 10% of position size, TP2 20%, TP3 20% and TP4 20-40%.
The Leverage Take-Profit-Lines indicator empowers traders with valuable insights into setting profit targets and managing risk effectively, contributing to more informed trading decisions.
Historical Correlation [LuxAlgo]The Historical Correlation tool aims to provide the historical correlation coefficients of up to 10 pairs of user-defined tickers starting from a user-defined point in time.
Users can choose to display the historical values as lines or the most recent correlation values as a heat map.
🔶 USAGE
This tool provides historical correlation coefficients, the correlation coefficient between two assets highlight their linear relationship and is always within the range (-1, 1).
It is a simple and easy to use statistical tool, with the following interpretation:
Positive correlation (values close to +1.0): the two assets move in sync, they rise and fall at the same time.
Negative correlation (values close to -1.0): the two assets move in opposite directions: when one goes up, the other goes down and vice versa.
No correlation (values close to 0): the two assets move independently.
The user must confirm the selection of the anchor point in order for the tool to be executed; this can be done directly on the chart by clicking on any bar, or via the date field in the settings panel.
For the parameter Anchor period , the user can choose between the following values NONE, HOURLY, DAILY, WEEKLY, MONTHLY, QUARTERLY and YEARLY. If NONE is selected, there will be no resetting of the calculations, otherwise the calculations will start from the first bar of the new period.
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 negative correlated asset or going short a positive correlated asset.
Traders generally need to develop awareness, a key point is to be aware of the relationships between the assets we hold or trade, the historical correlation is an invaluable tool in our arsenal which allows us to make better informed decisions.
On this chart we have an example of historical correlations for several futures markets.
We can clearly see how positively correlated the Nasdaq100 and Dow30 are with the SP500 over the whole period, or how the correlation between the Euro and the SP500 falls from almost +85% to almost -4% since 2021.
As we can see, correlations, like everything else in the market, are not static and vary over time depending on many factors, from macro to technical and everything in between.
🔹 Heatmap
The chart above shows the tool with the default settings and the Drawing Mode set to 'HEATMAP'.
We can see the current correlation between the assets, in this case the FX pairs.
The highest positive correlation is +90% (+0.90) between EURUSD and GBPUSD.
The highest negative correlation is -78% (-0.78) between EURUSD and USDJPY.
The pair with no correlation is AUDUSD and EURCAD with 1% (0.01)
On the above chart we can see the current correlations for the futures markets.
Currently, the assets that are less correlated to the SP500 are NaturalGas and the Euro, the more positive correlations are Nasdaq100 and Dow20, and the more negative correlations are the Yen, Treasury Bonds and 10-Year Notes.
🔶 DETAILS
🔹 Anchor Period
This chart shows the standard FX correlations with the Anchor Period set to `MONTHLY`.
We can clearly see how the calculations restart with the new month, in this case we can clearly see the differences between the correlations from month to month.
Let us look at the correlation coefficient between GBPUSD and USDJPY
In January, their correlation started at close to -100%, rose to close to +50%, only to fall to close to 0% and remain there for the second half of the month.
In February it was -90% in the first few days of the month and is now around -57%.
And between AUDUSD and EURCAD
Last month their correlation was negative for most of the month, reaching -70% and ending around -14%.
This month their correlation has never gone below +21% and at the time of writing is close to +53%.
🔶 SETTINGS
Anchor point: Starting point from which the tool is executed
Anchor period: At the beginning of each new period, the tool will reset the calculations
Pairs from 1 to 10: For each pair of tickers, you can: enable/disable the pair, select the color and specify the two tickers from which you wish to obtain the correlation
🔹 Style
Drawing Mode: Output style, `LINES` will show the historical correlations as lines, `HEATMAP` will show the current correlations with a color gradient from green for correlations near 1 to red for correlations near -1.
Bitcoin Momentum StrategyThis is a very simple long-only strategy I've used since December 2022 to manage my Bitcoin position.
I'm sharing it as an open-source script for other traders to learn from the code and adapt it to their liking if they find the system concept interesting.
General Overview
Always do your own research and backtesting - this script is not intended to be traded blindly (no script should be) and I've done limited testing on other markets beyond Ethereum and BTC, it's just a template to tweak and play with and make into one's own.
The results shown in the strategy tester are from Bitcoin's inception so as to get a large sample size of trades, and potential returns have diminished significantly as BTC has grown to become a mega cap asset, but the script includes a date filter for backtesting and it has still performed solidly in recent years (speaking from personal experience using it myself - DYOR with the date filter).
The main advantage of this system in my opinion is in limiting the max drawdown significantly versus buy & hodl. Theoretically much better returns can be made by just holding, but that's also a good way to lose 70%+ of your capital in the inevitable bear markets (also speaking from experience).
In saying all of that, the future is fundamentally unknowable and past results in no way guarantee future performance.
System Concept:
Capture as much Bitcoin upside volatility as possible while side-stepping downside volatility as quickly as possible.
The system uses a simple but clever momentum-style trailing stop technique I learned from one of my trading mentors who uses this approach on momentum/trend-following stock market systems.
Basically, the system "ratchets" up the stop-loss to be much tighter during high bearish volatility to protect open profits from downside moves, but loosens the stop loss during sustained bullish momentum to let the position ride.
It is invested most of the time, unless BTC is trading below its 20-week EMA in which case it stays in cash/USDT to avoid holding through bear markets. It only trades one position (no pyramiding) and does not trade short, but can easily be tweaked to do whatever you like if you know what you're doing in Pine.
Default parameters:
HTF: Weekly Chart
EMA: 20-Period
ATR: 5-period
Bar Lookback: 7
Entry Rule #1:
Bitcoin's current price must be trading above its higher-timeframe EMA (Weekly 20 EMA).
Entry Rule #2:
Bitcoin must not be in 'caution' condition (no large bearish volatility swings recently).
Enter at next bar's open if conditions are met and we are not already involved in a trade.
"Caution" Condition:
Defined as true if BTC's recent 7-bar swing high minus current bar's low is > 1.5x ATR, or Daily close < Daily 20-EMA.
Trailing Stop:
Stop is trailed 1 ATR from recent swing high, or 20% of ATR if in caution condition (ie. 0.2 ATR).
Exit on next bar open upon a close below stop loss.
I typically use a limit order to open & exit trades as close to the open price as possible to reduce slippage, but the strategy script uses market orders.
I've never had any issues getting filled on limit orders close to the market price with BTC on the Daily timeframe, but if the exchange has relatively low slippage I've found market orders work fine too without much impact on the results particularly since BTC has consistently remained above $20k and highly liquid.
Cost of Trading:
The script uses no leverage and a default total round-trip commission of 0.3% which is what I pay on my exchange based on their tier structure, but this can vary widely from exchange to exchange and higher commission fees will have a significantly negative impact on realized gains so make sure to always input the correct theoretical commission cost when backtesting any script.
Static slippage is difficult to estimate in the strategy tester given the wide range of prices & liquidity BTC has experienced over the years and it largely depends on position size, I set it to 150 points per buy or sell as BTC is currently very liquid on the exchange I trade and I use limit orders where possible to enter/exit positions as close as possible to the market's open price as it significantly limits my slippage.
But again, this can vary a lot from exchange to exchange (for better or worse) and if BTC volatility is high at the time of execution this can have a negative impact on slippage and therefore real performance, so make sure to adjust it according to your exchange's tendencies.
Tax considerations should also be made based on short-term trade frequency if crypto profits are treated as a CGT event in your region.
Summary:
A simple, but effective and fairly robust system that achieves the goals I set for it.
From my preliminary testing it appears it may also work on altcoins but it might need a bit of tweaking/loosening with the trailing stop distance as the default parameters are designed to work with Bitcoin which obviously behaves very differently to smaller cap assets.
Good luck out there!
Power OutageThe Power Outage indicator serves as the antithesis to the Power Trend, highlighting periods of extreme weakness or downtrends. Drawing inspiration from the Power Trend, the Power Outage framework was conceived by reversing the logic to highlight periods where being in cash or net short could be beneficial.
What Initiates a Power Outage?
The high is below the 21-day EMA for at least 10 consecutive days.
The 21-day EMA is below the 50-day SMA for a minimum of five days.
The 50-day SMA is on a downward trajectory.
The closing price is lower than the previous day's close.
A Power Outage can be a caution sign for traders to tighten up risk management and encourage defensive strategies or the consideration of short positions. Not only does this indicator clearly identify a Power Outage by a shaded background or shape plotted on the chart, but it also records metrics for each previous Power Outage.
The number of Power Outages that have occurred, their average length, and average depth (from the first day's close when the Power Outage activates to the low of the Power Outage) are all displayed to help assess the condition of the current Power Outage.
What Ends a Power Outage?
A Power Outage ends when the 21-day EMA crosses above the 50-day SMA, or when the price closes 10% above the recent low and above the 50-day SMA.
This indicator is designed to be viewed on a daily time frame.
Index investingThe Index Investing indicator simplifies decision-making for adding to Index ETF's Long-term investments. By utilizing a percentage discount methodology, it highlights potential opportunities to enhance portfolios. This straightforward tool aids in identifying favorable moments to invest based on calculated price discounts from selected reference points, making the process more systematic and less subjective.
🔶 SETTINGS
Reference Price: Choose between 'All-Time-High' or 'Start of the Year' as the basis for calculating discount levels. This allows for flexibility in strategy depending on market conditions or investment philosophy.
Discount 1 %, Discount 2 %, Discount 3 %: These inputs define the percentage below the reference price at which buy signals are generated. They represent strategic entry points at discounted prices.
🔶 Default Parameters
The default parameters of 4.13%, 8.26%, and 12.39% for the discount levels are chosen based on the average 5-year return of the NSE:NIFTY Index, which stands at approximately 12.39%. By dividing this return into three parts, we obtain a structured approach to capturing potential upside at varying levels of market retracement, providing a logical basis for the selected default values.
Users have the flexibility to modify these parameters, tailoring the indicator to fit their unique approach and market outlook.
🔶 How Levels Are Calculated
Discount levels are calculated using the formula: Discount Price = Reference Price * (1 - Discount %) . This succinct approach establishes specific entry points below the chosen reference, such as an all-time high or the year's start price.
🔶 How Are the Buy Labels Generated
Buy signals are generated when the market price(Low of the candle) crosses under any of the defined discount levels. Each level has a corresponding buy label ('Buy 1', 'Buy 2', 'Buy 3'), which is activated upon the price crossing below the specified discount level and is only reset at the beginning of a new year or upon reaching a new reference high, ensuring signals are not repetitive for the same price level.
🔶 Other Features
Alerts: The indicator provides alerts for each buy signal, notifying potential entry points at their defined discount levels. The alert triggers only once per candle.
Year Marker: A vertical line with an accompanying label marks the start of each trading year on the chart. This feature aids in visualizing the temporal context of buy signals and reference price adjustments.
Position Size CalculatorThe provided Pine Script is a custom indicator titled "Position Size Calculator" designed to assist traders in calculating the appropriate size of a trading position based on predefined risk parameters. This script is intended to be overlaid on a trading chart, as indicated by `overlay=true`, allowing traders to visualize and adjust their risk and position size directly within the context of their trading strategy.
What It Does:
The core functionality of this script revolves around calculating the position size a trader should take based on three input parameters:
**Risk in USD (`Risk`)**: This represents the amount of money the trader is willing to risk on a single trade.
**Entry Price (`EntryPrice`)**: The price at which the trader plans to enter the market.
**Stop Loss (`StopLoss`)**: The price at which the trader plans to exit the market should the trade move against them, effectively limiting their loss.
The script calculates the position size using a function named `calculatePositionSize`, which performs the following steps:
It first calculates the `expectedLoss` by taking 90% (`0.9`) of the input risk. This implies that the script factors in a safety margin, assuming traders are willing to risk up to 90% of their stated risk amount per trade.
It then calculates the position size based on the distance between the Entry Price and the Stop Loss. This calculation adjusts based on whether the Entry Price is higher or lower than the Stop Loss, ensuring that the position size fits the risk profile regardless of trade direction.
The function returns several values: `risk`, `entryPrice`, `stopLoss`, `expectedLoss`, and `size`, which are then plotted on the chart.
How It Does It:
**Expected Loss Calculation**: By reducing the risk by 10% before calculating position size, the script provides a buffer to account for slippage or to ensure the trader does not fully utilize their risk budget on a single trade.
**Position Size Calculation**: The script calculates position size by dividing the adjusted risk (`expectedLoss`) by the price difference between the Entry Price and Stop Loss. This gives a quantitative measure of how many units of the asset can be bought or sold while staying within the risk parameters.
What Traders Can Use It For:
Traders can use this Position Size Calculator for several purposes:
- **Risk Management**: By determining the appropriate position size, traders can ensure that they do not overexpose themselves to market risk on a single trade.
- **Trade Planning**: Before entering a trade, the script allows traders to visualize their risk, entry, and exit points, helping them to make more informed decisions.
- **Consistency**: Using a standardized method for calculating position size helps traders maintain consistency in their trading approach, a key aspect of successful trading strategies.
- **Efficiency**: Automating the calculation of position size saves time and reduces the likelihood of manual calculation errors.
Overall, this Pine Script indicator is a practical tool for traders looking to implement strict risk management rules within their trading strategies, ensuring that each trade is sized appropriately according to their risk tolerance and market conditions.