Machine Learning RSI [BackQuant]Machine Learning RSI
The Machine Learning RSI is a cutting-edge trading indicator that combines the power of Relative Strength Index (RSI) with Machine Learning (ML) clustering techniques to dynamically determine overbought and oversold thresholds. This advanced indicator adapts to market conditions in real-time, offering traders a robust tool for identifying optimal entry and exit points with increased precision.
Core Concept: Relative Strength Index (RSI)
The RSI is a well-known momentum oscillator that measures the speed and change of price movements, oscillating between 0 and 100. Typically, RSI values above 70 are considered overbought, and values below 30 are considered oversold. However, static thresholds may not be effective in all market conditions.
This script enhances the RSI by integrating a dynamic thresholding system powered by Machine Learning clustering, allowing it to adapt thresholds based on historical RSI behavior and market context.
Machine Learning Clustering for Dynamic Thresholds
The Machine Learning (ML) component uses clustering to calculate dynamic thresholds for overbought and oversold levels. Instead of relying on fixed RSI levels, this indicator clusters historical RSI values into three groups using a percentile-based initialization and iterative optimization:
Cluster 1: Represents lower RSI values (typically associated with oversold conditions).
Cluster 2: Represents mid-range RSI values.
Cluster 3: Represents higher RSI values (typically associated with overbought conditions).
Dynamic thresholds are determined as follows:
Long Threshold: The upper centroid value of Cluster 3.
Short Threshold: The lower centroid value of Cluster 1.
This approach ensures that the indicator adapts to the current market regime, providing more accurate signals in volatile or trending conditions.
Smoothing Options for RSI
To further enhance the effectiveness of the RSI, this script allows traders to apply various smoothing methods to the RSI calculation, including:
Simple Moving Average (SMA)
Exponential Moving Average (EMA)
Weighted Moving Average (WMA)
Hull Moving Average (HMA)
Linear Regression (LINREG)
Double Exponential Moving Average (DEMA)
Triple Exponential Moving Average (TEMA)
Adaptive Linear Moving Average (ALMA)
T3 Moving Average
Traders can select their preferred smoothing method and adjust the smoothing period to suit their trading style and market conditions. The option to smooth the RSI reduces noise and makes the indicator more reliable for detecting trends and reversals.
Long and Short Signals
The indicator generates long and short signals based on the relationship between the RSI value and the dynamic thresholds:
Long Signals: Triggered when the RSI crosses above the long threshold, signaling bullish momentum.
Short Signals: Triggered when the RSI falls below the short threshold, signaling bearish momentum.
These signals are dynamically adjusted to reflect real-time market conditions, making them more robust than static RSI signals.
Visualization and Clustering Insights
The Machine Learning RSI provides an intuitive and visually rich interface, including:
RSI Line: Plotted in real-time, color-coded based on its position relative to the dynamic thresholds (green for long, red for short, gray for neutral).
Dynamic Threshold Lines: The script plots the long and short thresholds calculated by the ML clustering process, providing a clear visual reference for overbought and oversold levels.
Cluster Plots: Each RSI cluster is displayed with distinct colors (green, orange, and red) to give traders insights into how RSI values are grouped and how the dynamic thresholds are derived.
Customization Options
The Machine Learning RSI is highly customizable, allowing traders to tailor the indicator to their preferences:
RSI Settings : Adjust the RSI length, source price, and smoothing method to match your trading strategy.
Threshold Settings : Define the range and step size for clustering thresholds, allowing you to fine-tune the clustering process.
Optimization Settings : Control the performance memory, maximum clustering steps, and maximum data points for ML calculations to ensure optimal performance.
UI Settings : Customize the appearance of the RSI plot, dynamic thresholds, and cluster plots. Traders can also enable or disable candle coloring based on trend direction.
Alerts and Automation
To assist traders in staying on top of market movements, the script includes alert conditions for key events:
Long Signal: When the RSI crosses above the long threshold.
Short Signal: When the RSI crosses below the short threshold.
These alerts can be configured to notify traders in real-time, enabling timely decisions without constant chart monitoring.
Trading Applications
The Machine Learning RSI is versatile and can be applied to various trading strategies, including:
Trend Following: By dynamically adjusting thresholds, this indicator is effective in identifying and following trends in real-time.
Reversal Trading: The ML clustering process helps identify extreme RSI levels, offering reliable signals for reversals.
Range-Bound Trading: The dynamic thresholds adapt to market conditions, making the indicator suitable for trading in sideways markets where static thresholds often fail.
Final Thoughts
The Machine Learning RSI represents a significant advancement in RSI-based trading indicators. By integrating Machine Learning clustering techniques, this script overcomes the limitations of static thresholds, providing dynamic, adaptive signals that respond to market conditions in real-time. With its robust visualization, customizable settings, and alert capabilities, this indicator is a powerful tool for traders seeking to enhance their momentum analysis and improve decision-making.
As always, thorough backtesting and integration into a broader trading strategy are recommended to maximize the effectiveness!

# Statistics

Position Size Calculator by Dr. Rahul Ware.Position Size Calculator
The Position Size Calculator script helps traders determine the optimal position size for their trades based on their account balance, risk percentage, and stop loss parameters. It calculates the number of shares to buy and the total position size in INR (Indian Rupees), providing a clear and concise way to manage risk effectively.
Key Features:
Account Balance Input: Specify your account balance in INR to tailor the position size calculations to your specific trading capital.
Risk Percentage Input: Define the percentage of your account balance you are willing to risk on each trade, ensuring you stay within your risk tolerance.
Stop Loss Options: Choose between using a fixed stop loss price or a stop loss percentage to calculate the risk amount per share.
Dynamic Stop Loss Line: The script plots a red dotted line representing the stop loss price on the chart, updating dynamically for the last bar.
Comprehensive Table Display: View key metrics, including account balance, risk percentage, amount at risk, current price, stop loss price, stop loss percentage, position size in INR, and the number of shares to buy, all in a neatly formatted table.
This tool is designed to enhance your trading strategy by providing precise position sizing, helping you manage risk effectively and make informed trading decisions. Use this script to optimize your trade sizes and improve your overall trading performance.

Gold Miners %R StrategyThis "Gold Miners Williams %R Strategy" leverages the Williams %R indicator to identify potential overbought and oversold conditions in assets, specifically the GDX (VanEck Vectors Gold Miners ETF) or any user-defined asset, by analyzing price momentum. The Williams %R, or Williams Percent Range, was developed by trader and author Larry Williams to identify entry and exit points based on relative price position within a given range (typically 14 or 90 periods). This indicator provides insights into whether an asset is trading near its highs or lows for a specified period, making it useful for mean-reversion trading strategies (Williams, 1979).
Indicator Mechanism
Williams %R oscillates between -100 (oversold) and 0 (overbought), with standard threshold levels set at -20 (overbought) and -80 (oversold) (Colby, 2002). However, this strategy allows users to adjust these thresholds, offering flexibility based on specific market conditions or asset behavior. When the indicator crosses the lower threshold, the asset is considered oversold, potentially signaling a buying opportunity. Conversely, crossing the upper threshold signals overbought conditions and can trigger a sell or short position.
Strategy Parameters
This strategy includes customizable parameters to adapt the Williams %R calculation length, upper and lower thresholds, and an optional reversal logic. If reversal logic is enabled, it inverts the typical interpretation, positioning short on oversold and long on overbought signals. This flexibility can optimize strategy performance across varying market conditions, including bullish and bearish trends, and periods of high or low volatility (Lento & Gradojevic, 2009).
Theoretical Foundations
The Williams %R indicator is rooted in the concept of mean reversion—the hypothesis that asset prices will eventually revert to their long-term mean or average value. Numerous studies have validated the predictive potential of mean-reversion indicators in financial markets, especially in assets like commodities, which are often subject to cyclical price movements (Poterba & Summers, 1988). Additionally, research has shown that overbought and oversold conditions tend to produce high probability trade setups in volatile markets, where short-term extremes in price are often corrected (Jegadeesh & Titman, 1993).
Strategy Implementation
The following implementation allows traders to apply the Williams %R indicator as a decision-making tool for initiating buy or sell trades based on observed extreme price conditions. The strategy’s configurable reversal logic supports adaptive responses to changing market dynamics, enhancing robustness across multiple asset types and market conditions (Lo, Mamaysky, & Wang, 2000).
References
Colby, R. W. (2002). The Encyclopedia of Technical Market Indicators. McGraw-Hill.
Jegadeesh, N., & Titman, S. (1993). Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency. The Journal of Finance, 48(1), 65-91.
Lento, C., & Gradojevic, N. (2009). The profitability of technical trading rules: A combined signal approach. Journal of Applied Business Research (JABR), 25(1), 1-12.
Lo, A. W., Mamaysky, H., & Wang, J. (2000). Foundations of Technical Analysis: Computational Algorithms, Statistical Inference, and Empirical Implementation. The Journal of Finance, 55(4), 1705-1765.
Poterba, J. M., & Summers, L. H. (1988). Mean Reversion in Stock Prices: Evidence and Implications. Journal of Financial Economics, 22(1), 27-59.
Williams, L. (1979). How I Made One Million Dollars Last Year Trading Commodities. Doubleday.

