Candle Size Alerts (Manual size)This TradingView Pine Script (v6) is an indicator that triggers alerts based on the size of the previous candle. Here's a breakdown of how it works:
1. Indicator Definition
//@version=6
indicator('Candle Size Alerts (Manual size)', overlay = true)
The script is written in Pine Script v6.
indicator('Candle Size Alerts (Manual size)', overlay = true):
Defines the indicator name as "Candle Size Alerts (Manual size)".
overlay = true means it runs directly on the price chart (not as a separate panel).
2. Calculate the Previous Candle's Body Size
candleSize = math.abs(close - open )
close and open refer to the previous candle’s closing and opening prices.
math.abs(...) ensures that the size is always a positive value, regardless of whether it's a green or red candle.
3. Define a User-Adjustable Candle Size Threshold
candleThreshold = input(500, title = 'Fixed Candle Size Threshold')
input(500, title = 'Fixed Candle Size Threshold'):
Allows users to set a custom threshold (default is 500 points).
If the previous candle's body size exceeds or equals this threshold, an alert is triggered.
4. Check if the Candle Size Meets the Condition
sizeCondition = candleSize >= candleThreshold
This evaluates whether the previous candle's size is greater than or equal to the threshold.
If true, an alert will be generated.
5. Determine Candle Color
isRedCandle = close < open
isGreenCandle = close > open
isRedCandle: The candle is red if the closing price is lower than the opening price.
isGreenCandle: The candle is green if the closing price is higher than the opening price.
6. Generate Alerts Based on Candle Color
if sizeCondition
if isRedCandle
alert('SHORT SIGNAL: Previous candle is RED, body size = ' + str.tostring(candleSize) + ' points (Threshold: ' + str.tostring(candleThreshold) + ')', alert.freq_once_per_bar)
else if isGreenCandle
alert('LONG SIGNAL: Previous candle is GREEN, body size = ' + str.tostring(candleSize) + ' points (Threshold: ' + str.tostring(candleThreshold) + ')', alert.freq_once_per_bar)
If the candle size meets the threshold (sizeCondition == true):
If red, a SHORT SIGNAL alert is triggered.
If green, a LONG SIGNAL alert is triggered.
alert.freq_once_per_bar ensures that alerts are sent only once per candle (avoiding repeated notifications).
How It Works in TradingView:
The script does not plot anything on the chart.
It monitors the previous candle’s body size.
If the size exceeds the threshold, an alert is generated.
Alerts can be used to notify the trader when big candles appear.
How to set Alerts in Trading View
1. Select Indicator – Ensure the indicator is added and properly configured.
2. Set Time Frame – Make sure it's appropriate for your trading strategy.
3. Open Alerts Panel – Click the "Alerts" tab or use the shortcut (Alt + A on Windows).
4. Create a New Alert – Click "+" or "Create Alert."
5. Select Condition – Pick the relevant indicator condition (e.g., "Candle Size Alerts(Manual size)").
6. Choose Alert Function – Default is "Any Alert() Function Call".
7. Set Expiration & Name – Define how long the alert remains active.
8. Configure Notifications – Choose between pop-up, email, webhook, or app notifications.
9. Create Alert – Click "Create" to finalize.
How to set the size manually:
Add the "Candle Size Alerts (Manual size)" Indicator to your chart.
Open Indicator Settings – Click on the indicator and go to the "Inputs" tab.
Set Fixed Size Threshold – Adjust the "Fixed Size Candle Threshold" to your desired value.
Click OK – This applies the changes.
Reset Alerts – Delete and recreate alerts to reflect the new threshold.
Happy Trading !!!!
بيتكوين (عملة رقمية)
Session vertical linesThis script automatically plots vertical lines every 4 hours which follows Bitcoins rhythmic cycle:
⏰ 8 AM, 12 PM, 4 PM, 8 PM, 12 AM, 4 AM.
It visually marks the start of each session, helping you plan trades efficiently. Perfect for crypto traders.
Candle Size Alert (Open-Close)This Pine Script is a TradingView indicator that checks the size of the previous candle's body (difference between the open and close prices) and triggers an alert if it exceeds a certain threshold.
Breakdown of the Script
1. Indicator Declaration
//@version=5
indicator("Candle Size Alert (Open-Close)", overlay=true)
//@version=5: Specifies that the script is using Pine Script v5.
indicator("Candle Size Alert (Open-Close)", overlay=true):
Creates an indicator named "Candle Size Alert (Open-Close)".
overlay=true: Ensures the script runs directly on the price chart (not in a separate panel).
2. User-Defined Threshold
candleThreshold = input.int(500, title="Candle Size Threshold")
input.int(500, title="Candle Size Threshold"):
Allows the user to set the threshold for candle body size.
Default value is 500 points.
3. Calculate Candle Size
candleSize = math.abs(close - open )
close and open :
close : Closing price of the previous candle.
open : Opening price of the previous candle.
math.abs(...):
Takes the absolute difference between the open and close price.
This gives the candle body size (ignoring whether it's bullish or bearish).
4. Check If the Candle Size Meets the Threshold
sizeCondition = candleSize >= candleThreshold
If the previous candle’s body size is greater than or equal to the threshold, sizeCondition becomes true.
5. Determine Candle Color
isRedCandle = close < open
isGreenCandle = close > open
Red Candle (Bearish):
If the closing price is less than the opening price (close < open ).
Green Candle (Bullish):
If the closing price is greater than the opening price (close > open ).
6. Generate Alerts
if sizeCondition
direction = isRedCandle ? "SHORT SIGNAL (RED)" : "LONG SIGNAL (GREEN)"
alertMessage = direction + ": Previous candle body size = " + str.tostring(candleSize) +
" points (Threshold: " + str.tostring(candleThreshold) + ")"
alert(alertMessage, alert.freq_once_per_bar)
If the candle body size exceeds the threshold, an alert is triggered.
direction = isRedCandle ? "SHORT SIGNAL (RED)" : "LONG SIGNAL (GREEN)":
If the candle is red, it signals a short (sell).
If the candle is green, it signals a long (buy).
The alert message includes:
Signal type (LONG/SHORT).
Candle body size.
The user-defined threshold.
How It Works in TradingView:
The script does not plot anything on the chart.
It monitors the previous candle’s body size.
If the size exceeds the threshold, an alert is generated.
Alerts can be used to notify the trader when big candles appear.
WAGMI LAB Bitcoin SCALPING TREND REV + VOL FILTER WAGMI LAB Bitcoin SCALPING TREND REV + VOL FILTER is a powerful scalping indicator designed for Bitcoin (BTC) on M1, M5, and M15 timeframes. It helps traders identify trend reversals with volume confirmation, making it an effective tool for short-term trading.
Key Features:
✅ Hull Moving Average (HMA) – A fast-reacting trend filter to determine bullish or bearish momentum.
✅ MACD Confirmation – Ensures momentum shift alignment for stronger entry signals.
✅ Volume-Based Filtering – Uses a moving average of volume to filter out weak signals and avoid false breakouts.
✅ Clear Buy & Sell Signals – Plots green arrows for buy signals and red arrows for sell signals, making decision-making easier.
This indicator is ideal for scalpers looking to trade Bitcoin's rapid price movements efficiently while minimizing noise. 🚀💰
👉 Recommended Timeframes: M1, M5, M15
👉 Best Used With: Additional support/resistance levels or order flow analysis for enhanced accuracy.
Try it now and take your Bitcoin scalping to the next level! 🚀🔥
Ragi's 24h volumeThis script is a TradingView Pine Script indicator that displays the 24-hour trading volume for a given asset. It provides both the native volume of the asset and, if the asset is not already listed on Binance, also displays the 24-hour volume from Binance (if applicable). Here's a breakdown of the key components:
Volume Calculation:
It sums the volume data over different time frames: 1-minute, 5-minute (for daily charts), or 60-minute intervals.
The volume is calculated based on the asset's volume type (either "quote" volume or a calculated value of close * volume).
For crypto assets, if the volume data is unavailable, it raises an error.
Binance Volume:
If the asset is not from Binance, the script fetches 24-hour volume data from Binance for that symbol, ensuring it is using the correct currency rate.
Display:
The indicator displays a table with the 24-hour volume in the chosen position on the chart (top, middle, or bottom).
The table displays the current exchange's volume, and if applicable, the Binance volume.
The volume is color-coded based on predefined thresholds:
Attention: Displays a warning color for volumes exceeding the attention level.
Warning: Shows an alert color for volumes above the warning threshold.
Normal: Displays in standard color when the volume is lower than the warning level.
The text and background color are customizable, and users can adjust the text size and position of the table.
User Inputs:
The script allows customization of table text size, position, background color, and volume thresholds for attention and warning.
In summary, this indicator is designed to track and display 24-hour volume on a chart, with additional volume information from Binance if necessary, and provides visual cues based on volume levels to help traders quickly assess trading activity.
Crypto Fear & Greed Score [Underblock]Crypto Fear & Greed Score - Methodology & Functioning
Introduction
The Crypto Fear & Greed Score is a comprehensive indicator designed to assess market sentiment by detecting extreme conditions of panic (fear) and euphoria (greed). By combining multiple technical factors, it helps traders identify potential buying and selling opportunities based on the emotional state of the market.
This indicator is highly customizable, allowing users to adjust weight parameters for RSI, volatility, Bitcoin dominance, and trading volume, making it adaptable to different market conditions.
Key Components
The indicator consists of two primary sub-scores:
Fear Score (Panic) - Measures the intensity of fear in the market.
Greed Score (Euphoria) - Measures the level of overconfidence and excessive optimism.
The difference between these two values results in the Net Score, which indicates the dominant market sentiment at any given time.
1. Relative Strength Index (RSI)
The indicator utilizes multiple RSI timeframes to measure momentum and overbought/oversold conditions:
RSI 1D (Daily) - Captures medium-term sentiment shifts.
RSI 4H (4-hour) - Identifies short-term market movements.
RSI 1W (Weekly) - Helps detect long-term overbought/oversold conditions.
2. Volatility Analysis
High volatility is often associated with fear and panic-driven selling.
Low volatility in bullish markets may indicate complacency and overconfidence.
3. Bitcoin Dominance (BTC.D)
Bitcoin dominance provides insights into capital flow between Bitcoin and altcoins:
Rising BTC dominance suggests fear as investors move into BTC for safety.
Declining BTC dominance indicates increased risk appetite and potential market euphoria.
4. Buying and Selling Volume
The indicator analyzes both buying and selling volume, ensuring a clearer confirmation of market sentiment.
High buying volume in uptrends reinforces bullish momentum.
Spikes in selling volume indicate panic and possible market bottoms.
Calculation Methodology
The indicator allows users to adjust weight parameters for each component, making it adaptable to different trading strategies. The formulas are structured as follows:
Fear Score (Panic Calculation)
Fear Score = (1 - RSI_1D) * W_RSI1D + (1 - RSI_4H) * W_RSI4H + (1 - Dominance) * W_Dominance + Volatility * W_Volatility + Sell Volume * W_SellVolume
Greed Score (Euphoria Calculation)
Greed Score = RSI_1D * W_RSI1D + RSI_4H * W_RSI4H + Dominance * W_Dominance + (1 - Volatility) * W_Volatility + Buy Volume * W_BuyVolume
Net Fear & Greed Score
Net Score = (Greed Score - Fear Score) * 100
Interpretation:
Above 70: Extreme greed -> possible overbought conditions.
Below -70: Extreme fear -> potential buying opportunity.
Near 0: Neutral market sentiment.
Trend Reversal Detection
The indicator includes two moving averages for enhanced trend detection:
Short-term SMA (50-periods) - Reacts quicklier to changes in sentiment.
Long-term SMA (200-periods) - Captures broader trend reversals.
How Crossovers Work:
Short SMA crossing above Long SMA -> Potential bullish reversal.
Short SMA crossing below Long SMA -> Possible bearish trend shift.
Alerts for SMA crossovers help traders act on momentum shifts in real-time.
Customization and Visualization
The Net Score dynamically changes color: green for greed, red for fear.
Users can adjust weightings directly from settings, avoiding manual script modifications.
Reference levels at 70 and -70 provide clarity on extreme market conditions.
Conclusion
The Crypto Fear & Greed Score provides a powerful and objective measure of market sentiment, helping traders navigate extreme conditions effectively.
🟢 If the Net Score is below -70, panic may present a buying opportunity.
🔴 If the Net Score is above 70, excessive euphoria may indicate a selling opportunity.
⚖️ Neutral values suggest a balanced market sentiment.
By customizing weight parameters and utilizing trend reversal alerts, traders can gain a deeper insight into market psychology and make more informed trading decisions. 🚀
ADX for BTC [PineIndicators]The ADX Strategy for BTC is a trend-following system that uses the Average Directional Index (ADX) to determine market strength and momentum shifts. Designed for Bitcoin trading, this strategy applies a customizable ADX threshold to confirm trend signals and optionally filters entries using a Simple Moving Average (SMA). The system features automated entry and exit conditions, dynamic trade visualization, and built-in trade tracking for historical performance analysis.
⚙️ Core Strategy Components
1️⃣ Average Directional Index (ADX) Calculation
The ADX indicator measures trend strength without indicating direction. It is derived from the Positive Directional Movement (+DI) and Negative Directional Movement (-DI):
+DI (Positive Directional Index): Measures upward price movement.
-DI (Negative Directional Index): Measures downward price movement.
ADX Value: Higher values indicate stronger trends, regardless of direction.
This strategy uses a default ADX length of 14 to smooth out short-term fluctuations while detecting sustainable trends.
2️⃣ SMA Filter (Optional Trend Confirmation)
The strategy includes a 200-period SMA filter to validate trend direction before entering trades. If enabled:
✅ Long Entry is only allowed when price is above a long-term SMA multiplier (5x the standard SMA length).
✅ If disabled, the strategy only considers the ADX crossover threshold for trade entries.
This filter helps reduce entries in sideways or weak-trend conditions, improving signal reliability.
📌 Trade Logic & Conditions
🔹 Long Entry Conditions
A buy signal is triggered when:
✅ ADX crosses above the threshold (default = 14), indicating a strengthening trend.
✅ (If SMA filter is enabled) Price is above the long-term SMA multiplier.
🔻 Exit Conditions
A position is closed when:
✅ ADX crosses below the stop threshold (default = 45), signaling trend weakening.
By adjusting the entry and exit ADX levels, traders can fine-tune sensitivity to trend changes.
📏 Trade Visualization & Tracking
Trade Markers
"Buy" label (▲) appears when a long position is opened.
"Close" label (▼) appears when a position is exited.
Trade History Boxes
Green if a trade is profitable.
Red if a trade closes at a loss.
Trend Tracking Lines
Horizontal lines mark entry and exit prices.
A filled trade box visually represents trade duration and profitability.
These elements provide clear visual insights into trade execution and performance.
⚡ How to Use This Strategy
1️⃣ Apply the script to a BTC chart in TradingView.
2️⃣ Adjust ADX entry/exit levels based on trend sensitivity.
3️⃣ Enable or disable the SMA filter for trend confirmation.
4️⃣ Backtest performance to analyze historical trade execution.
5️⃣ Monitor trade markers and history boxes for real-time trend insights.
This strategy is designed for trend traders looking to capture high-momentum market conditions while filtering out weak trends.
Cash And Carry Arbitrage BTC Compare Month 6 by SeoNo1Detailed Explanation of the BTC Cash and Carry Arbitrage Script
Script Title: BTC Cash And Carry Arbitrage Month 6 by SeoNo1
Short Title: BTC C&C ABT Month 6
Version: Pine Script v5
Overlay: True (The indicators are plotted directly on the price chart)
Purpose of the Script
This script is designed to help traders analyze and track arbitrage opportunities between the spot market and futures market for Bitcoin (BTC). Specifically, it calculates the spread and Annual Percentage Yield (APY) from a cash-and-carry arbitrage strategy until a specific expiry date (in this case, June 27, 2025).
The strategy helps identify profitable opportunities when the futures price of BTC is higher than the spot price. Traders can then buy BTC in the spot market and short BTC futures contracts to lock in a risk-free profit.
1. Input Settings
Spot Symbol: The real-time BTC spot price from Binance (BTCUSDT).
Futures Symbol: The BTC futures contract that expires in June 2025 (BTCUSDM2025).
Expiry Date: The expiration date of the futures contract, set to June 27, 2025.
These inputs allow users to adjust the symbols or expiry date according to their trading needs.
2. Price Data Retrieval
Spot Price: Fetches the latest closing price of BTC from the spot market.
Futures Price: Fetches the latest closing price of BTC futures.
Spread: The difference between the futures price and the spot price (futures_price - spot_price).
The spread indicates how much higher (or lower) the futures price is compared to the spot market.
3. Time to Maturity (TTM) and Annual Percentage Yield (APY) Calculation
Current Date: Gets the current timestamp.
Time to Maturity (TTM): The number of days left until the futures contract expires.
APY Calculation:
Formula:
APY = ( Spread / Spot Price ) x ( 365 / TTM Days ) x 100
This represents the annualized return from holding a cash-and-carry arbitrage position if the trader buys BTC at the spot price and sells BTC futures.
4. Display Information Table on the Chart
A table is created on the chart's top-right corner showing the following data:
Metric: Labels such as Spread and APY
Value: Displays the calculated spread and APY
The table automatically updates at the latest bar to display the most recent data.
5. Alert Condition
This sets an alert condition that triggers every time the script runs.
In practice, users can modify this alert to trigger based on specific conditions (e.g., APY exceeds a threshold).
6. Plotting the APY and Spread
APY Plot: Displays the annualized yield as a blue line on the chart.
Spread Plot: Visualizes the futures-spot spread as a red line.
This helps traders quickly identify arbitrage opportunities when the spread or APY reaches desirable levels.
How to Use the Script
Monitor Arbitrage Opportunities:
A positive spread indicates a potential cash-and-carry arbitrage opportunity.
The larger the APY, the more profitable the arbitrage opportunity could be.
Timing Trades:
Execute a buy on the BTC spot market and simultaneously sell BTC futures when the APY is attractive.
Close both positions upon futures contract expiry to realize profits.
Risk Management:
Ensure you have sufficient margin to hold both positions until expiry.
Monitor funding rates and volatility, which could affect returns.
Conclusion
This script is an essential tool for traders looking to exploit price discrepancies between the BTC spot market and futures market through a cash-and-carry arbitrage strategy. It provides real-time data on spreads, annualized returns (APY), and visual alerts, helping traders make informed decisions and maximize their profit potential.
Bitcoin Power Law: Complete with Oscillator + Future Projection
Firstly, we would like to give credit to @apsk32 and @x_X_77_X_x as part of the code originates from their work. Additionally, @apsk32 is widely credited with applying the Power Law concept to Bitcoin and popularizing this model within the crypto community. Additionally, the visual layout is fully inspired by @apsk32's designs, and we think it looks amazing. So much so that we had to turn it into a TradingView script. Thank you!
Understanding the Bitcoin Power Law Model
Also called the Long-Term Bitcoin Power Law Model. The Bitcoin Power Law model tries to capture and predict Bitcoin's price growth over time. It assumes that Bitcoin's price follows an exponential growth pattern, where the price increases over time according to a mathematical relationship.
By fitting a power law to historical data, the model creates a trend line that represents this growth. It then generates additional parallel lines (support and resistance lines) to show potential price boundaries, helping to visualize where Bitcoin’s price could move within certain ranges.
In simple terms, the model helps us understand Bitcoin's general growth trajectory and provides a framework to visualize how its price could behave over the long term.
The Bitcoin Power Law has the following function:
Power Law = 10^(a + b * log10(d))
Consisting of the following parameters:
a: Power Law Intercept (default: -17.668).
b: Power Law Slope (default: 5.926).
d: Number of days since a reference point(calculated by counting bars from the reference point with an offset).
Explanation of the a and b parameters:
Roughly explained, the optimal values for the a and b parameters are determined through a process of linear regression on a log-log scale (after applying a logarithmic transformation to both the x and y axes). On this log-log scale, the power law relationship becomes linear, making it possible to apply linear regression. The best fit for the regression is then evaluated using metrics like the R-squared value, residual error analysis, and visual inspection. This process can be quite complex and is beyond the scope of this post.
Applying vertical shifts to generate the other lines:
Once the initial power-law is created, additional lines are generated by applying a vertical shift . This shift is achieved by adding a specific number of days (or years in case of this script) to the d-parameter. This creates new lines perfectly parallel to the initial power law with an added vertical shift, maintaining the same slope and intercept.
In the case of this script, shifts are made by adding +365 days, +2 * 365 days, +3 * 365 days, +4 * 365 days, and +5 * 365 days, effectively introducing one to five years of shifts. This results in a total of six Power Law lines, as outlined below (From lowest to highest):
Base Power Law Line (no shift)
1-year shifted line
2-year shifted line
3-year shifted line
4-year shifted line
5-year shifted line
The six power law lines:
Bitcoin Power Law Oscillator
This publication also includes the oscillator version of the Bitcoin Power Law. This version applies a logarithmic transformation to the price, Base Power Law Line, and 5-year shifted line using the formula log10(x) .
The log-transformed price is then normalized using min-max normalization relative to the log-transformed Base Power Law Line and 5-year shifted line with the formula:
normalized price = log(close) - log(Base Power Law Line) / log(5-year shifted line) - log(Base Power Law Line)
Finally, the normalized price was multiplied by 5 to map its value between 0 and 5, aligning with the shifted lines. The Oscillator version can be found here .
Interpretation of the Bitcoin Power Law Model:
The shifted Power Law lines provide a framework for predicting Bitcoin's future price movements based on historical trends. These lines are created by applying a vertical shift to the initial Power Law line, with each shifted line representing a future time frame (e.g., 1 year, 2 years, 3 years, etc.).
By analyzing these shifted lines, users can make predictions about minimum price levels at specific future dates. For example, the 5-year shifted line will act as the main support level for Bitcoin’s price in 5 years, meaning that Bitcoin’s price should not fall below this line, ensuring that Bitcoin will be valued at least at this level by that time. Similarly, the 2-year shifted line will serve as the support line for Bitcoin's price in 2 years, establishing that the price should not drop below this line within that time frame.
On the other hand, the 5-year shifted line also functions as an absolute resistance , meaning Bitcoin's price will not exceed this line prior to the 5-year mark. This provides a prediction that Bitcoin cannot reach certain price levels before a specific date. For example, the price of Bitcoin is unlikely to reach $100,000 before 2021, and it will not exceed this price before the 5-year shifted line becomes relevant. After 2028, however, the price is predicted to never fall below $100,000, thanks to the support established by the shifted lines.
In essence, the shifted Power Law lines offer a way to predict both the minimum price levels that Bitcoin will hit by certain dates and the earliest dates by which certain price points will be reached. These lines help frame Bitcoin's potential future price range, offering insight into long-term price behavior and providing a guide for investors and analysts. Lets examine some examples:
Example 1:
In Example 1 it can be seen that point A on the 5-year shifted line acts as major resistance . Also it can be seen that 5 years later this price level now corresponds to the Base Power Law Line and acts as a major support (Note: Vertical yearly grid lines have been added for this purpose👍).
Example 2:
In Example 2, the price level at point C on the 3-year shifted line becomes a major support three years later at point C, now aligning with the Base Power Law Line.
Finally, let's explore some future price predictions, as this script provides projections on the weekly timeframe :
Example 3:
In Example 3, the Bitcoin Power Law indicates that Bitcoin's price cannot surpass approximately $808K before 2030 as can be seen at point E, while also ensuring it will be at least $224K by then (point F).
Bitcoin Log Growth Curve OscillatorThis script presents the oscillator version of the Bitcoin Logarithmic Growth Curve 2024 indicator, offering a new perspective on Bitcoin’s long-term price trajectory.
By transforming the original logarithmic growth curve into an oscillator, this version provides a normalized view of price movements within a fixed range, making it easier to identify overbought and oversold conditions.
For a comprehensive explanation of the mathematical derivation, underlying concepts, and overall development of the Bitcoin Logarithmic Growth Curve, we encourage you to explore our primary script, Bitcoin Logarithmic Growth Curve 2024, available here . This foundational script details the regression-based approach used to model Bitcoin’s long-term price evolution.
Normalization Process
The core principle behind this oscillator lies in the normalization of Bitcoin’s price relative to the upper and lower regression boundaries. By applying Min-Max Normalization, we effectively scale the price into a bounded range, facilitating clearer trend analysis. The normalization follows the formula:
normalized price = (upper regresionline − lower regressionline) / (price − lower regressionline)
This transformation ensures that price movements are always mapped within a fixed range, preventing distortions caused by Bitcoin’s exponential long-term growth. Furthermore, this normalization technique has been applied to each of the confidence interval lines, allowing for a structured and systematic approach to analyzing Bitcoin’s historical and projected price behavior.
By representing the logarithmic growth curve in oscillator form, this indicator helps traders and analysts more effectively gauge Bitcoin’s position within its long-term growth trajectory while identifying potential opportunities based on historical price tendencies.
TSI Long/Short for BTC 2HThe TSI Long/Short for BTC 2H strategy is an advanced trend-following system designed specifically for trading Bitcoin (BTC) on a 2-hour timeframe. It leverages the True Strength Index (TSI) to identify momentum shifts and executes both long and short trades in response to dynamic market conditions.
Unlike traditional moving average-based strategies, this script uses a double-smoothed momentum calculation, enhancing signal accuracy and reducing noise. It incorporates automated position sizing, customizable leverage, and real-time performance tracking, ensuring a structured and adaptable trading approach.
🔹 What Makes This Strategy Unique?
Unlike simple crossover strategies or generic trend-following approaches, this system utilizes a customized True Strength Index (TSI) methodology that dynamically adjusts to market conditions.
🔸 True Strength Index (TSI) Filtering – The script refines the TSI by applying double exponential smoothing, filtering out weak signals and capturing high-confidence momentum shifts.
🔸 Adaptive Entry & Exit Logic – Instead of fixed thresholds, it compares the TSI value against a dynamically determined high/low range from the past 100 bars to confirm trade signals.
🔸 Leverage & Risk Optimization – Position sizing is dynamically adjusted based on account equity and leverage settings, ensuring controlled risk exposure.
🔸 Performance Monitoring System – A built-in performance tracking table allows traders to evaluate monthly and yearly results directly on the chart.
📊 Core Strategy Components
1️⃣ Momentum-Based Trade Execution
The strategy generates long and short trade signals based on the following conditions:
✅ Long Entry Condition – A buy signal is triggered when the TSI crosses above its 100-bar highest value (previously set), confirming bullish momentum.
✅ Short Entry Condition – A sell signal is generated when the TSI crosses below its 100-bar lowest value (previously set), indicating bearish pressure.
Each trade execution is fully automated, reducing emotional decision-making and improving trading discipline.
2️⃣ Position Sizing & Leverage Control
Risk management is a key focus of this strategy:
🔹 Dynamic Position Sizing – The script calculates position size based on:
Account Equity – Ensuring trade sizes adjust dynamically with capital fluctuations.
Leverage Multiplier – Allows traders to customize risk exposure via an adjustable leverage setting.
🔹 No Fixed Stop-Loss – The strategy relies on reversals to exit trades, meaning each position is closed when the opposite signal appears.
This design ensures maximum capital efficiency while adapting to market conditions in real time.
3️⃣ Performance Visualization & Tracking
Understanding historical performance is crucial for refining strategies. The script includes:
📌 Real-Time Trade Markers – Buy and sell signals are visually displayed on the chart for easy reference.
📌 Performance Metrics Table – Tracks monthly and yearly returns in percentage form, helping traders assess profitability over time.
📌 Trade History Visualization – Completed trades are displayed with color-coded boxes (green for long trades, red for short trades), visually representing profit/loss dynamics.
📢 Why Use This Strategy?
✔ Advanced Momentum Detection – Uses a double-smoothed TSI for more accurate trend signals.
✔ Fully Automated Trading – Removes emotional bias and enforces discipline.
✔ Customizable Risk Management – Adjust leverage and position sizing to suit your risk profile.
✔ Comprehensive Performance Tracking – Integrated reporting system provides clear insights into past trades.
This strategy is ideal for Bitcoin traders looking for a structured, high-probability system that adapts to both bullish and bearish trends on the 2-hour timeframe.
📌 How to Use: Simply add the script to your 2H BTC chart, configure your leverage settings, and let the system handle trade execution and tracking! 🚀
Blockchain Fundamentals: Liquidity & BTC YoYLiquidity & BTC YoY Indicator
Overview:
This indicator calculates the Year-over-Year (YoY) percentage change for two critical metrics: a custom Liquidity Index and Bitcoin's price. The Liquidity Index is derived from a blend of economic and forex data representing the M2 money supply, while the BTC price is obtained from a reliable market source. A dedicated limit(length) function is implemented to handle limited historical data, ensuring that the YoY calculations are available immediately—even when the chart's history is short.
Features Breakdown:
1. Limited Historical Data Workaround
- Functionality: limit(length) The function dynamically adjusts the lookback period when there isn’t enough historical data. This prevents delays in displaying YoY metrics at the beginning of the chart.
2. Liquidity Calculation
- Data Sources: Combines multiple data streams:
USM2, ECONOMICS:CNM2, USDCNY, ECONOMICS:JPM2, USDJPY, ECONOMICS:EUM2, USDEUR
- Formula:
Liquidity Index = USM2 + (CNM2 / USDCNY) + (JPM2 / USDJPY) + (EUM2 / USDEUR)
[b3. Bitcoin Price Calculation
- Data Source: Retrieves Bitcoin's price from BITSTAMP:BTCUSD on the user-selected timeframe for its historical length.
4. Year-over-Year (YoY) Percent Change Calculation
- Methodology:
- The indicator uses a custom function, to autodetect the proper number of bars, based on the selected timeframe.
- It then compares the current value to that from one year ago for both the Liquidity Index and BTC price, calculating the YoY percentage change.
5. Visual Presentation
- Plotting:
- The YoY percentage changes for Liquidity (plotted in blue) and BTC price (plotted in orange) are clearly displayed.
- A horizontal zero line is added for visual alignment, making it easier to compare the two copies of the metric. You add one copy and only display the BTC YoY. Then you add another copy and only display the M2 YoY.
-The zero lines are then used to align the scripts to each other by interposing them. You scale each chart the way you like, then move each copy individually to align both zero lines on top of each other.
This indicator is ideal for analysts and investors looking to monitor macroeconomic liquidity trends alongside Bitcoin's performance, providing immediate insights.
Ultimate Volatility Scanner by NHBprod - Requested by Client!Hey Everyone!
I created another script to add to my growing library of strategies and indicators that I use for automated crypto and stock trading! This strategy is for BITCOIN but can be used on any stock or crypto. This was requested by a client so I thought I should create it and hopefully build off of it and build variants!
This script gets and compares the 14-day volatility using the ATR percentage for a list of cryptocurrencies and stocks. Cryptocurrencies are preloaded into the script, and the script will show you the TOP 5 coins in terms of volatility, and then compares it to the Bitcoin volatility as a reference. It updates these values once per day using daily timeframe data from TradingView. The coins are then sorted in descending order by their volatility.
If you don't want to use the preloaded set of coins, you have the option of inputting your own coins AND/OR stocks!
Let me know your thoughts.
Ultimate T3 Fibonacci for BTC Scalping. Look at backtest report!Hey Everyone!
I created another script to add to my growing library of strategies and indicators that I use for automated crypto trading! This strategy is for BITCOIN on the 30 minute chart since I designed it to be a scalping strategy. I calculated for trading fees, and use a small amount of capital in the backtest report. But feel free to modify the capital and how much per order to see how it changes the results:)
It is called the "Ultimate T3 Fibonacci Indicator by NHBprod" that computes and displays two T3-based moving averages derived from price data. The t3_function calculates the Tilson T3 indicator by applying a series of exponential moving averages to a combined price metric and then blending these results with specific coefficients derived from an input factor.
The script accepts several user inputs that toggle the use of the T3 filter, select the buy signal method, and set parameters like lengths and volume factors for two variations of the T3 calculation. Two T3 lines, T3 and T32, are computed with different parameters, and their colors change dynamically (green/red for T3 and blue/purple for T32) based on whether the lines are trending upward or downward. Depending on the selected signal method, the script generates buy signals either when T32 crosses over T3 or when the closing price is above T3, and similarly, sell signals are generated on the respective conditions for crossing under or closing below. Finally, the indicator plots the T3 lines on the chart, adds visual buy/sell markers, and sets alert conditions to notify users when the respective trading signals occur.
The user has the ability to tune the parameters using TP/SL, date timerames for analyses, and the actual parameters of the T3 function including the buy/sell signal! Lastly, the user has the option of trading this long, short, or both!
Let me know your thoughts and check out the backtest report!
WAGMI LAB Trend Reversal Indicator HMA-Kahlman (m15)WAGMI HMA-Kahlman Trend Reversal Indicator
This indicator combines the Hull Moving Average (HMA) with the Kahlman filter to provide a dynamic trend reversal signal, perfect for volatile assets like Bitcoin. The strategy works particularly well on lower timeframes, making it ideal for intraday trading and fast-moving markets.
Key Features:
Trend Detection: It uses a blend of HMA and Kahlman filters to detect trend reversals, providing more accurate and timely signals.
Volatility Adaptability: Designed with volatile assets like Bitcoin in mind, this indicator adapts to rapid price movements, offering smoother trend detection during high volatility.
Easy Visualization: Buy (B) and Sell (S) signals are clearly marked with labels, helping traders spot trend shifts quickly and accurately.
Trendlines Module: The indicator plots trendlines based on pivot points, highlighting important support and resistance levels. This helps traders understand the market structure and identify potential breakout or breakdown zones.
Customizable: Adjust the HMA and Kahlman parameters to fit different assets or trading styles, making it flexible for various market conditions.
Usage Tips:
Best Timeframes: The indicator performs exceptionally well on lower timeframes (such as 15-minute to 1-hour charts), making it ideal for scalping and short-term trading strategies.
Ideal for Volatile Assets: This strategy is perfect for highly volatile assets like Bitcoin, but can also be applied to other cryptocurrencies and traditional markets with high price fluctuations.
Signal Confirmation: Use the trend signals (green for uptrend, red for downtrend) along with the buy/sell labels to help you confirm potential entries and exits. It's also recommended to combine the signals with other technical tools like volume analysis or RSI for enhanced confirmation.
Trendline Analysis: The plotted trendlines provide additional visual context to identify key market zones, supporting your trading decisions with a clear view of ongoing trends and possible reversal areas.
Risk Management: As with any strategy, always consider proper risk management techniques, such as stop-loss and take-profit levels, to protect against unforeseen market moves.
Wagmi Lab- Bitcoin H4 Buy Sell Signals This indicator, designed primarily for Bitcoin on the H4 timeframe, is a versatile tool that can also be applied to other assets and timeframes by adjusting its parameters. It combines Exponential Moving Averages (EMAs), MACD (Moving Average Convergence Divergence), and a crossover filtering mechanism to generate reliable buy and sell signals. The indicator is ideal for traders looking to identify trend direction and potential entry/exit points with added precision.
Key Features:
Customizable EMAs and MACD:
Fast EMA (default: 12): Tracks short-term price momentum.
Slow EMA (default: 26): Tracks long-term price momentum.
Signal SMA (default: 9): Smooths the MACD line to generate the signal line.
MACD Crossover Signals:
The indicator calculates the MACD line and signal line to identify potential buy and sell opportunities.
Buy signals are generated when the MACD line crosses above the signal line, indicating bullish momentum.
Sell signals are generated when the MACD line crosses below the signal line, indicating bearish momentum.
Crossover Strength Filter:
A minimum crossover distance percentage (default: 0.1%) ensures that only significant crossovers are considered, reducing false signals.
This filter helps traders avoid weak or insignificant crossovers that may not lead to strong price movements.
Trend Visualization:
The indicator highlights the trend direction by filling the area between the fast and slow EMAs with colors:
Green: Uptrend (MACD > Signal Line).
Red: Downtrend (MACD < Signal Line).
Buy/Sell Signal Markers:
Buy signals are marked with green circles below the price bars.
Sell signals are marked with red circles above the price bars.
These markers provide clear visual cues for potential entry and exit points.
Adaptable to Other Timeframes and Assets:
While optimized for the H4 timeframe, the indicator can be adjusted for other timeframes (e.g., M15, H1, D1) by modifying the EMA and SMA settings.
It can also be applied to other assets, such as stocks, forex, or commodities, by tweaking the parameters to suit the asset's volatility and characteristics.
How to Use:
Identify Trends:
Use the colored areas (green for uptrend, red for downtrend) to determine the overall market direction.
Wait for Confirmation:
Look for buy or sell signals (green or red circles) that align with the trend direction.
Ensure the crossover meets the minimum distance requirement to filter out weak signals.
Enter and Exit Trades:
Enter a long position when a buy signal appears during an uptrend.
Enter a short position or exit a long position when a sell signal appears during a downtrend.
Adjust Settings for Other Timeframes/Assets:
Experiment with the EMA and SMA periods to optimize the indicator for different timeframes or assets.
Why Use This Indicator?
Precision: The crossover strength filter reduces noise and false signals.
Versatility: Works across multiple timeframes and assets with customizable settings.
Visual Clarity: Clear trend visualization and signal markers make it easy to interpret.
This indicator is a powerful tool for traders seeking to capitalize on Bitcoin's volatility or other assets' price movements, providing a structured approach to identifying trends and potential trading opportunities.
Ultimate Stochastics Strategy by NHBprod Use to Day Trade BTCHey All!
Here's a new script I worked on that's super simple but at the same time useful. Check out the backtest results. The backtest results include slippage and fees/commission, and is still quite profitable. Obviously the profitability magnitude depends on how much capital you begin with, and how much the user utilizes per order, but in any event it seems to be profitable according to backtests.
This is different because it allows you full functionality over the stochastics calculations which is designed for random datasets. This script allows you to:
Designate ANY period of time to analyze and study
Choose between Long trading, short trading, and Long & Short trading
It allows you to enter trades based on the stochastics calculations
It allows you to EXIT trades using the stochastics calculations or take profit, or stop loss, Or any combination of those, which is nice because then the user can see how one variable effects the overall performance.
As for the actual stochastics formula, you get control, and get to SEE the plot lines for slow K, slow D, and fast K, which is usually not considered.
You also get the chance to modify the smoothing method, which has not been done with regular stochastics indicators. You get to choose the standard simple moving average (SMA) method, but I also allow you to choose other MA's such as the HMA and WMA.
Lastly, the user gets the option of using a custom trade extender, which essentially allows a buy or sell signal to exist for X amount of candles after the initial signal. For example, you can use "max bars since signal" to 1, and this will allow the indicator to produce an extra sequential buy signal when a buy signal is generated. This can be useful because it is possible that you use a small take profit (TP) and quickly exit a profitable trade. With the max bars since signal variable, you're able to reenter on the next candle and allow for another opportunity.
Let me know if you have any questions! Please take a look at the performance report and let me know your thoughts! :)
Mxwll Hedge Suite [Mxwll]Hello Traders!
The Mxwll Hedge Suite determines the best asset to hedge against the asset on your chart!
By determining correlation between the asset on your chart and a group of internally listed assets, the Mxwll Hedge Suite determines which asset from the list exhibits the highest negative correlation, and then determines exactly how many coins/shares/contracts of the asset must be bought to achieve a perfect 1:1 hedge!
The image above exemplifies the process!
The purple box on the chart shows the eligible price action used to determine correlation between the asset on my chart (BTCUSDT.P) and the list of cryptocurrencies that can be used as a hedge!
From this price action, the coin determined to have to greatest negative correlation to BTCUSDT.P is FTMUSD.
The image above further outlines the hedge table located in the bottom-right corner of your chart!
The hedge table shows exactly how many coins you’d need to purchase for the hedge asset at various leverages to achieve a perfect 1:1 hedge!
Hedge Suite works on any asset on any timeframe!
And that’s all! A short and sweet script that is hopefully helpful to traders looking to hedge their positions with a negatively correlated asset!
Thank you, Traders!
[ADDYad] Google Search Trends - Bitcoin (2012 Jan - 2025 Jan)This Pine Script shows the Google Search Trends as an indicator for Bitcoin from January 2012 to January 2025, based on monthly data retrieved from Google Trends. It calculates and displays the relative search interest for Bitcoin over time, offering a historical perspective on its popularity mainly built for BITSTAMP:BTCUSD .
Important note: This is not a live indicator. It visualizes historical search trends based on Google Trends data.
Key Features:
Data Source : Google Trends (Last retrieved in January 10 2025).
Timeframe : The script is designed to be used on a monthly chart, with the data reflecting monthly search trends from January 2012 to January 2025. For other timeframes, the data is linearly interpolated to estimate the trends at finer resolutions.
Purpose : This indicator helps visualize Bitcoin's search interest over the years, offering insights into public interest and sentiment during specific periods (e.g., major price movements or news events).
Data Handling : The data is interpolated for use on non-monthly timeframes, allowing you to view search trends on any chart timeframe. This makes it versatile for use in longer-term analysis or shorter timeframes, despite the raw data being available only on a monthly basis. However, it is most relevant for Monthly, Weekly, and Daily timeframes.
How It Works:
The script calculates the number of months elapsed since January 1, 2012, and uses this to interpolate Google Trends data values for any given point in time on the chart.
The linear interpolation function adjusts the monthly data to provide an approximate trend for intermediate months.
Why It's Useful:
Track Bitcoin's historic search trends to understand how interest in Bitcoin evolved over time, potentially correlating with price movements.
Correlate search trends with price action and other market indicators to analyze the effects of public sentiment and sentiment-driven market momentum.
Final Notes:
This script is unique because it shows real-world, non-financial dataset (Google Trends) to understand price action of Bitcoin correlating with public interest. Hopefully is a valuable addition to the TradingView community.
ADDYad
4-Year Cycles [jpkxyz]Overview of the Script
I wanted to write a script that encompasses the wide-spread macro fund manager investment thesis: "Crypto is simply and expression of macro." A thesis pioneered by the likes of Raoul Pal (EXPAAM) , Andreesen Horowitz (A16Z) , Joe McCann (ASYMETRIC) , Bob Loukas and many more.
Cycle Theory Background:
The 2007-2008 financial crisis transformed central bank monetary policy by introducing:
- Quantitative Easing (QE): Creating money to buy assets and inject liquidity
- Coordinated global monetary interventions
Proactive 4-year economic cycles characterised by:
- Expansionary periods (low rates, money creation)
- Followed by contraction/normalisation
Central banks now deliberately manipulate liquidity, interest rates, and asset prices to control economic cycles, using monetary policy as a precision tool rather than a blunt instrument.
Cycle Characteristics (based on historical cycles):
- A cycle has 4 seasons (Spring, Summer, Fall, Winter)
- Each season with a cycle lasts 365 days
- The Cycle Low happens towards the beginning of the Spring Season of each new cycle
- This is followed by a run up throughout the Spring and Summer Season
- The Cycle High happens towards the end of the Fall Season
- The Winter season is characterised by price corrections until establishing a new floor in the Spring of the next cycle
Key Functionalities
1. Cycle Tracking
- Divides market history into 4-year cycles (Spring, Summer, Fall, Winter)
- Starts tracking cycles from 2011 (first cycle after the 2007 crisis cycle)
- Identifies and marks cycle boundaries
2. Visualization
- Colors background based on current cycle season
- Draws lines connecting:
- Cycle highs and lows
- Inter-cycle price movements
- Adds labels showing:
- Percentage gains/losses between cycles
- Number of days between significant points
3. Customization Options
- Allows users to customize:
- Colors for each season
- Line and label colors
- Label size
- Background opacity
Detailed Mechanism
Cycle Identification
- Uses a modulo calculation to determine the current season in the 4-year cycle
- Preset boundary years include 2015, 2019, 2023, 2027
- Automatically tracks and marks cycle transitions
Price Analysis
- Tracks highest and lowest prices within each cycle
- Calculates percentage changes:
- Intra-cycle (low to high)
- Inter-cycle (previous high to current high/low)
Visualization Techniques
- Background color changes based on current cycle season
- Dashed and solid lines connect significant price points
- Labels provide quantitative insights about price movements
Unique Aspects
1. Predictive Cycle Framework: Provides a structured way to view market movements beyond traditional technical analysis
2. Seasonal Color Coding: Intuitive visual representation of market cycle stages
3. Comprehensive Price Tracking: Captures both intra-cycle and inter-cycle price dynamics
4. Highly Customizable: Users can adjust visual parameters to suit their preferences
Potential Use Cases
- Technical analysis for long-term investors
- Identifying market cycle patterns
- Understanding historical price movement rhythms
- Educational tool for market cycle theory
Limitations/Considerations
- Based on a predefined 4-year cycle model (Liquidity Cycles)
- Historic Cycle Structures are not an indication for future performance
- May not perfectly represent all market behavior
- Requires visual interpretation
This script is particularly interesting for investors who believe in cyclical market theories and want a visual, data-driven representation of market stages.
Log Regression OscillatorThe Log Regression Oscillator transforms the logarithmic regression curves into an easy-to-interpret oscillator that displays potential cycle tops/bottoms.
🔶 USAGE
Calculating the logarithmic regression of long-term swings can help show future tops/bottoms. The relationship between previous swing points is calculated and projected further. The calculated levels are directly associated with swing points, which means every swing point will change the calculation. Importantly, all levels will be updated through all bars when a new swing is detected.
The "Log Regression Oscillator" transforms the calculated levels, where the top level is regarded as 100 and the bottom level as 0. The price values are displayed in between and calculated as a ratio between the top and bottom, resulting in a clear view of where the price is situated.
The main picture contains the Logarithmic Regression Alternative on the chart to compare with this published script.
Included are the levels 30 and 70. In the example of Bitcoin, previous cycles showed a similar pattern: the bullish parabolic was halfway when the oscillator passed the 30-level, and the top was very near when passing the 70-level.
🔹 Proactive
A "Proactive" option is included, which ensures immediate calculations of tentative unconfirmed swings.
Instead of waiting 300 bars for confirmation, the "Proactive" mode will display a gray-white dot (not confirmed swing) and add the unconfirmed Swing value to the calculation.
The above example shows that the "Calculated Values" of the potential future top and bottom are adjusted, including the provisional swing.
When the swing is confirmed, the calculations are again adjusted, showing a red dot (confirmed top swing) or a green dot (confirmed bottom swing).
🔹 Dashboard
When less than two swings are available (top/bottom), this will be shown in the dashboard.
The user can lower the "Threshold" value or switch to a lower timeframe.
🔹 Notes
Logarithmic regression is typically used to model situations where growth or decay accelerates rapidly at first and then slows over time, meaning some symbols/tickers will fit better than others.
Since the logarithmic regression depends on swing values, each new value will change the calculation. A well-fitted model could not fit anymore in the future.
Users have to check the validity of swings; for example, if the direction of swings is downwards, then the dataset is not fitted for logarithmic regression.
In the example above, the "Threshold" is lowered. However, the calculated levels are unreliable due to the swings, which do not fit the model well.
Here, the combination of downward bottom swings and price accelerates slower at first and faster recently, resulting in a non-fit for the logarithmic regression model.
Note the price value (white line) is bound to a limit of 150 (upwards) and -150 (down)
In short, logarithmic regression is best used when there are enough tops/bottoms, and all tops are around 100, and all bottoms around 0.
Also, note that this indicator has been developed for a daily (or higher) timeframe chart.
🔶 DETAILS
In mathematics, the dot product or scalar product is an algebraic operation that takes two equal-length sequences of numbers (arrays) and returns a single number, the sum of the products of the corresponding entries of the two sequences of numbers.
The usual way is to loop through both arrays and sum the products.
In this case, the two arrays are transformed into a matrix, wherein in one matrix, a single column is filled with the first array values, and in the second matrix, a single row is filled with the second array values.
After this, the function matrix.mult() returns a new matrix resulting from the product between the matrices m1 and m2.
Then, the matrix.eigenvalues() function transforms this matrix into an array, where the array.sum() function finally returns the sum of the array's elements, which is the dot product.
dot(x, y)=>
if x.size() > 1 and y.size() > 1
m1 = matrix.new()
m2 = matrix.new()
m1.add_col(m1.columns(), y)
m2.add_row(m2.rows (), x)
m1.mult (m2)
.eigenvalues()
.sum()
🔶 SETTINGS
Threshold: Period used for the swing detection, with higher values returning longer-term Swing Levels.
Proactive: Tentative Swings are included with this setting enabled.
Style: Color Settings
Dashboard: Toggle, "Location" and "Text Size"
Murad Picks Target MCThe Murad Picks Target Market Cap Indicator is a custom TradingView tool designed for crypto traders and enthusiasts tracking tokens in the Murad Picks list. This indicator dynamically calculates and visualizes the price targets based on Murad Mahmudov's projected market capitalizations, allowing you to gauge each token's growth potential directly on your charts.
Indicator support tokens:
- SPX6900
- GIGA
- MOG
- POPCAT
- APU
- BITCOIN
- RETARDIO
- LOCKIN
Key Features :
Dynamic Target Price Lines:
- Displays horizontal lines representing the price when the token reaches its projected market cap.
- Automatically adjusts for the active chart symbol (e.g., SPX, MOG, APU, etc.).
X Multiplier Calculation:
- Shows how many times the current price must multiply to achieve the target price.
- Perfect for understanding relative growth potential.
Customizable Inputs:
- Easily update target market caps and circulating supply for each token.
- Adjust visuals such as line colors and styles.
Seamless Integration:
- Automatically adapts to the token you’re viewing (e.g., SPX, MOG, APU).
- Clean and visually intuitive, with labels marking targets.
Logarithmic Regression AlternativeLogarithmic regression is typically used to model situations where growth or decay accelerates rapidly at first and then slows over time. Bitcoin is a good example.
𝑦 = 𝑎 + 𝑏 * ln(𝑥)
With this logarithmic regression (log reg) formula 𝑦 (price) is calculated with constants 𝑎 and 𝑏, where 𝑥 is the bar_index .
Instead of using the sum of log x/y values, together with the dot product of log x/y and the sum of the square of log x-values, to calculate a and b, I wanted to see if it was possible to calculate a and b differently.
In this script, the log reg is calculated with several different assumed a & b values, after which the log reg level is compared to each Swing. The log reg, where all swings on average are closest to the level, produces the final 𝑎 & 𝑏 values used to display the levels.
🔶 USAGE
The script shows the calculated logarithmic regression value from historical swings, provided there are enough swings, the price pattern fits the log reg model, and previous swings are close to the calculated Top/Bottom levels.
When the price approaches one of the calculated Top or Bottom levels, these levels could act as potential cycle Top or Bottom.
Since the logarithmic regression depends on swing values, each new value will change the calculation. A well-fitted model could not fit anymore in the future.
Swings are based on Weekly bars. A Top Swing, for example, with Swing setting 30, is the highest value in 60 weeks. Thirty bars at the left and right of the Swing will be lower than the Top Swing. This means that a confirmation is triggered 30 weeks after the Swing. The period will be automatically multiplied by 7 on the daily chart, where 30 becomes 210 bars.
Please note that the goal of this script is not to show swings rapidly; it is meant to show the potential next cycle's Top/Bottom levels.
🔹 Multiple Levels
The script includes the option to display 3 Top/Bottom levels, which uses different values for the swing calculations.
Top: 'high', 'maximum open/close' or 'close'
Bottom: 'low', 'minimum open/close' or 'close'
These levels can be adjusted up/down with a percentage.
Lastly, an "Average" is included for each set, which will only be visible when "AVG" is enabled, together with both Top and Bottom levels.
🔹 Notes
Users have to check the validity of swings; the above example only uses 1 Top Swing for its calculations, making the Top level unreliable.
Here, 1 of the Bottom Swings is pretty far from the bottom level, changing the swing settings can give a more reliable bottom level where all swings are close to that level.
Note the display was set at "Logarithmic", it can just as well be shown as "Regular"
In the example below, the price evolution does not fit the logarithmic regression model, where growth should accelerate rapidly at first and then slows over time.
Please note that this script can only be used on a daily timeframe or higher; using it at a lower timeframe will show a warning. Also, it doesn't work with bar-replay.
🔶 DETAILS
The code gathers data from historical swings. At the last bar, all swings are calculated with different a and b values. The a and b values which results in the smallest difference between all swings and Top/Bottom levels become the final a and b values.
The ranges of a and b are between -20.000 to +20.000, which means a and b will have the values -20.000, -19.999, -19.998, -19.997, -19.996, ... -> +20.000.
As you can imagine, the number of calculations is enormous. Therefore, the calculation is split into parts, first very roughly and then very fine.
The first calculations are done between -20 and +20 (-20, -19, -18, ...), resulting in, for example, 4.
The next set of calculations is performed only around the previous result, in this case between 3 (4-1) and 5 (4+1), resulting in, for example, 3.9. The next set goes even more in detail, for example, between 3.8 (3.9-0.1) and 4.0 (3.9 + 0.1), and so on.
1) -20 -> +20 , then loop with step 1 (result (example): 4 )
2) 4 - 1 -> 4 +1 , then loop with step 0.1 (result (example): 3.9 )
3) 3.9 - 0.1 -> 3.9 +0.1 , then loop with step 0.01 (result (example): 3.93 )
4) 3.93 - 0.01 -> 3.93 +0.01, then loop with step 0.001 (result (example): 3.928)
This ensures complicated calculations with less effort.
These calculations are done at the last bar, where the levels are displayed, which means you can see different results when a new swing is found.
Also, note that this indicator has been developed for a daily (or higher) timeframe chart.
🔶 SETTINGS
Three sets
High/Low
• color setting
• Swing Length settings for 'High' & 'Low'
• % adjustment for 'High' & 'Low'
• AVG: shows average (when both 'High' and 'Low' are enabled)
Max/Min (maximum open/close, minimum open/close)
• color setting
• Swing Length settings for 'Max' & 'Min'
• % adjustment for 'Max' & 'Min'
• AVG: shows average (when both 'Max' and 'Min' are enabled)
Close H/Close L (close Top/Bottom level)
• color setting
• Swing Length settings for 'Close H' & 'Close L'
• % adjustment for 'Close H' & 'Close L'
• AVG: shows average (when both 'Close H' and 'Close L' are enabled)
Show Dashboard, including Top/Bottom levels of the desired source and calculated a and b values.
Show Swings + Dot size