Z Value AlertZ Value Alert analyzes daily price movements by evaluating fluctuations relative to historical volatility. It calculates the daily percentage change in the closing price, the average of this change over 252 days, and the standard deviation. Using these values, a Z-Score is calculated, indicating how much the current price change deviates from the historical range of fluctuations.
The user can set a threshold in standard deviations (Z-Score). When the absolute Z-Score exceeds this threshold, a significant movement is detected, indicating increased volatility. The Z-Score is visualized as a histogram, and an alert can be triggered when a significant movement occurs.
The number of trading days used to calculate historical volatility is adjustable, allowing the Sigma Move Alert to be tailored to various trading strategies and analysis periods.
Additionally, a dropdown option for the calculation method is available in the input menu, allowing the user to select between:
Normal: Calculates the percentage change in closing prices without using the logarithm.
Logarithmic: Uses the natural logarithm of daily returns. This method is particularly suitable for longer timeframes and scientific analyses, as logarithmic returns are additive.
These comprehensive features allow for precise customization of the Sigma Move Alert to individual needs and specific market conditions.

BarRange StrategyHello,
This is a long-only, volatility-based strategy that analyzes the range of the previous bar (high - low).
If the most recent bar’s range exceeds a threshold based on the last X bars, a trade is initiated.
You can customize the lookback period, threshold value, and exit type.
For exits, you can choose to exit after X bars or when the close price exceeds the previous bar’s high.
The strategy is designed for instruments with a long-term upward-sloping curves, such as ES1! or NQ1!. It may not perform well on other instruments.
Commissions are set to $2.50 per side ($5.00 per round trip).
Recommended timeframes are 1h and higher. With adjustments to the lookback period and threshold, it could potentially achieve similar results on lower timeframes as well.

lib_momentumLibrary "lib_momentum"
This library calculates the momentum, derived from a sample range of prior candles. Depending on set MomentumType it either deduces the momentum from the price, volume, or a product of both. If price/product are selected, you can choose from SampleType if only candle body, full range from high to low or a combination of both (body counts full, wicks half for each direction) should be used. Optional: You can choose to normalize the results, dividing each value by its average (normalization_ma_length, normalization_ma). This will allow comparison between different instruments. For the normalization Moving Average you can choose any currently supported in my lib_no_delay.
get_momentum(momentum_type, sample_type, sample_length, normalization_ma_length, normalization_ma)
Parameters:
momentum_type (series MomentumType) : select one of MomentumType. to sample the price, volume or a product of both
sample_type (series SampleType) : select one of SampleType. to sample the body, total range from high to low or a combination of both (body count full, wicks half for each direction)
sample_length (simple int) : how many candles should be sampled (including the current)
normalization_ma_length (simple int) : if you want to normalize results (momentum / momentum average) this sets the period for the average. (default = 0 => no normalization)
normalization_ma (simple MovingAverage enum from robbatt/lib_no_delay/9) : is the type of moving average to normalize / compare with
Returns: returns the current momentum where the total line is not just (up - down) but also sampled over the sample_length and can therefore be used as trend indicator. If up/down fail to reach total's level it's a sign of decreasing momentum, if up/down exceed total the trend it's a sign of increasing momentum.

Fed Fund Futures Custom AverageThis indicator helps traders track the expected average interest rate for the upcoming 12 months based on Fed Fund Futures. It calculates the average price of the next 12 monthly futures contracts and also shows the spread against the 1-Year US Treasury yield (US01Y). This can be useful for understanding market expectations regarding interest rate changes and identifying trading opportunities related to interest rate movements.

Kendall, Pearson, Spearman, Rolling Pearson//@version=5
indicator("Kendall, Pearson, Spearman, Rolling Pearson", overlay=false)
// -----------------------------
// User Inputs
// -----------------------------
symbol1 = input.symbol("SPY", title="First Symbol", inline="Symbol")
symbol2 = input.symbol("AAPL", title="Second Symbol", inline="Symbol")
lookback = input.int(20, minval=2, title="Lookback Period")
rolling_window = input.int(10, minval=2, title="Rolling Window for Pearson")
// -----------------------------
// Data Requests
// -----------------------------
asset1_close = request.security(symbol1, timeframe.period, close)
asset2_close = request.security(symbol2, timeframe.period, close)
// -----------------------------
// Helper Functions
// -----------------------------
// Function to calculate the sign of a value
sign_func(x) =>
x > 0 ? 1 : x < 0 ? -1 : 0
// Function to format values to 4 decimal places
format_val(val) =>
str.tostring(val, "#.####")
// Custom Rank Function
rank_func(val, series, len) =>
float r = 1.0
for i = 0 to len - 1
if series < val
r += 1
r
// -----------------------------
// Correlation Calculations
// -----------------------------
// Kendall's Tau-B Calculation
var float concordant = 0.0
var float discordant = 0.0
var float tie1 = 0.0
var float tie2 = 0.0
// Reset counts on each bar
concordant := 0.0
discordant := 0.0
tie1 := 0.0
tie2 := 0.0
for i = 0 to lookback - 2
for j = i + 1 to lookback - 1
diff1 = asset1_close - asset1_close
diff2 = asset2_close - asset2_close
sign_diff1 = sign_func(diff1)
sign_diff2 = sign_func(diff2)
if sign_diff1 == sign_diff2 and sign_diff1 != 0
concordant += 1
else if sign_diff1 != sign_diff2 and sign_diff1 != 0 and sign_diff2 != 0
discordant += 1
if diff1 == 0 and diff2 != 0
tie1 += 1
if diff2 == 0 and diff1 != 0
tie2 += 1
if diff1 == 0 and diff2 == 0
tie1 += 1
tie2 += 1
n = (lookback * (lookback - 1)) / 2
// To prevent division by zero, check if denominator is not zero
tau_b = (n - tie1) != 0 and (n - tie2) != 0 ? (concordant - discordant) / math.sqrt((n - tie1) * (n - tie2)) : na
// Pearson's Correlation Calculation
var float sum_x = 0.0
var float sum_y = 0.0
var float sum_x_squared = 0.0
var float sum_y_squared = 0.0
var float sum_xy = 0.0
// Reset sums on each bar
sum_x := 0.0
sum_y := 0.0
sum_x_squared := 0.0
sum_y_squared := 0.0
sum_xy := 0.0
for i = 0 to lookback - 1
sum_x += asset1_close
sum_y += asset2_close
sum_x_squared += asset1_close * asset1_close
sum_y_squared += asset2_close * asset2_close
sum_xy += asset1_close * asset2_close
mean_x = sum_x / lookback
mean_y = sum_y / lookback
stddev_x = math.sqrt(sum_x_squared / lookback - mean_x * mean_x)
stddev_y = math.sqrt(sum_y_squared / lookback - mean_y * mean_y)
covariance = (sum_xy / lookback) - (mean_x * mean_y)
pearson = (stddev_x != 0 and stddev_y != 0) ? covariance / (stddev_x * stddev_y) : na
// Spearman's Rank Correlation Calculation
var float sum_rank_x = 0.0
var float sum_rank_y = 0.0
var float sum_rank_x_squared = 0.0
var float sum_rank_y_squared = 0.0
var float sum_rank_xy = 0.0
// Reset sums on each bar
sum_rank_x := 0.0
sum_rank_y := 0.0
sum_rank_x_squared := 0.0
sum_rank_y_squared := 0.0
sum_rank_xy := 0.0
for i = 0 to lookback - 1
rank_x = rank_func(asset1_close , asset1_close, lookback)
rank_y = rank_func(asset2_close , asset2_close, lookback)
sum_rank_x += rank_x
sum_rank_y += rank_y
sum_rank_x_squared += rank_x * rank_x
sum_rank_y_squared += rank_y * rank_y
sum_rank_xy += rank_x * rank_y
mean_rank_x = sum_rank_x / lookback
mean_rank_y = sum_rank_y / lookback
stddev_rank_x = math.sqrt(sum_rank_x_squared / lookback - mean_rank_x * mean_rank_x)
stddev_rank_y = math.sqrt(sum_rank_y_squared / lookback - mean_rank_y * mean_rank_y)
cov_rank = (sum_rank_xy / lookback) - (mean_rank_x * mean_rank_y)
spearman = (stddev_rank_x != 0 and stddev_rank_y != 0) ? cov_rank / (stddev_rank_x * stddev_rank_y) : na
// Rolling Pearson Correlation Calculation
var float roll_sum_x = 0.0
var float roll_sum_y = 0.0
var float roll_sum_x_squared = 0.0
var float roll_sum_y_squared = 0.0
var float roll_sum_xy = 0.0
// Reset rolling sums on each bar
roll_sum_x := 0.0
roll_sum_y := 0.0
roll_sum_x_squared := 0.0
roll_sum_y_squared := 0.0
roll_sum_xy := 0.0
for i = 0 to rolling_window - 1
roll_sum_x += asset1_close
roll_sum_y += asset2_close
roll_sum_x_squared += asset1_close * asset1_close
roll_sum_y_squared += asset2_close * asset2_close
roll_sum_xy += asset1_close * asset2_close
roll_mean_x = roll_sum_x / rolling_window
roll_mean_y = roll_sum_y / rolling_window
roll_stddev_x = math.sqrt(roll_sum_x_squared / rolling_window - roll_mean_x * roll_mean_x)
roll_stddev_y = math.sqrt(roll_sum_y_squared / rolling_window - roll_mean_y * roll_mean_y)
roll_covariance = (roll_sum_xy / rolling_window) - (roll_mean_x * roll_mean_y)
rolling_pearson = (roll_stddev_x != 0 and roll_stddev_y != 0) ? roll_covariance / (roll_stddev_x * roll_stddev_y) : na
// -----------------------------
// Plotting Correlations
// -----------------------------
plot(tau_b, color=color.blue, title="Kendall's Tau-B")
plot(pearson, color=color.red, title="Pearson's Correlation")
plot(spearman, color=color.green, title="Spearman's Correlation")
plot(rolling_pearson, color=color.purple, title="Rolling Pearson's Correlation")
hline(0, "Zero Line", color=color.gray)
// -----------------------------
// Table Display
// -----------------------------
// Initialize table only once
var table corrTable = table.new(position.top_right, 2, 5, border_width=1, frame_color=color.black)
// Update table headers on the first bar
if barstate.isfirst
table.cell(corrTable, 0, 0, "Metric", text_color=color.white, bgcolor=color.blue)
table.cell(corrTable, 1, 0, "Value", text_color=color.white, bgcolor=color.blue)
// Update table with latest correlation values on every bar
table.cell(corrTable, 0, 1, "Kendall's Tau-B: Ordinal association measure", text_color=color.black, bgcolor=color.orange)
table.cell(corrTable, 1, 1, format_val(tau_b), text_color=color.white)
table.cell(corrTable, 0, 2, "Pearson's Correlation: Linear relationship measure", text_color=color.black, bgcolor=color.orange)
table.cell(corrTable, 1, 2, format_val(pearson), text_color=color.white)
table.cell(corrTable, 0, 3, "Spearman's Correlation: Monotonic relationship measure", text_color=color.black, bgcolor=color.orange)
table.cell(corrTable, 1, 3, format_val(spearman), text_color=color.white)
table.cell(corrTable, 0, 4, "Rolling Pearson's Correlation: Dynamic linear relationship over time", text_color=color.black, bgcolor=color.orange)
table.cell(corrTable, 1, 4, format_val(rolling_pearson), text_color=color.white)

52 Week High/Low Tracking TableThis Indicator helps the User to Quickly view Current Closing Price Compared to the Mentioned Period High and Low.
"Bars Back" indicate the period you need to look back. In case of Daily charts 260 Bars Back usually indicate 52 Weeks/1 year. This is set a default. But you can change it as well.
The Indicator will show the data for below:-
1) High - Highest Close price for the Mentioned Period
2) % from High - The Percentage difference between the Current Close Price Vs Highest Close price for the Mentioned Period. (-) indicate that the current close price is lesser then then High Price.
3) Low - Lowest Close price for the Mentioned Period
4) % from Low - The Percentage difference between the Current Close Price Vs Highest Close price for the Mentioned Period. (-) indicate that the current close price is lesser then then High Price.
You can add this indicator to Quickly Scan multiple stocks to see were they stand.

TrigWave Suite [InvestorUnknown]The TrigWave Suite combines Sine-weighted, Cosine-weighted, and Hyperbolic Tangent moving averages (HTMA) with a Directional Movement System (DMS) and a Relative Strength System (RSS).
Hyperbolic Tangent Moving Average (HTMA)
The HTMA smooths the price by applying a hyperbolic tangent transformation to the difference between the price and a simple moving average. It also adjusts this value by multiplying it by a standard deviation to create a more stable signal.
// Function to calculate Hyperbolic Tangent
tanh(x) =>
e_x = math.exp(x)
e_neg_x = math.exp(-x)
(e_x - e_neg_x) / (e_x + e_neg_x)
// Function to calculate Hyperbolic Tangent Moving Average
htma(src, len, mul) =>
tanh_src = tanh((src - ta.sma(src, len)) * mul) * ta.stdev(src, len) + ta.sma(src, len)
htma = ta.sma(tanh_src, len)
Sine-Weighted Moving Average (SWMA)
The SWMA applies sine-based weights to historical prices. This gives more weight to the central data points, making it responsive yet less prone to noise.
// Function to calculate the Sine-Weighted Moving Average
f_Sine_Weighted_MA(series float src, simple int length) =>
var float sine_weights = array.new_float(0)
array.clear(sine_weights) // Clear the array before recalculating weights
for i = 0 to length - 1
weight = math.sin((math.pi * (i + 1)) / length)
array.push(sine_weights, weight)
// Normalize the weights
sum_weights = array.sum(sine_weights)
for i = 0 to length - 1
norm_weight = array.get(sine_weights, i) / sum_weights
array.set(sine_weights, i, norm_weight)
// Calculate Sine-Weighted Moving Average
swma = 0.0
if bar_index >= length
for i = 0 to length - 1
swma := swma + array.get(sine_weights, i) * src
swma
Cosine-Weighted Moving Average (CWMA)
The CWMA uses cosine-based weights for data points, which produces a more stable trend-following behavior, especially in low-volatility markets.
f_Cosine_Weighted_MA(series float src, simple int length) =>
var float cosine_weights = array.new_float(0)
array.clear(cosine_weights) // Clear the array before recalculating weights
for i = 0 to length - 1
weight = math.cos((math.pi * (i + 1)) / length) + 1 // Shift by adding 1
array.push(cosine_weights, weight)
// Normalize the weights
sum_weights = array.sum(cosine_weights)
for i = 0 to length - 1
norm_weight = array.get(cosine_weights, i) / sum_weights
array.set(cosine_weights, i, norm_weight)
// Calculate Cosine-Weighted Moving Average
cwma = 0.0
if bar_index >= length
for i = 0 to length - 1
cwma := cwma + array.get(cosine_weights, i) * src
cwma
Directional Movement System (DMS)
DMS is used to identify trend direction and strength based on directional movement. It uses ADX to gauge trend strength and combines +DI and -DI for directional bias.
// Function to calculate Directional Movement System
f_DMS(simple int dmi_len, simple int adx_len) =>
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
trur = ta.rma(ta.tr, dmi_len)
plus = fixnan(100 * ta.rma(plusDM, dmi_len) / trur)
minus = fixnan(100 * ta.rma(minusDM, dmi_len) / trur)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adx_len)
dms_up = plus > minus and adx > minus
dms_down = plus < minus and adx > plus
dms_neutral = not (dms_up or dms_down)
signal = dms_up ? 1 : dms_down ? -1 : 0
Relative Strength System (RSS)
RSS employs RSI and an adjustable moving average type (SMA, EMA, or HMA) to evaluate whether the market is in a bullish or bearish state.
// Function to calculate Relative Strength System
f_RSS(rsi_src, rsi_len, ma_type, ma_len) =>
rsi = ta.rsi(rsi_src, rsi_len)
ma = switch ma_type
"SMA" => ta.sma(rsi, ma_len)
"EMA" => ta.ema(rsi, ma_len)
"HMA" => ta.hma(rsi, ma_len)
signal = (rsi > ma and rsi > 50) ? 1 : (rsi < ma and rsi < 50) ? -1 : 0
ATR Adjustments
To minimize false signals, the HTMA, SWMA, and CWMA signals are adjusted with an Average True Range (ATR) filter:
// Calculate ATR adjusted components for HTMA, CWMA and SWMA
float atr = ta.atr(atr_len)
float htma_up = htma + (atr * atr_mult)
float htma_dn = htma - (atr * atr_mult)
float swma_up = swma + (atr * atr_mult)
float swma_dn = swma - (atr * atr_mult)
float cwma_up = cwma + (atr * atr_mult)
float cwma_dn = cwma - (atr * atr_mult)
This adjustment allows for better adaptation to varying market volatility, making the signal more reliable.
Signals and Trend Calculation
The indicator generates a Trend Signal by aggregating the output from each component. Each component provides a directional signal that is combined to form a unified trend reading. The trend value is then converted into a long (1), short (-1), or neutral (0) state.
Backtesting Mode and Performance Metrics
The Backtesting Mode includes a performance metrics table that compares the Buy and Hold strategy with the TrigWave Suite strategy. Key statistics like Sharpe Ratio, Sortino Ratio, and Omega Ratio are displayed to help users assess performance. Note that due to labels and plotchar use, automatic scaling may not function ideally in backtest mode.
Alerts and Visualization
Trend Direction Alerts: Set up alerts for long and short signals
Color Bars and Gradient Option: Bars are colored based on the trend direction, with an optional gradient for smoother visual feedback.
Important Notes
Customization: Default settings are experimental and not intended for trading/investing purposes. Users are encouraged to adjust and calibrate the settings to optimize results according to their trading style.
Backtest Results Disclaimer: Please note that backtest results are not indicative of future performance, and no strategy guarantees success.

RSI Wave Function Ultimate OscillatorEnglish Explanation of the "RSI Wave Function Ultimate Oscillator" Pine Script Code
Understanding the Code
Purpose:
This Pine Script code creates a custom indicator that combines the Relative Strength Index (RSI) with a wave function to potentially provide more nuanced insights into market dynamics.
Key Components:
* Wave Function: This is a custom calculation that introduces a sinusoidal wave component to the price data. The frequency parameter controls the speed of the oscillation, and the decay factor determines how quickly the influence of past prices diminishes.
* Smoothed Signal: The wave function is applied to the closing price to create a smoothed signal, which is essentially a price series modulated by a sine wave.
* RSI: The traditional RSI is then calculated on this smoothed signal, providing a measure of the speed and change of price movements relative to recent price changes.
Calculation Steps:
* Wave Function Calculation:
* A sinusoidal wave is generated based on the bar index and the frequency parameter.
* The wave is combined with the closing price using a weighted average, where the decay factor determines the weight given to previous values.
* RSI Calculation:
* The RSI is calculated on the smoothed signal using a standard RSI formula.
* Plotting:
* The RSI values are plotted on a chart, along with horizontal lines at 70 and 30 to indicate overbought and oversold conditions.
* The area between the RSI line and the overbought/oversold lines is filled with color to visually represent the market condition.
Interpretation and Usage
* Wave Function: The wave function introduces cyclical patterns into the price data, which can help identify potential turning points or momentum shifts.
* RSI: The RSI provides a measure of the speed and change of price movements relative to recent price changes. When applied to the smoothed signal, it can help identify overbought and oversold conditions, as well as potential divergences between price and momentum.
* Combined Indicator: The combination of the wave function and RSI aims to provide a more sensitive and potentially earlier indication of market reversals.
* Signals:
* Crossovers: Crossovers of the RSI line above or below the overbought/oversold lines can be used to generate buy or sell signals.
* Divergences: Divergences between the price and the RSI can indicate a weakening trend.
* Oscillations: The amplitude and frequency of the oscillations in the RSI can provide insights into the strength and duration of market trends.
How it Reflects Market Volatility
* Amplified Volatility: The wave function can amplify the volatility of the price data, making it easier to identify potential turning points.
* Smoothing: The decay factor helps to smooth out short-term fluctuations, allowing the indicator to focus on longer-term trends.
* Sensitivity: The combination of the wave function and RSI can make the indicator more sensitive to changes in market momentum.
In essence, this custom indicator attempts to enhance traditional RSI analysis by incorporating a cyclical component that can potentially provide earlier signals of market reversals.
Note: The effectiveness of this indicator will depend on various factors, including the specific market, time frame, and the chosen values for the frequency and decay parameters. It is recommended to conduct thorough backtesting and optimize the parameters to suit your specific trading strategy.

Average Bullish & Bearish Percentage ChangeAverage Bullish & Bearish Percentage Change
Processes two key aspects of directional market movements relative to price levels. Unlike traditional momentum tools, it separately calculates the average of positive and negative percentage changes in price using user-defined independent counts of actual past bullish and bearish candles. This approach delivers comprehensive and precise view of average percentage changes.
FEATURES:
Count-Based Averages: Separate averaging of bullish and bearish %𝜟 based on their respective number of occurrences ensures reliable and precise momentum calculations.
Customizable Averaging: User-defined number of candle count sets number of past bullish and bearish candles used in independent averaging.
Two Methods of Candle Metrics:
1. Net Move: Focuses on the body range of the candle, emphasizing the net directional movement.
2. Full Capacity: Incorporates wicks and gaps to capture full potential of the bar.
The indicator classifies Doji candles contextually, ensuring they are appropriately factored into the bullish or bearish metrics to avoid mistakes in calculation:
1. Standard Doji - open equals close.
2. Flat Close Doji - Candles where the close matches the previous close.
Timeframe Flexibility:
The indicator can be applied across any desired timeframe, allowing for seamless multi-timeframe analysis.
HOW TO USE
Select Method of Bar Metrics:
Net Move: For analyzing markets where price changes are consistent and bars are close to each other.
Full Capacity: Incorporates wicks and gaps, providing relevant figures for markets like stocks
Set the number of past candles to average:
🟩 Average Past Bullish Candles (Default: 10)
🟥 Average Past Bullish Candles (Default: 10)
Why Percentage Change Is Important
Standardized Measurement Across Assets:
Percentage change normalizes price movements, making it easier to compare different assets with varying price levels. For example, a $1 move in a $10 stock is significant, but the same $1 move in a $1,000 stock is negligible.
Highlights Relative Impact:
By measuring the price change as a percentage of the close, traders can better understand the relative impact of a move on the asset’s overall value.
Volatility Insights:
A high percentage change indicates heightened volatility, which can be a signal of potential opportunities or risks, making it more actionable than raw price changes. Percents directly reflect the strength of buying or selling pressure, providing a clearer view of momentum compared to raw price moves, which may not account for the relative size of the move.
By focusing on percentage change, this indicator provides a normalized, actionable, and insightful measure of market momentum, which is critical for comparing, analyzing, and acting on price movements across various assets and conditions.

Sequence Waves [OmegaTools]the sequence waves indicator, developed by omegatools, is a multi-functional tool designed to detect trends, sequences, and potential reversal signals based on price movements and volume. this indicator has two main modes, "trend" and "sequence," which determine how the indicator calculates directional changes. additional enhancements in this version include reversal signals, allowing users to identify potential long and short opportunities with specific entry cues.
input parameters
mode (mode): chooses the calculation basis for directional movement.
- "trend": uses a midline calculated from the highest high and lowest low over the "trend mode length" period to assess if the price is in an upward or downward trend.
- "sequence": compares the current price to the closing price of the previous "sequence mode length" period to detect shifts in direction.
counter mode (modec): sets whether the counter increments by a fixed amount (1 or -1) or the volume of the bar, impacting the indicator’s sensitivity.
- "fixed": increments or decrements the counter by 1.
- "volume": increments or decrements based on the period’s volume, making the indicator more responsive to high-volume periods.
percentile length (lntp): defines the lookback period for calculating overbought and oversold thresholds using a percentile method. shorter lengths make ob/os levels more reactive.
sensitivity (sens): controls the percentile-based ob/os thresholds, ranging from 10 to 100. higher values narrow ob/os zones, while lower values widen them, impacting signal frequency.
trend mode length (lnt1): sets the period length for midline calculation in trend mode, defaulting to 21. longer periods smooth the midline for detecting major trends.
sequence mode length (lnt2): sets the lookback period in sequence mode, with a default of 4. shorter lengths capture more frequent directional changes, while longer lengths smooth signals.
visual colors:
- up color (upc): sets the color for upward movements.
- down color (dnc): sets the color for downward movements.
calculation logic
midline calculation: in trend mode, a midline is derived from the average of the highest high and lowest low over the "trend mode length" period, acting as a reference to detect upward or downward movements.
counter calculation:
- in trend mode, if the close price is above the midline, the counter increases (or volume if volume mode is selected). it decreases when the price is below.
- in sequence mode, the counter increases if the close is above the closing price from "sequence mode length" periods ago and decreases if below.
the counter resets to zero on direction changes, creating clear directional transitions.
overbought/oversold percentiles: separate arrays track the counter’s values each time the direction changes, creating historical up and down values. ob and os thresholds are dynamically determined based on these arrays, with sizes limited by the percentile length and sensitivity inputs.
reversal signals: two new variables, "long" and "short," detect potential reversal points when the counter crosses specific thresholds:
- long: a long signal is generated when the counter switches to positive and exceeds the down percentile.
- short: a short signal is triggered when the counter switches to negative and exceeds the up percentile.
visual and display elements
counter plot: plots the counter value on the chart with color-coded columns, making it easy to spot directional momentum.
up and down percentiles: displays overbought (up percentile) and oversold (down percentile) thresholds to identify potential reversal zones.
regime background: the background color changes based on market regime:
- bullish (up percentile > down percentile): greenish background.
- bearish (down percentile > up percentile): reddish background.
- neutral (both percentiles equal): grayish background.
reversal signals: plotted as small triangles on the chart for visual confirmation of potential long (triangle up) and short (triangle down) reversal signals.
obs background: changes color when the counter exceeds ob or os thresholds, creating a visual cue for extreme market conditions:
- overbought: background changes to a faint down color.
- oversold: background changes to a faint up color.
status table: displayed on the right side of the chart, providing real-time status information:
- status: shows "overbought," "oversold," "long," "short," or "none" based on the current counter position.
- regime: indicates whether the market is in a "bullish," "bearish," or "neutral" state based on the percentile comparison.
- percentile up/down: displays the current up and down percentiles for quick reference.
how to use the indicator
trend following: in trend mode, use the midline-based counter to gauge if the market is in an uptrend (positive counter) or downtrend (negative counter).
reversal detection: the ob/os thresholds assist in identifying potential reversal points. when the counter exceeds the up percentile, it may indicate an overbought state, suggesting a bearish reversal. similarly, dropping below the down percentile may indicate an oversold state, suggesting a bullish reversal.
entry signals: use the long and short reversal signals for potential entry points, particularly in trending or range-bound markets. these signals are indicated by up and down triangles.
sequence trading: in sequence mode, the indicator tracks shorter-term directional shifts, making it suitable for detecting smaller momentum patterns based on recent price comparisons.
volume sensitivity: selecting volume mode enhances sensitivity to high-volume moves, allowing it to detect stronger market activity in both trend and sequence modes.
the sequence waves indicator is suited to both short-term and long-term traders. it allows for detailed trend analysis, reversal detection, and dynamic ob/os signals. the inclusion of visual reversal cues makes it a flexible tool adaptable to a variety of trading strategies.

Low Price VolatilityI highlighted periods of low price volatility in the Nikkei 225 futures trading.
It is Japan Standard Time (JST)
This script is designed to color-code periods in the Nikkei 225 futures market according to times when prices tend to be more volatile and times when they are less volatile. The testing period is from March 11, 2024, to November 1, 2024. It identifies periods and counts where price movement exceeded half of the ATR, and colors are applied based on this data. There are no calculations involved; it simply uses the results of the analysis to apply color.

Volume Bars [jpkxyz]
Multi-Timeframe Volume indicator by @jpkxyz
This script is a Multi-Timeframe Volume Z-Score Indicator. It dynamically calculates /the Z-Score of volume over different timeframes to assess how significantly current
volume deviates from its historical average. The Z-Score is computed for each
timeframe independently and is based on a user-defined lookback period. The
script switches between timeframes automatically, adapting to the chart's current
timeframe using `timeframe.multiplier`.
The Z-Score formula used is: (current volume - mean) / standard deviation, where
mean and standard deviation are calculated over the lookback period.
The indicator highlights periods of "significant" and "massive" volume by comparing
the Z-Score to user-specified thresholds (`zScoreThreshold` for significant volume
and `massiveZScoreThreshold` for massive volume). The script flags buy or sell
conditions based on whether the current close is higher or lower than the open.
Visual cues:
- Dark Green for massive buy volume.
- Red for massive sell volume.
- Green for significant buy volume.
- Orange for significant sell volume.
- Gray for normal volume.
The script also provides customizable alert conditions for detecting significant or massive buy/sell volume events, allowing users to set real-time alerts.

FTMO Rules MonitorFTMO Rules Monitor: Stay on Track with Your FTMO Challenge Goals
TLDR; You can test with this template whether your strategy for one asset would pass the FTMO challenges step 1 then step 2, then with real money conditions.
Passing a prop firm challenge is ... challenging.
I believe a toolkit allowing to test in minutes whether a strategy would have passed a prop firm challenge in the past could be very powerful.
The FTMO Rules Monitor is designed to help you stay within FTMO’s strict risk management guidelines directly on your chart. Whether you’re aiming for the $10,000 or the $200,000 account challenge, this tool provides real-time tracking of your performance against FTMO’s rules to ensure you don’t accidentally breach any limits.
NOTES
The connected indicator for this post doesn't matter.
It's just a dummy double supertrends (see below)
The strategy results for this script post does not matter as I'm posting a FTMO rules template on which you can connect any indicator/strategy.
//@version=5
indicator("Supertrends", overlay=true)
// Supertrend 1 Parameters
var string ST1 = "Supertrend 1 Settings"
st1_atrPeriod = input.int(10, "ATR Period", minval=1, maxval=50, group=ST1)
st1_factor = input.float(2, "Factor", minval=0.5, maxval=10, step=0.5, group=ST1)
// Supertrend 2 Parameters
var string ST2 = "Supertrend 2 Settings"
st2_atrPeriod = input.int(14, "ATR Period", minval=1, maxval=50, group=ST2)
st2_factor = input.float(3, "Factor", minval=0.5, maxval=10, step=0.5, group=ST2)
// Calculate Supertrends
= ta.supertrend(st1_factor, st1_atrPeriod)
= ta.supertrend(st2_factor, st2_atrPeriod)
// Entry conditions
longCondition = direction1 == -1 and direction2 == -1 and direction1 == 1
shortCondition = direction1 == 1 and direction2 == 1 and direction1 == -1
// Optional: Plot Supertrends
plot(supertrend1, "Supertrend 1", color = direction1 == -1 ? color.green : color.red, linewidth=3)
plot(supertrend2, "Supertrend 2", color = direction2 == -1 ? color.lime : color.maroon, linewidth=3)
plotshape(series=longCondition, location=location.belowbar, color=color.green, style=shape.triangleup, title="Long")
plotshape(series=shortCondition, location=location.abovebar, color=color.red, style=shape.triangledown, title="Short")
signal = longCondition ? 1 : shortCondition ? -1 : na
plot(signal, "Signal", display = display.data_window)
To connect your indicator to this FTMO rules monitor template, please update it as follow
Create a signal variable to store 1 for the long/buy signal or -1 for the short/sell signal
Plot it in the display.data_window panel so that it doesn't clutter your chart
signal = longCondition ? 1 : shortCondition ? -1 : na
plot(signal, "Signal", display = display.data_window)
In the FTMO Rules Monitor template, I'm capturing this external signal with this input.source variable
entry_connector = input.source(close, "Entry Connector", group="Entry Connector")
longCondition = entry_connector == 1
shortCondition = entry_connector == -1
🔶 USAGE
This indicator displays essential FTMO Challenge rules and tracks your progress toward meeting each one. Here’s what’s monitored:
Max Daily Loss
• 10k Account: $500
• 25k Account: $1,250
• 50k Account: $2,500
• 100k Account: $5,000
• 200k Account: $10,000
Max Total Loss
• 10k Account: $1,000
• 25k Account: $2,500
• 50k Account: $5,000
• 100k Account: $10,000
• 200k Account: $20,000
Profit Target
• 10k Account: $1,000
• 25k Account: $2,500
• 50k Account: $5,000
• 100k Account: $10,000
• 200k Account: $20,000
Minimum Trading Days: 4 consecutive days for all account sizes
🔹 Key Features
1. Real-Time Compliance Check
The FTMO Rules Monitor keeps track of your daily and total losses, profit targets, and trading days. Each metric updates in real-time, giving you peace of mind that you’re within FTMO’s rules.
2. Color-Coded Visual Feedback
Each rule’s status is shown clearly with a ✓ for compliance or ✗ if the limit is breached. When a rule is broken, the indicator highlights it in red, so there’s no confusion.
3. Completion Notification
Once all FTMO requirements are met, the indicator closes all open positions and displays a celebratory message on your chart, letting you know you’ve successfully completed the challenge.
4. Easy-to-Read Table
A table on your chart provides an overview of each rule, your target, current performance, and whether you’re meeting each goal. The table adjusts its color scheme based on your chart settings for optimal visibility.
5. Dynamic Position Sizing
Integrated ATR-based position sizing helps you manage risk and avoid large drawdowns, ensuring each trade aligns with FTMO’s risk management principles.
Daveatt

Dynamic Market Correlation Analyzer (DMCA) v1.0Description
The Dynamic Market Correlation Analyzer (DMCA) is an advanced TradingView indicator designed to provide real-time correlation analysis between multiple assets. It offers a comprehensive view of market relationships through correlation coefficients, technical indicators, and visual representations.
Key Features
- Multi-asset correlation tracking (up to 5 symbols)
- Dynamic correlation strength categorization
- Integrated technical indicators (RSI, MACD, DX)
- Customizable visualization options
- Real-time price change monitoring
- Flexible timeframe selection
## Use Cases
1. **Portfolio Diversification**
- Identify highly correlated assets to avoid concentration risk
- Find negatively correlated assets for hedging strategies
- Monitor correlation changes during market events
2. Pairs Trading
- Detect correlation breakdowns for potential trading opportunities
- Track correlation strength for pair selection
- Monitor technical indicators for trade timing
3. Risk Management
- Assess portfolio correlation risk in real-time
- Monitor correlation shifts during market stress
- Identify potential portfolio vulnerabilities
4. **Market Analysis**
- Study sector relationships and rotations
- Analyze cross-asset correlations (e.g., stocks vs. commodities)
- Track market regime changes through correlation patterns
Components
Input Parameters
- **Timeframe**: Custom timeframe selection for analysis
- **Length**: Correlation calculation period (default: 20)
- **Source**: Price data source selection
- **Symbol Selection**: Up to 5 customizable symbols
- **Display Options**: Table position, text color, and size settings
Technical Indicators
1. **Correlation Coefficient**
- Range: -1 to +1
- Strength categories: Strong/Moderate/Weak (Positive/Negative)
2. **RSI (Relative Strength Index)**
- 14-period default setting
- Momentum comparison across assets
3. **MACD (Moving Average Convergence Divergence)**
- Standard settings (12, 26, 9)
- Trend direction indicator
4. **DX (Directional Index)**
- Trend strength measurement
- Based on DMI calculations
Visual Components
1. **Correlation Table**
- Symbol identifiers
- Correlation coefficients
- Correlation strength descriptions
- Price change percentages
- Technical indicator values
2. **Correlation Plot**
- Real-time correlation visualization
- Multiple correlation lines
- Reference levels at -1, 0, and +1
- Color-coded for easy identification
Installation and Setup
1. Load the indicator on TradingView
2. Configure desired symbols (up to 5)
3. Adjust timeframe and calculation length
4. Customize display settings
5. Enable/disable desired components (table, plot, RSI)
Best Practices
1. **Symbol Selection**
- Choose related but distinct assets
- Include a mix of asset classes
- Consider market cap and liquidity
2. **Timeframe Selection**
- Match timeframe to trading strategy
- Consider longer timeframes for strategic analysis
- Use shorter timeframes for tactical decisions
3. **Interpretation**
- Monitor correlation changes over time
- Consider multiple timeframes
- Combine with other technical analysis tools
- Account for market conditions and volatility
Performance Notes
- Calculations update in real-time
- Resource usage scales with number of active symbols
- Historical data availability may affect initial calculations
Version History
- v1.0: Initial release with core functionality
- Multi-symbol correlation analysis
- Technical indicator integration
- Customizable display options
Future Enhancements (Planned)
- Additional technical indicators
- Advanced correlation algorithms
- Enhanced visualization options
- Custom alert conditions
- Statistical significance testing

[Volatility] [Gain & Loss] - OverviewFX:EURUSD
Indicator Overview: Volatility & Gain/Loss - Forex Pair Analysis
This indicator, " —Overview" , is designed for users interested in analyzing the volatility and gain/loss metrics of multiple forex pairs. The tool is especially useful for traders aiming to assess currency pair volatility alongside gain and loss percentages over selected periods. It enables a clearer understanding of pair behavior and aids in decision-making.
Key Features
Customizable Volatility and Gain/Loss Periods : Define your preferred calculation periods and timeframes for both volatility and gain/loss to tailor the indicator to specific trading strategies. Multi-Pair Analysis : This indicator supports up to six forex pairs (default pairs include EURUSD, GBPUSD, USDJPY, USDCHF, AUDUSD, and USDCAD) and allows you to adjust these pairs as needed. Visual Ranking : Forex pairs are sorted by volatility, displaying the highest pairs at the top for quick reference. Top Gain/Loss Highlighting : The pair with the maximum gain and the pair with the maximum loss are highlighted in the table, making it easy to identify the best and worst performers at a glance.
Indicator Settings
Volatility Settings : Period : Adjust the number of periods used in the ATR (Average True Range) calculation. A default period of 14 is set. Timeframe : Select a timeframe (e.g., Daily, Weekly) for volatility calculation to match your analysis preference.
Gain/Loss Settings : Period : Choose the number of periods for gain/loss calculation. The default is set to 1. Timeframe : Select the timeframe for gain/loss calculation, independent of the volatility timeframe.
Symbol Selection : Configure up to six forex pairs. By default, popular forex pairs are pre-loaded but can be customized to include other currency pairs.
Output and Visualization
Table Display : This indicator displays data in a neatly structured table positioned in the top-right corner of your chart. Columns : Includes columns for the Forex Pair, Volatility Percentage, Gain Percentage, and Loss Percentage. Color Coding : Volatility is displayed in a standard color for clear readability. Gain values are highlighted in green, and Loss values are highlighted in red, allowing for quick visual differentiation. Highlighting : Rows representing the pair with the highest gain and the pair with the most significant loss are especially highlighted for emphasis.
How to Use
Volatility Analysis : This metric gives insight into the average price range movements for each pair over the specified period and timeframe, helping you evaluate the potential for rapid price changes. Gain/Loss Tracking : Gain or loss percentages show the pair's recent performance, allowing you to observe whether a currency pair is trending positively or negatively over the chosen period. Comparative Pair Ranking : Use the table to identify pairs with the highest volatility and extremes in gain or loss to guide trading decisions based on market conditions.
Ideal For
Swing Traders and Day Traders looking to understand short-term market fluctuations in currency pairs. Risk Management : Helps traders gauge pairs with higher risk (volatility) and recent performance (gain/loss) for informed position sizing and risk control.
This indicator is a comprehensive tool for visualizing and analyzing key forex pairs, making it an essential addition for traders looking to stay updated on volatility trends and recent price changes.

AutoCorrelation Test [OmegaTools]Overview
The AutoCorrelation Test indicator is designed to analyze the correlation patterns of a financial asset over a specified period. This tool can help traders identify potential predictive patterns by measuring the relationship between sequential returns, effectively assessing the autocorrelation of price movements.
Autocorrelation analysis is useful in identifying the consistency of directional trends (upward or downward) and potential cyclical behavior. This indicator provides an insight into whether recent price movements are likely to continue in a similar direction (positive correlation) or reverse (negative correlation).
Key Features
Multi-Period Autocorrelation: The indicator calculates autocorrelation across three periods, offering a granular view of price movement consistency over time.
Customizable Length & Sensitivity: Adjustable parameters allow users to tailor the length of analysis and sensitivity for detecting correlation.
Visual Aids: Three separate autocorrelation plots are displayed, along with an average correlation line. Dotted horizontal lines mark the thresholds for positive and negative correlation, helping users quickly assess potential trend continuation or reversal.
Interpretive Table: A table summarizing correlation status for each period helps traders make quick, informed decisions without needing to interpret the plot details directly.
Parameters
Source: Defines the price source (default: close) for calculating autocorrelation.
Length: Sets the analysis period, ranging from 10 to 2000 (default: 200).
Sensitivity: Adjusts the threshold sensitivity for defining correlation as positive or negative (default: 2.5).
Interpretation
Above 50 + Sensitivity: Indicates Positive Correlation. The price movements over the selected period are likely to continue in the same direction, potentially signaling a trend continuation.
Below 50 - Sensitivity: Indicates Negative Correlation. The price movements show a likelihood of reversing, which could signal an upcoming trend reversal.
Between 50 ± Sensitivity: Indicates No Correlation. Price movements are less predictable in direction, with no clear trend continuation or reversal tendency.
How It Works
The indicator calculates the logarithmic returns of the selected source price over each length period.
It then compares returns over consecutive periods, categorizing them as either "winning" (consistent direction) or "losing" (inconsistent direction) movements.
The result for each period is displayed as a percentage, with values above 50% indicating a higher degree of directional consistency (positive or negative).
A table updates with descriptive labels (Positive Correlation, Negative Correlation, No Correlation) for each tested period, providing a quick overview.
Visual Elements
Plots:
AutoCorrelation Test : Displays autocorrelation for the closest period (lag 1).
AutoCorrelation Test : Displays autocorrelation for the second period (lag 2).
AutoCorrelation Test : Displays autocorrelation for the third period (lag 3).
Average: Displays the simple moving average of the three test periods for a smoothed view of overall correlation trends.
Horizontal Lines:
No Correlation (50%): A baseline indicating neutral correlation.
Positive/Negative Correlation Thresholds: Dotted lines set at 50 ± Sensitivity, marking the thresholds for significant correlation.
Usage Guide
Adjust Parameters:
Select the Source to define which price metric (e.g., close, open) will be analyzed.
Set the Length based on your preferred analysis window (e.g., shorter for intraday trends, longer for swing trading).
Modify Sensitivity to fine-tune the thresholds based on market volatility and personal trading preference.
Interpret Table and Plots:
Use the table to quickly check the correlation status of each lag period.
Analyze the plots for changes in correlation. If multiple lags show positive correlation above the sensitivity threshold, a trend continuation may be expected. Conversely, negative values suggest a potential reversal.
Integrate with Other Indicators:
For enhanced insights, consider using the AutoCorrelation Test indicator in conjunction with other trend or momentum indicators.
This indicator offers a powerful method to assess market conditions, identify potential trend continuations or reversals, and better inform trading decisions. Its customization options provide flexibility for various trading styles and timeframes.

RBF Kijun Trend System [InvestorUnknown]The RBF Kijun Trend System utilizes advanced mathematical techniques, including the Radial Basis Function (RBF) kernel and Kijun-Sen calculations, to provide traders with a smoother trend-following experience and reduce the impact of noise in price data. This indicator also incorporates ATR to dynamically adjust smoothing and further minimize false signals.
Radial Basis Function (RBF) Kernel Smoothing
The RBF kernel is a mathematical method used to smooth the price series. By calculating weights based on the distance between data points, the RBF kernel ensures smoother transitions and a more refined representation of the price trend.
The RBF Kernel Weighted Moving Average is computed using the formula:
f_rbf_kernel(x, xi, sigma) =>
math.exp(-(math.pow(x - xi, 2)) / (2 * math.pow(sigma, 2)))
The smoothed price is then calculated as a weighted sum of past prices, using the RBF kernel weights:
f_rbf_weighted_average(src, kernel_len, sigma) =>
float total_weight = 0.0
float weighted_sum = 0.0
// Compute weights and sum for the weighted average
for i = 0 to kernel_len - 1
weight = f_rbf_kernel(kernel_len - 1, i, sigma)
total_weight := total_weight + weight
weighted_sum := weighted_sum + (src * weight)
// Check to avoid division by zero
total_weight != 0 ? weighted_sum / total_weight : na
Kijun-Sen Calculation
The Kijun-Sen, a component of Ichimoku analysis, is used here to further establish trends. The Kijun-Sen is computed as the average of the highest high and the lowest low over a specified period (default: 14 periods).
This Kijun-Sen calculation is based on the RBF-smoothed price to ensure smoother and more accurate trend detection.
f_kijun_sen(len, source) =>
math.avg(ta.lowest(source, len), ta.highest(source, len))
ATR-Adjusted RBF and Kijun-Sen
To mitigate false signals caused by price volatility, the indicator features ATR-adjusted versions of both the RBF smoothed price and Kijun-Sen.
The ATR multiplier is used to create upper and lower bounds around these lines, providing dynamic thresholds that account for market volatility.
Neutral State and Trend Continuation
This indicator can interpret a neutral state, where the signal is neither bullish nor bearish. By default, the indicator is set to interpret a neutral state as a continuation of the previous trend, though this can be adjusted to treat it as a truly neutral state.
Users can configure this setting using the signal_str input:
simple string signal_str = input.string("Continuation of Previous Trend", "Treat 0 State As", options = , group = G1)
Visual difference between "Neutral" (Bottom) and "Continuation of Previous Trend" (Top). Click on the picture to see it in full size.
Customizable Inputs and Settings:
Source Selection: Choose the input source for calculations (open, high, low, close, etc.).
Kernel Length and Sigma: Adjust the RBF kernel parameters to change the smoothing effect.
Kijun Length: Customize the lookback period for Kijun-Sen.
ATR Length and Multiplier: Modify these settings to adapt to market volatility.
Backtesting and Performance Metrics
The indicator includes a Backtest Mode, allowing users to evaluate the performance of the strategy using historical data. In Backtest Mode, a performance metrics table is generated, comparing the strategy's results to a simple buy-and-hold approach. Key metrics include mean returns, standard deviation, Sharpe ratio, and more.
Equity Calculation: The indicator calculates equity performance based on signals, comparing it against the buy-and-hold strategy.
Performance Metrics Table: Detailed performance analysis, including probabilities of positive, neutral, and negative returns.
Alerts
To keep traders informed, the indicator supports alerts for significant trend shifts:
// - - - - - ALERTS - - - - - //{
alert_source = sig
bool long_alert = ta.crossover (intrabar ? alert_source : alert_source , 0)
bool short_alert = ta.crossunder(intrabar ? alert_source : alert_source , 0)
alertcondition(long_alert, "LONG (RBF Kijun Trend System)", "RBF Kijun Trend System flipped ⬆LONG⬆")
alertcondition(short_alert, "SHORT (RBF Kijun Trend System)", "RBF Kijun Trend System flipped ⬇Short⬇")
//}
Important Notes
Calibration Needed: The default settings provided are not optimized and are intended for demonstration purposes only. Traders should adjust parameters to fit their trading style and market conditions.
Neutral State Interpretation: Users should carefully choose whether to treat the neutral state as a continuation or a separate signal.
Backtest Results: Historical performance is not indicative of future results. Market conditions change, and past trends may not recur.

Dual Momentum StrategyThis Pine Script™ strategy implements the "Dual Momentum" approach developed by Gary Antonacci, as presented in his book Dual Momentum Investing: An Innovative Strategy for Higher Returns with Lower Risk (McGraw Hill Professional, 2014). Dual momentum investing combines relative momentum and absolute momentum to maximize returns while minimizing risk. Relative momentum involves selecting the asset with the highest recent performance between two options (a risky asset and a safe asset), while absolute momentum considers whether the chosen asset has a positive return over a specified lookback period.
In this strategy:
Risky Asset (SPY): Represents a stock index fund, typically more volatile but with higher potential returns.
Safe Asset (TLT): Represents a bond index fund, which generally has lower volatility and acts as a hedge during market downturns.
Monthly Momentum Calculation: The momentum for each asset is calculated based on its price change over the last 12 months. Only assets with a positive momentum (absolute momentum) are considered for investment.
Decision Rules:
Invest in the risky asset if its momentum is positive and greater than that of the safe asset.
If the risky asset’s momentum is negative or lower than the safe asset's, the strategy shifts the allocation to the safe asset.
Scientific Reference
Antonacci's work on dual momentum investing has shown the strategy's ability to outperform traditional buy-and-hold methods while reducing downside risk. This approach has been reviewed and discussed in both academic and investment publications, highlighting its strong risk-adjusted returns (Antonacci, 2014).
Reference: Antonacci, G. (2014). Dual Momentum Investing: An Innovative Strategy for Higher Returns with Lower Risk. McGraw Hill Professional.

XRP Comparative Price Action Indicator - Final VersionXRP Comparative Price Action Indicator - Final Version
The XRP Comparative Price Action Indicator provides a comprehensive visual analysis of XRP’s price movements relative to key cryptocurrencies and market indices. This indicator normalises price data across various assets, allowing traders and investors to assess XRP’s performance against its peers and major market influences at a glance.
Key Features:
• Normalised Price Data: Prices are scaled between 0.00 and 1.00,
enabling straightforward comparisons between different assets.
• Key Comparisons: Includes normalised prices for:
• XRP/USD (Bitstamp)
• XRP Dominance (CryptoCap)
• XRP/BTC (Bitstamp)
• BTC/USD (Bitstamp)
• BTC Dominance (CryptoCap)
• USDT Dominance (CryptoCap)
• S&P 500 (SPY)
• DXY (Dollar Index)
• ETH/USD (Bitstamp)
• ETH Dominance (CryptoCap)
• XRP/ETH (Binance)
• Visual Clarity: Each asset is plotted with distinct colors for easy identification,
with thicker lines enhancing visibility on the chart.
• Reference Lines: Optional horizontal lines indicate the minimum (0) and maximum (1) normalised values, providing clear reference points for analysis.
This indicator is ideal for traders looking to understand XRP’s relative performance, gauge market sentiment, and make informed trading decisions based on comparative price action.

Autocorrelogram (YavuzAkbay)The Autocorrelogram (ACF) is a statistical tool designed for traders and analysts to evaluate the autocorrelation of price movements over time. Autocorrelation measures the correlation of a signal with a delayed version of itself, providing insights into the degree to which past price movements influence future price movements. This indicator is particularly useful for identifying trends and patterns in time series data, helping traders make informed decisions based on historical price behavior.
Key Components and Functionality
1. Input Parameters:
Sample Size: This parameter defines the number of data points used in the calculation of the autocorrelation function. A minimum value of 9 ensures statistical relevance. The default value is set to 100, which provides a broad view of the price behavior.
Data Source: Users can select the price data they wish to analyze (e.g., closing prices). This flexibility allows traders to apply the ACF to various price types, depending on their trading strategy.
Significance Level: This parameter determines the threshold for statistical significance in the autocorrelation values. The default value is set at 1.96, corresponding to a 95% confidence level, but users can adjust it to their preferences.
Calculate Change: This boolean option allows users to choose whether to calculate the change in the selected data source (e.g., daily price changes) rather than using the raw data. Analyzing changes can highlight momentum shifts that may be obscured in absolute price levels.
2. Core Calculations:
Simple Moving Average (SMA): The indicator computes the SMA of the selected data source over the defined sample size. This average serves as a baseline for assessing deviations in price behavior.
Variance Calculation: The variance of the price changes is calculated to understand the spread of the data. The variance is scaled by the sample size to ensure that the autocorrelation values are appropriately normalized.
Lag Value: The indicator calculates a lag value based on the sample size to determine how many periods back the autocorrelation will be calculated. This helps in assessing correlations at different time intervals.
3. Autocorrelation Calculation:
The script calculates the autocorrelation for lags ranging from 0 to 53. For each lag, it computes the autocovariance (the correlation of the signal with itself at different time intervals) and normalizes this by the variance. The result is a set of autocorrelation values that indicate the strength and direction of the relationship between current and past price movements.
4. Visualization:
The autocorrelation values are plotted as lines on the chart, with different colors indicating positive and negative correlations. Lines are dynamically drawn for each lag, providing a visual representation of how past prices influence current prices. A maximum of 54 lines (for lags 0 to 53) is maintained, with the oldest line being removed when the limit is exceeded.
Significance Levels: Horizontal lines are drawn at the defined significance levels, helping traders quickly identify when the autocorrelation values exceed the statistically significant threshold. These lines serve as benchmarks for interpreting the relevance of the autocorrelation values.
How to Use the ACF Indicator
Identifying Trends: Traders can use the ACF indicator to spot trends in the data. Strong positive autocorrelation at a given lag indicates that past price movements have a lasting influence on future movements, suggesting a potential continuation of the current trend. Conversely, significant negative autocorrelation may indicate reversals or mean reversion.
Decision Making: By comparing the autocorrelation values against the significance levels, traders can make informed decisions. For example, if the autocorrelation at lag 1 is significantly positive, it may suggest that a trend is likely to persist in the immediate future, prompting traders to consider long positions.
Setting Parameters: Adjusting the sample size and significance level allows traders to tailor the indicator to their specific market conditions and trading style. A larger sample size may provide more stable estimates but could obscure short-term fluctuations, while a smaller size may capture quick changes but with higher variability.
Combining with Other Indicators: The ACF can be used in conjunction with other technical indicators (like Moving Averages or RSI) to enhance trading strategies. Confirming signals from multiple indicators can provide stronger trade confirmations.