40 Ticker Cross-Sectional Z-Scores [BackQuant]40 Ticker Cross-Sectional Z-Scores
BackQuant’s 40 Ticker Cross-Sectional Z-Scores is a powerful portfolio management strategy that analyzes the relative performance of up to 40 different assets, comparing them on a cross-sectional basis to identify the top and bottom performers. This indicator computes Z-scores for each asset based on their log returns and evaluates them relative to the mean and standard deviation over a rolling window. The Z-scores represent how far an asset's return deviates from the average, and these values are used to rank the assets, allowing for dynamic asset allocation based on performance.
By focusing on the strongest-performing assets and avoiding the weakest, this strategy aims to enhance returns while managing risk. Additionally, by adjusting for standard deviations, the system offers a risk-adjusted method of ranking assets, making it suitable for traders who want to dynamically allocate capital based on performance metrics rather than just price movements.
Key Features
1. Cross-Sectional Z-Score Calculation:
The system calculates Z-scores for 40 different assets, evaluating their log returns against the mean and standard deviation over a rolling window. This enables users to assess the relative performance of each asset dynamically, highlighting which assets are performing better or worse compared to their historical norms. The Z-score is a useful statistical tool for identifying outliers in asset performance.
2. Asset Ranking and Allocation:
The system ranks assets based on their Z-scores and allocates capital to the top performers. It identifies the top and bottom assets, and traders can allocate capital to the top-performing assets, ensuring that their portfolio is aligned with the best performers. Conversely, the bottom assets are removed from the portfolio, reducing exposure to underperforming assets.
3. Rolling Window for Mean and Standard Deviation Calculations:
The Z-scores are calculated based on rolling means and standard deviations, making the system adaptive to changing market conditions. This rolling calculation window allows the strategy to adjust to recent performance trends and minimize the impact of outdated data.
4. Mean and Standard Deviation Visualization:
The script provides real-time visualizations of the mean (x̄) and standard deviation (σ) of asset returns, helping traders quickly identify trends and volatility in their portfolio. These visual indicators are useful for understanding the current market environment and making more informed allocation decisions.
5. Top & Bottom Performer Tables:
The system generates tables that display the top and bottom performers, ranked by their Z-scores. Traders can quickly see which assets are outperforming and underperforming. These tables provide clear and actionable insights, helping traders make informed decisions about which assets to include in their portfolio.
6. Customizable Parameters:
The strategy allows traders to customize several key parameters, including:
Rolling Calculation Window: Set the window size for the rolling mean and standard deviation calculations.
Top & Bottom Tickers: Choose how many of the top and bottom assets to display and allocate capital to.
Table Orientation: Select between vertical or horizontal table formats to suit the user’s preference.
7. Forward Test & Out-of-Sample Testing:
The system includes out-of-sample forward tests, ensuring that the strategy is evaluated based on real-time performance, not just historical data. This forward testing approach helps validate the robustness of the strategy in dynamic market conditions.
8. Visual Feedback and Alerts:
The system provides visual feedback on the current asset rankings and allocations, with dynamic labels and plots on the chart. Additionally, users receive alerts when allocations change, keeping them informed of important adjustments.
9. Risk Management via Z-Scores and Std Dev:
The system’s approach to asset selection is based on Z-scores, which normalize performance relative to the historical mean. By incorporating standard deviation, it accounts for the volatility and risk associated with each asset. This allows for more precise risk management and portfolio construction.
10. Note on Mean Reversion Strategy:
If you take the inverse of the signals provided by this indicator, the strategy can be used for mean-reversion rather than trend-following. This would involve buying the underperforming assets and selling the outperforming ones. However, it's important to note that this approach does not work well with highly correlated assets, as the relationship between the assets could result in the same directional movement, undermining the effectiveness of the mean-reversion strategy.
References
www.uts.edu.au
onlinelibrary.wiley.com
www.cmegroup.com
Final Thoughts
The 40 Ticker Cross-Sectional Z-Scores strategy offers a data-driven approach to portfolio management, dynamically allocating capital based on the relative performance of assets. By using Z-scores and standard deviations, this strategy ensures that capital is directed to the strongest performers while avoiding weaker assets, ultimately improving the risk-adjusted returns of the portfolio. Whether you’re focused on trend-following or looking to explore mean-reversion strategies, this flexible system can be tailored to suit your investment goals.
Gestione portafoglio
Performance Metrics With Bracketed Rebalacing [BackQuant]Performance Metrics With Bracketed Rebalancing
The Performance Metrics With Bracketed Rebalancing script offers a robust method for assessing portfolio performance, integrating advanced portfolio metrics with different rebalancing strategies. With a focus on adaptability, the script allows traders to monitor and adjust portfolio weights, equity, and other key financial metrics dynamically. This script provides a versatile approach for evaluating different trading strategies, considering factors like risk-adjusted returns, volatility, and the impact of portfolio rebalancing.
Please take the time to read the following:
Key Features and Benefits of Portfolio Methods
Bracketed Rebalancing:
Bracketed Rebalancing is an advanced strategy designed to trigger portfolio adjustments when an asset's weight surpasses a predefined threshold. This approach minimizes overexposure to any single asset while maintaining flexibility in response to market changes. The strategy is particularly beneficial for mitigating risks that arise from significant asset weight fluctuations. The following image illustrates how this method reacts when asset weights cross the threshold:
Daily Rebalancing:
Unlike the bracketed method, Daily Rebalancing adjusts portfolio weights every trading day, ensuring consistent asset allocation. This method aims for a more even distribution of portfolio weights, making it a suitable option for traders who prefer less sensitivity to individual asset volatility. Here's an example of Daily Rebalancing in action:
No Rebalancing:
For traders who prefer a passive approach, the "No Rebalancing" option allows the portfolio to remain static, without any adjustments to asset weights. This method may appeal to long-term investors or those who believe in the inherent stability of their selected assets. Here’s how the portfolio looks when no rebalancing is applied:
Portfolio Weights Visualization:
One of the standout features of this script is the visual representation of portfolio weights. With adjustable settings, users can track the current allocation of assets in real-time, making it easier to analyze shifts and trends. The following image shows the real-time weight distribution across three assets:
Rolling Drawdown Plot:
Managing drawdown risk is a critical aspect of portfolio management. The Rolling Drawdown Plot visually tracks the drawdown over time, helping traders monitor the risk exposure and performance relative to the peak equity levels. This feature is essential for assessing the portfolio's resilience during market downturns:
Daily Portfolio Returns:
Tracking daily returns is crucial for evaluating the short-term performance of the portfolio. The script allows users to plot daily portfolio returns to gain insights into daily profit or loss, helping traders stay updated on their portfolio’s progress:
Performance Metrics
Net Profit (%):
This metric represents the total return on investment as a percentage of the initial capital. A positive net profit indicates that the portfolio has gained value over the evaluation period, while a negative value suggests a loss. It's a fundamental indicator of overall portfolio performance.
Maximum Drawdown (Max DD):
Maximum Drawdown measures the largest peak-to-trough decline in portfolio value during a specified period. It quantifies the most significant loss an investor would have experienced if they had invested at the highest point and sold at the lowest point within the timeframe. A smaller Max DD indicates better risk management and less exposure to significant losses.
Annual Mean Returns (% p/y):
This metric calculates the average annual return of the portfolio over the evaluation period. It provides insight into the portfolio's ability to generate returns on an annual basis, aiding in performance comparison with other investment opportunities.
Annual Standard Deviation of Returns (% p/y):
This measure indicates the volatility of the portfolio's returns on an annual basis. A higher standard deviation signifies greater variability in returns, implying higher risk, while a lower value suggests more stable returns.
Variance:
Variance is the square of the standard deviation and provides a measure of the dispersion of returns. It helps in understanding the degree of risk associated with the portfolio's returns.
Sortino Ratio:
The Sortino Ratio is a variation of the Sharpe Ratio that only considers downside risk, focusing on negative volatility. It is calculated as the difference between the portfolio's return and the minimum acceptable return (MAR), divided by the downside deviation. A higher Sortino Ratio indicates better risk-adjusted performance, emphasizing the importance of avoiding negative returns.
Sharpe Ratio:
The Sharpe Ratio measures the portfolio's excess return per unit of total risk, as represented by standard deviation. It is calculated by subtracting the risk-free rate from the portfolio's return and dividing by the standard deviation of the portfolio's excess return. A higher Sharpe Ratio indicates more favorable risk-adjusted returns.
Omega Ratio:
The Omega Ratio evaluates the probability of achieving returns above a certain threshold relative to the probability of experiencing returns below that threshold. It is calculated by dividing the cumulative probability of positive returns by the cumulative probability of negative returns. An Omega Ratio greater than 1 indicates a higher likelihood of achieving favorable returns.
Gain-to-Pain Ratio:
The Gain-to-Pain Ratio measures the return per unit of risk, focusing on the magnitude of gains relative to the severity of losses. It is calculated by dividing the total gains by the total losses experienced during the evaluation period. A higher ratio suggests a more favorable balance between reward and risk.
www.linkedin.com
Compound Annual Growth Rate (CAGR) (% p/y):
CAGR represents the mean annual growth rate of the portfolio over a specified period, assuming the investment has been compounding over that time. It provides a smoothed annual rate of growth, eliminating the effects of volatility and offering a clearer picture of long-term performance.
Portfolio Alpha (% p/y):
Portfolio Alpha measures the portfolio's performance relative to a benchmark index, adjusting for risk. It is calculated using the Capital Asset Pricing Model (CAPM) and represents the excess return of the portfolio over the expected return based on its beta and the benchmark's performance. A positive alpha indicates outperformance, while a negative alpha suggests underperformance.
Portfolio Beta:
Portfolio Beta assesses the portfolio's sensitivity to market movements, indicating its exposure to systematic risk. A beta greater than 1 suggests the portfolio is more volatile than the market, while a beta less than 1 indicates lower volatility. Beta is used to understand the portfolio's potential for gains or losses in relation to market fluctuations.
Skewness of Returns:
Skewness measures the asymmetry of the return distribution. A positive skew indicates a distribution with a long right tail, suggesting more frequent small losses and fewer large gains. A negative skew indicates a long left tail, implying more frequent small gains and fewer large losses. Understanding skewness helps in assessing the likelihood of extreme outcomes.
Value at Risk (VaR) 95th Percentile:
VaR at the 95th percentile estimates the maximum potential loss over a specified period, given a 95% confidence level. It provides a threshold value such that there is a 95% probability that the portfolio will not experience a loss greater than this amount.
Conditional Value at Risk (CVaR):
CVaR, also known as Expected Shortfall, measures the average loss exceeding the VaR threshold. It provides insight into the tail risk of the portfolio, indicating the expected loss in the worst-case scenarios beyond the VaR level.
These metrics collectively offer a comprehensive view of the portfolio's performance, risk exposure, and efficiency. By analyzing these indicators, investors can make informed decisions, balancing potential returns with acceptable levels of risk.
Conclusion
The Performance Metrics With Bracketed Rebalancing script provides a comprehensive framework for evaluating and optimizing portfolio performance. By integrating advanced metrics, adaptive rebalancing strategies, and visual analytics, it empowers traders to make informed decisions in managing their investment portfolios. However, it's crucial to consider the implications of rebalancing strategies, as academic research indicates that predictable rebalancing can lead to market impact costs. Therefore, adopting flexible and less predictable rebalancing approaches may enhance portfolio performance and reduce associated costs.
NP Screener with Alerts For Nifty 50 [NITIN PADALE]//@version=6
indicator('NP Screener with Alerts For Nifty 50 ', overlay = true)
////////////
// INPUTS //
filter_enabled = input.bool(false, '', group = 'Filter', inline = 'Filter')
filter_column = input.string('Price', title = 'Column', options = , group = 'Filter', inline = 'Filter')
filter_from = input.float(-9999999, 'From', group = 'Filter', inline = 'Filter')
filter_to = input.float(9999999, 'To', group = 'Filter', inline = 'Filter')
// SMA
rsi_len = input.int(14, title = 'RSI Length', group = 'Indicators')
rsi_os = input.float(30, title = 'RSI Overbought', group = 'Indicators')
rsi_ob = input.float(70, title = 'RSI Oversold', group = 'Indicators')
// TSI
tsi_long_len = input.int(25, title = 'TSI Long Length', group = 'Indicators')
tsi_shrt_len = input.int(13, title = 'TSI Short Length', group = 'Indicators')
tsi_ob = input.float(30, title = 'TSI Overbought', group = 'Indicators')
tsi_os = input.float(-30, title = 'TSI Oversold', group = 'Indicators')
// ADX Params
adx_smooth = input.int(14, title = 'ADX Smoothing', group = 'Indicators')
adx_dilen = input.int(14, title = 'ADX DI Length', group = 'Indicators')
adx_level = input.float(40, title = 'ADX Level', group = 'Indicators')
// SuperTrend
sup_atr_len = input.int(10, 'Supertrend ATR Length', group = 'Indicators')
sup_factor = input.float(3.0, 'Supertrend Factor', group = 'Indicators')
/////////////
// SYMBOLS //
u01 = input.bool(true, title = '', group = 'Symbols', inline = 's01')
u02 = input.bool(true, title = '', group = 'Symbols', inline = 's02')
u03 = input.bool(true, title = '', group = 'Symbols', inline = 's03')
u04 = input.bool(true, title = '', group = 'Symbols', inline = 's04')
u05 = input.bool(true, title = '', group = 'Symbols', inline = 's05')
u06 = input.bool(true, title = '', group = 'Symbols', inline = 's06')
u07 = input.bool(true, title = '', group = 'Symbols', inline = 's07')
u08 = input.bool(true, title = '', group = 'Symbols', inline = 's08')
u09 = input.bool(true, title = '', group = 'Symbols', inline = 's09')
u10 = input.bool(true, title = '', group = 'Symbols', inline = 's10')
s01 = input.symbol('HDFCBANK', group = 'Symbols', inline = 's01')
s02 = input.symbol('ICICIBANK', group = 'Symbols', inline = 's02')
s03 = input.symbol('RELIANCE', group = 'Symbols', inline = 's03')
s04 = input.symbol('INFY', group = 'Symbols', inline = 's04')
s05 = input.symbol('BHARTIARTL', group = 'Symbols', inline = 's05')
s06 = input.symbol('LT', group = 'Symbols', inline = 's06')
s07 = input.symbol('ITC', group = 'Symbols', inline = 's07')
s08 = input.symbol('TCS', group = 'Symbols', inline = 's08')
s09 = input.symbol('AXISBANK', group = 'Symbols', inline = 's09')
s10 = input.symbol('SBIN', group = 'Symbols', inline = 's10')
//////////////////
// CALCULATIONS //
filt_col_id = switch filter_column
'Price' => 1
'RSI' => 2
'TSI' => 3
'ADX' => 4
'SuperTrend' => 5
=> 0
// Get only symbol
only_symbol(s) =>
array.get(str.split(s, ':'), 1)
id_symbol(s) =>
switch s
1 => only_symbol(s01)
2 => only_symbol(s02)
3 => only_symbol(s03)
4 => only_symbol(s04)
5 => only_symbol(s05)
6 => only_symbol(s06)
7 => only_symbol(s07)
8 => only_symbol(s08)
9 => only_symbol(s09)
10 => only_symbol(s10)
=> na
// for TSI
double_smooth(src, long, short) =>
fist_smooth = ta.ema(src, long)
ta.ema(fist_smooth, short)
// ADX
dirmov(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
truerange = ta.rma(ta.tr, len)
plus = fixnan(100 * ta.rma(plusDM, len) / truerange)
minus = fixnan(100 * ta.rma(minusDM, len) / truerange)
adx_func(dilen, adxlen) =>
= dirmov(dilen)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
adx
screener_func() =>
// RSI
rsi = ta.rsi(close, rsi_len)
// TSI
pc = ta.change(close)
double_smoothed_pc = double_smooth(pc, tsi_long_len, tsi_shrt_len)
double_smoothed_abs_pc = double_smooth(math.abs(pc), tsi_long_len, tsi_shrt_len)
tsi = 100 * (double_smoothed_pc / double_smoothed_abs_pc)
// ADX
adx = adx_func(adx_dilen, adx_smooth)
// Supertrend
= ta.supertrend(sup_factor, sup_atr_len)
// Set Up Matrix
screenerMtx = matrix.new(0, 6, na)
screenerFun(numSym, sym, flg) =>
= request.security(sym, timeframe.period, screener_func())
arr = array.from(numSym, cl, rsi, tsi, adx, sup)
if flg
matrix.add_row(screenerMtx, matrix.rows(screenerMtx), arr)
// Security call
screenerFun(01, s01, u01)
screenerFun(02, s02, u02)
screenerFun(03, s03, u03)
screenerFun(04, s04, u04)
screenerFun(05, s05, u05)
screenerFun(06, s06, u06)
screenerFun(07, s07, u07)
screenerFun(08, s08, u08)
screenerFun(09, s09, u09)
screenerFun(10, s10, u10)
///////////
// PLOTS //
var tbl = table.new(position.top_right, 6, 41, frame_color = #151715, frame_width = 1, border_width = 2, border_color = color.new(color.white, 100))
log.info(str.tostring(filt_col_id))
alert_msg = ''
if barstate.islast
table.clear(tbl, 0, 0, 5, 40)
table.cell(tbl, 0, 0, 'Symbol', text_halign = text.align_center, bgcolor = color.gray, text_color = color.white, text_size = size.small)
table.cell(tbl, 1, 0, 'Price', text_halign = text.align_center, bgcolor = color.gray, text_color = color.white, text_size = size.small)
table.cell(tbl, 2, 0, 'RSI', text_halign = text.align_center, bgcolor = color.gray, text_color = color.white, text_size = size.small)
table.cell(tbl, 3, 0, 'TSI', text_halign = text.align_center, bgcolor = color.gray, text_color = color.white, text_size = size.small)
table.cell(tbl, 4, 0, 'ADX', text_halign = text.align_center, bgcolor = color.gray, text_color = color.white, text_size = size.small)
table.cell(tbl, 5, 0, 'Supertrend', text_halign = text.align_center, bgcolor = color.gray, text_color = color.white, text_size = size.small)
if matrix.rows(screenerMtx) > 0
for i = 0 to matrix.rows(screenerMtx) - 1 by 1
is_filt = not filter_enabled or matrix.get(screenerMtx, i, filt_col_id) >= filter_from and matrix.get(screenerMtx, i, filt_col_id) <= filter_to
if is_filt
if str.length(alert_msg) > 0
alert_msg := alert_msg + ','
alert_msg
alert_msg := alert_msg + id_symbol(matrix.get(screenerMtx, i, 0))
rsi_col = matrix.get(screenerMtx, i, 2) > rsi_ob ? color.red : matrix.get(screenerMtx, i, 2) < rsi_os ? color.green : #aaaaaa
tsi_col = matrix.get(screenerMtx, i, 3) > tsi_ob ? color.red : matrix.get(screenerMtx, i, 3) < tsi_os ? color.green : #aaaaaa
adx_col = matrix.get(screenerMtx, i, 4) > adx_level ? color.green : #aaaaaa
sup_text = matrix.get(screenerMtx, i, 5) > 0 ? 'Down' : 'Up'
sup_col = matrix.get(screenerMtx, i, 5) < 0 ? color.green : color.red
table.cell(tbl, 0, i + 1, id_symbol(matrix.get(screenerMtx, i, 0)), text_halign = text.align_left, bgcolor = color.gray, text_color = color.white, text_size = size.small)
table.cell(tbl, 1, i + 1, str.tostring(matrix.get(screenerMtx, i, 1)), text_halign = text.align_center, bgcolor = #aaaaaa, text_color = color.white, text_size = size.small)
table.cell(tbl, 2, i + 1, str.tostring(matrix.get(screenerMtx, i, 2), '#.##'), text_halign = text.align_center, bgcolor = rsi_col, text_color = color.white, text_size = size.small)
table.cell(tbl, 3, i + 1, str.tostring(matrix.get(screenerMtx, i, 3), '#.##'), text_halign = text.align_center, bgcolor = tsi_col, text_color = color.white, text_size = size.small)
table.cell(tbl, 4, i + 1, str.tostring(matrix.get(screenerMtx, i, 4), '#.##'), text_halign = text.align_center, bgcolor = adx_col, text_color = color.white, text_size = size.small)
table.cell(tbl, 5, i + 1, sup_text, text_halign = text.align_center, bgcolor = sup_col, text_color = color.white, text_size = size.small)
if str.length(alert_msg) > 0
alert(alert_msg, freq = alert.freq_once_per_bar_close)
NP Screener with Alerts//@version=5
indicator(' NP Screener with Alerts ', overlay=true)
////////////
// INPUTS //
filter_enabled = input.bool(false, "", group = "Filter", inline = "Filter")
filter_column = input.string("Price", title = "Column", options = , group = "Filter", inline = "Filter")
filter_from = input.float(-9999999, "From", group = "Filter", inline = "Filter")
filter_to = input.float(9999999, "To", group = "Filter", inline = "Filter")
// SMA
rsi_len = input.int( 14, title = "RSI Length", group = "Indicators")
rsi_os = input.float(30, title = "RSI Overbought", group = "Indicators")
rsi_ob = input.float(70, title = "RSI Oversold", group = "Indicators")
// TSI
tsi_long_len = input.int( 25, title = "TSI Long Length", group = "Indicators")
tsi_shrt_len = input.int( 13, title = "TSI Short Length", group = "Indicators")
tsi_ob = input.float( 30, title = "TSI Overbought", group = 'Indicators')
tsi_os = input.float(-30, title = "TSI Oversold", group = 'Indicators')
// ADX Params
adx_smooth = input.int( 14, title = "ADX Smoothing", group = 'Indicators')
adx_dilen = input.int( 14, title = "ADX DI Length", group = 'Indicators')
adx_level = input.float(40, title = "ADX Level", group = 'Indicators')
// SuperTrend
sup_atr_len = input.int( 10, "Supertrend ATR Length", group = 'Indicators')
sup_factor = input.float(3.0, "Supertrend Factor", group = 'Indicators')
/////////////
// SYMBOLS //
u01 = input.bool(true, title = "", group = 'Symbols', inline = 's01')
u02 = input.bool(true, title = "", group = 'Symbols', inline = 's02')
u03 = input.bool(true, title = "", group = 'Symbols', inline = 's03')
u04 = input.bool(true, title = "", group = 'Symbols', inline = 's04')
u05 = input.bool(true, title = "", group = 'Symbols', inline = 's05')
u06 = input.bool(true, title = "", group = 'Symbols', inline = 's06')
u07 = input.bool(true, title = "", group = 'Symbols', inline = 's07')
u08 = input.bool(true, title = "", group = 'Symbols', inline = 's08')
u09 = input.bool(true, title = "", group = 'Symbols', inline = 's09')
u10 = input.bool(true, title = "", group = 'Symbols', inline = 's10')
u11 = input.bool(true, title = "", group = 'Symbols', inline = 's11')
u12 = input.bool(true, title = "", group = 'Symbols', inline = 's12')
u13 = input.bool(true, title = "", group = 'Symbols', inline = 's13')
u14 = input.bool(true, title = "", group = 'Symbols', inline = 's14')
u15 = input.bool(true, title = "", group = 'Symbols', inline = 's15')
u16 = input.bool(true, title = "", group = 'Symbols', inline = 's16')
u17 = input.bool(true, title = "", group = 'Symbols', inline = 's17')
u18 = input.bool(true, title = "", group = 'Symbols', inline = 's18')
u19 = input.bool(true, title = "", group = 'Symbols', inline = 's19')
u20 = input.bool(true, title = "", group = 'Symbols', inline = 's20')
u21 = input.bool(true, title = "", group = 'Symbols', inline = 's21')
u22 = input.bool(true, title = "", group = 'Symbols', inline = 's22')
u23 = input.bool(true, title = "", group = 'Symbols', inline = 's23')
u24 = input.bool(true, title = "", group = 'Symbols', inline = 's24')
u25 = input.bool(true, title = "", group = 'Symbols', inline = 's25')
u26 = input.bool(true, title = "", group = 'Symbols', inline = 's26')
u27 = input.bool(true, title = "", group = 'Symbols', inline = 's27')
u28 = input.bool(true, title = "", group = 'Symbols', inline = 's28')
u29 = input.bool(true, title = "", group = 'Symbols', inline = 's29')
u30 = input.bool(true, title = "", group = 'Symbols', inline = 's30')
u31 = input.bool(true, title = "", group = 'Symbols', inline = 's31')
u32 = input.bool(true, title = "", group = 'Symbols', inline = 's32')
u33 = input.bool(true, title = "", group = 'Symbols', inline = 's33')
u34 = input.bool(true, title = "", group = 'Symbols', inline = 's34')
u35 = input.bool(true, title = "", group = 'Symbols', inline = 's35')
u36 = input.bool(false, title = "", group = 'Symbols', inline = 's36')
u37 = input.bool(false, title = "", group = 'Symbols', inline = 's37')
u38 = input.bool(false, title = "", group = 'Symbols', inline = 's38')
u39 = input.bool(false, title = "", group = 'Symbols', inline = 's39')
u40 = input.bool(false, title = "", group = 'Symbols', inline = 's40')
s01 = input.symbol('XRPUSDT', group = 'Symbols', inline = 's01')
s02 = input.symbol('BTCUSDT', group = 'Symbols', inline = 's02')
s03 = input.symbol('DOGEUSDT', group = 'Symbols', inline = 's03')
s04 = input.symbol('BNBUSDT', group = 'Symbols', inline = 's04')
s05 = input.symbol('ETHUSDT', group = 'Symbols', inline = 's05')
s06 = input.symbol('ADAUSDT', group = 'Symbols', inline = 's06')
s07 = input.symbol('XRPBTC', group = 'Symbols', inline = 's07')
s08 = input.symbol('DOGEBTC', group = 'Symbols', inline = 's08')
s09 = input.symbol('TRXUSDT', group = 'Symbols', inline = 's09')
s10 = input.symbol('XRPUSDT', group = 'Symbols', inline = 's10')
s11 = input.symbol('BTCUSDT', group = 'Symbols', inline = 's11')
s12 = input.symbol('DOGEUSDT', group = 'Symbols', inline = 's12')
s13 = input.symbol('VETUSDT', group = 'Symbols', inline = 's13')
s14 = input.symbol('ETHBTC', group = 'Symbols', inline = 's14')
s15 = input.symbol('BNBBTC', group = 'Symbols', inline = 's15')
s16 = input.symbol('EOSUSDT', group = 'Symbols', inline = 's16')
s17 = input.symbol('XLMUSDT', group = 'Symbols', inline = 's17')
s18 = input.symbol('LTCUSDT', group = 'Symbols', inline = 's18')
s19 = input.symbol('DOGEBTC', group = 'Symbols', inline = 's19')
s20 = input.symbol('WINUSDT', group = 'Symbols', inline = 's20')
s21 = input.symbol('DOTUSDT', group = 'Symbols', inline = 's21')
s22 = input.symbol('VETUSDT', group = 'Symbols', inline = 's22')
s23 = input.symbol('BCHUSDT', group = 'Symbols', inline = 's23')
s24 = input.symbol('ADABTC', group = 'Symbols', inline = 's24')
s25 = input.symbol('IOSTUSDT', group = 'Symbols', inline = 's25')
s26 = input.symbol('CHZUSDT', group = 'Symbols', inline = 's26')
s27 = input.symbol('LINKUSDT', group = 'Symbols', inline = 's27')
s28 = input.symbol('TRXBTC', group = 'Symbols', inline = 's28')
s29 = input.symbol('ATOMUSDT', group = 'Symbols', inline = 's29')
s30 = input.symbol('BTCEUR', group = 'Symbols', inline = 's30')
s31 = input.symbol('FILUSDT', group = 'Symbols', inline = 's31')
s32 = input.symbol('HOTUSDT', group = 'Symbols', inline = 's32')
s33 = input.symbol('SXPUSDT', group = 'Symbols', inline = 's33')
s34 = input.symbol('TRXBTC', group = 'Symbols', inline = 's34')
s35 = input.symbol('RVNUSDT', group = 'Symbols', inline = 's35')
s36 = input.symbol('ATOMUSDT', group = 'Symbols', inline = 's36')
s37 = input.symbol('XRPBNB', group = 'Symbols', inline = 's37')
s38 = input.symbol('LTCBTC', group = 'Symbols', inline = 's38')
s39 = input.symbol('IOSTBTC', group = 'Symbols', inline = 's39')
s40 = input.symbol('GRTUSDT', group = 'Symbols', inline = 's40')
//////////////////
// CALCULATIONS //
filt_col_id = switch filter_column
'Price' => 1
'RSI' => 2
'TSI' => 3
'ADX' => 4
'SuperTrend' => 5
=> 0
// Get only symbol
only_symbol(s) =>
array.get(str.split(s, ":"), 1)
id_symbol(s)=>
switch s
1 => only_symbol(s01)
2 => only_symbol(s02)
3 => only_symbol(s03)
4 => only_symbol(s04)
5 => only_symbol(s05)
6 => only_symbol(s06)
7 => only_symbol(s07)
8 => only_symbol(s08)
9 => only_symbol(s09)
10 => only_symbol(s10)
11 => only_symbol(s11)
12 => only_symbol(s12)
13 => only_symbol(s13)
14 => only_symbol(s14)
15 => only_symbol(s15)
16 => only_symbol(s16)
17 => only_symbol(s17)
18 => only_symbol(s18)
19 => only_symbol(s19)
20 => only_symbol(s20)
21 => only_symbol(s21)
22 => only_symbol(s22)
23 => only_symbol(s23)
24 => only_symbol(s24)
25 => only_symbol(s25)
26 => only_symbol(s26)
27 => only_symbol(s27)
28 => only_symbol(s28)
29 => only_symbol(s29)
30 => only_symbol(s30)
31 => only_symbol(s31)
32 => only_symbol(s32)
33 => only_symbol(s33)
34 => only_symbol(s34)
35 => only_symbol(s35)
36 => only_symbol(s36)
37 => only_symbol(s37)
38 => only_symbol(s38)
39 => only_symbol(s39)
40 => only_symbol(s40)
=> na
// for TSI
double_smooth(src, long, short) =>
fist_smooth = ta.ema(src, long)
ta.ema(fist_smooth, short)
// ADX
dirmov(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)
truerange = ta.rma(ta.tr, len)
plus = fixnan(100 * ta.rma(plusDM, len) / truerange)
minus = fixnan(100 * ta.rma(minusDM, len) / truerange)
adx_func(dilen, adxlen) =>
= dirmov(dilen)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
screener_func() =>
// RSI
rsi = ta.rsi(close, rsi_len)
// TSI
pc = ta.change(close)
double_smoothed_pc = double_smooth(pc, tsi_long_len, tsi_shrt_len)
double_smoothed_abs_pc = double_smooth(math.abs(pc), tsi_long_len, tsi_shrt_len)
tsi = 100 * (double_smoothed_pc / double_smoothed_abs_pc)
// ADX
adx = adx_func(adx_dilen, adx_smooth)
// Supertrend
= ta.supertrend(sup_factor, sup_atr_len)
// Set Up Matrix
screenerMtx = matrix.new(0, 6, na)
screenerFun(numSym, sym, flg) =>
= request.security(sym, timeframe.period, screener_func())
arr = array.from(numSym, cl, rsi, tsi, adx, sup)
if flg
matrix.add_row(screenerMtx, matrix.rows(screenerMtx), arr)
// Security call
screenerFun(01, s01, u01), screenerFun(02, s02, u02), screenerFun(03, s03, u03), screenerFun(04, s04, u04),
screenerFun(05, s05, u05), screenerFun(06, s06, u06), screenerFun(07, s07, u07), screenerFun(08, s08, u08),
screenerFun(09, s09, u09), screenerFun(10, s10, u10), screenerFun(11, s11, u11), screenerFun(12, s12, u12),
screenerFun(13, s13, u13), screenerFun(14, s14, u14), screenerFun(15, s15, u15), screenerFun(16, s16, u16),
screenerFun(17, s17, u17), screenerFun(18, s18, u18), screenerFun(19, s19, u19), screenerFun(20, s20, u20),
screenerFun(21, s21, u21), screenerFun(22, s22, u22), screenerFun(23, s23, u23), screenerFun(24, s24, u24),
screenerFun(25, s25, u25), screenerFun(26, s26, u26), screenerFun(27, s27, u27), screenerFun(28, s28, u28),
screenerFun(29, s29, u29), screenerFun(30, s30, u30), screenerFun(31, s31, u31), screenerFun(32, s32, u32),
screenerFun(33, s33, u33), screenerFun(34, s34, u34), screenerFun(35, s35, u35), screenerFun(36, s36, u36),
screenerFun(37, s37, u37), screenerFun(38, s38, u38), screenerFun(39, s39, u39), screenerFun(40, s40, u40),
///////////
// PLOTS //
var tbl = table.new(position.top_right, 6, 41, frame_color=#151715, frame_width=1, border_width=2, border_color=color.new(color.white, 100))
log.info(str.tostring(filt_col_id))
alert_msg = ''
if barstate.islast
table.clear(tbl, 0, 0, 5, 40)
table.cell(tbl, 0, 0, 'Symbol', text_halign = text.align_center, bgcolor = color.gray, text_color = color.white, text_size = size.small)
table.cell(tbl, 1, 0, 'Price', text_halign = text.align_center, bgcolor = color.gray, text_color = color.white, text_size = size.small)
table.cell(tbl, 2, 0, 'RSI', text_halign = text.align_center, bgcolor = color.gray, text_color = color.white, text_size = size.small)
table.cell(tbl, 3, 0, 'TSI', text_halign = text.align_center, bgcolor = color.gray, text_color = color.white, text_size = size.small)
table.cell(tbl, 4, 0, 'ADX', text_halign = text.align_center, bgcolor = color.gray, text_color = color.white, text_size = size.small)
table.cell(tbl, 5, 0, 'Supertrend', text_halign = text.align_center, bgcolor = color.gray, text_color = color.white, text_size = size.small)
if matrix.rows(screenerMtx) > 0
for i = 0 to matrix.rows(screenerMtx) - 1
is_filt = (not filter_enabled) or (matrix.get(screenerMtx, i, filt_col_id) >= filter_from and matrix.get(screenerMtx, i, filt_col_id) <= filter_to)
if is_filt
if str.length(alert_msg) > 0
alert_msg := alert_msg + ','
alert_msg := alert_msg + id_symbol(matrix.get(screenerMtx, i, 0))
rsi_col = matrix.get(screenerMtx, i, 2) > rsi_ob ? color.red : matrix.get(screenerMtx, i, 2) < rsi_os ? color.green : #aaaaaa
tsi_col = matrix.get(screenerMtx, i, 3) > tsi_ob ? color.red : matrix.get(screenerMtx, i, 3) < tsi_os ? color.green : #aaaaaa
adx_col = matrix.get(screenerMtx, i, 4) > adx_level ? color.green : #aaaaaa
sup_text = matrix.get(screenerMtx, i, 5) > 0 ? "Down" : "Up"
sup_col = matrix.get(screenerMtx, i, 5) < 0 ? color.green : color.red
table.cell(tbl, 0, i + 1, id_symbol(matrix.get(screenerMtx, i, 0)), text_halign = text.align_left, bgcolor = color.gray, text_color = color.white, text_size = size.small)
table.cell(tbl, 1, i + 1, str.tostring(matrix.get(screenerMtx, i, 1)), text_halign = text.align_center, bgcolor = #aaaaaa, text_color = color.white, text_size = size.small)
table.cell(tbl, 2, i + 1, str.tostring(matrix.get(screenerMtx, i, 2), "#.##"), text_halign = text.align_center, bgcolor = rsi_col, text_color = color.white, text_size = size.small)
table.cell(tbl, 3, i + 1, str.tostring(matrix.get(screenerMtx, i, 3), "#.##"), text_halign = text.align_center, bgcolor = tsi_col, text_color = color.white, text_size = size.small)
table.cell(tbl, 4, i + 1, str.tostring(matrix.get(screenerMtx, i, 4), "#.##"), text_halign = text.align_center, bgcolor = adx_col , text_color = color.white, text_size = size.small)
table.cell(tbl, 5, i + 1, sup_text, text_halign = text.align_center, bgcolor = sup_col, text_color = color.white, text_size = size.small)
if str.length(alert_msg) > 0
alert(alert_msg, freq = alert.freq_once_per_bar_close)
SDCALibraryMy Valuation Library for mostly crypto currency use, but some can be applied to other assets.
There are technical and on-chain indicator functions for use.
Technical Indicators:
1. **drawdown_zscore**
- **Summary**: Calculates the z-score of drawdowns over a specified lookback period.
- **Inputs**:
- `lookback_length` (int): Period for drawdown calculation.
- `zScoreLen` (int): Length for z-score calculation.
2. **sharpe_zscore**
- **Summary**: Computes the z-score of the Sharpe ratio using returns over a period and a smoothing length.
- **Inputs**:
- `length` (int): Period for returns calculation.
- `smalen` (int): Smoothing length for returns.
- `zScoreLen` (int): Length for z-score calculation.
3. **rsi_zscore**
- **Summary**: Calculates the z-score of the Relative Strength Index (RSI) with smoothing.
- **Inputs**:
- `length` (int): Period for RSI calculation.
- `smalen` (int): Smoothing length for RSI.
- `zScoreLen` (int): Length for z-score calculation.
4. **DFATH_zscore**
- **Summary**: Computes the z-score for a specific DFATH metric (details not specified).
- **Inputs**:
- `zScoreLen` (int): Length for z-score calculation.
5. **RTI_zscore**
- **Summary**: Calculates the z-score of a trend indicator based on data count and sensitivity.
- **Inputs**:
- `trend_data_count` (int): Number of data points for trend analysis.
- `trend_sensitivity_percentage` (int): Sensitivity threshold for trend detection.
- `zScoreLen` (int): Length for z-score calculation.
On-Chain (Crypto only, mostly BTC, ETH)
6. **SOPR_zscore**
- **Summary**: Computes the z-score of Spent Output Profit Ratio (SOPR) for a specific coin.
- **Inputs**:
- `zScoreLen` (int): Length for z-score calculation.
- `coin_sopr` (string): SOPR data for the specified coin.
7. **thermocap_zscore**
- **Summary**: Calculates the z-score of the Thermocap metric using moving average and coin-specific data.
- **Inputs**:
- `ma_len` (int): Length of the moving average.
- `ma_type` (string): Type of moving average.
- `zScoreLen` (int): Length for z-score calculation.
- `coin_index` (string): Coin index data.
- `coin_blocks_mined` (string): Data on blocks mined for the coin.
8. **MVRV_zscore**
- **Summary**: Computes the z-score of the Market Value to Realized Value (MVRV) ratio.
- **Inputs**:
- `zScoreLen` (int): Length for z-score calculation.
- `coin_MC` (string): Market capitalization data.
- `coin_MC_real` (string): Realized market capitalization data.
9. **supplyinprofit_zscore**
- **Summary**: Calculates the z-score of the percentage of coin supply in profit or loss, optionally adjusted for alpha decay.
- **Inputs**:
- `isAlphaDecayAdjusted` (bool): Whether to apply alpha decay adjustment.
- `zScoreLen` (int): Length for z-score calculation.
- `coin_profit_address_percent` (string): Percentage of addresses in profit.
- `coin_loss_address_percent` (string): Percentage of addresses in loss.
10. **realized_price_zscore**
- **Summary**: Computes the z-score of the realized price based on realized market cap and supply.
- **Inputs**:
- `zScoreLen` (int): Length for z-score calculation.
- `coin_MC_real` (string): Realized market capitalization data.
- `coin_supply` (string): Coin supply data.
11. **CVVD_zscore**
- **Summary**: Calculates the z-score of Cumulative Value Days Destroyed (CVVD) metric.
- **Inputs**:
- `zScoreLen` (int): Length for z-score calculation.
- `coin_MC_real` (string): Realized market capitalization data.
- `coin_total_volume` (string): Total volume data for the coin.
12. **NUPL_zscore**
- **Summary**: Computes the z-score of Net Unrealized Profit and Loss (NUPL) metric.
- **Inputs**:
- `zScoreLen` (int): Length for z-score calculation.
- `coin_MC` (string): Market capitalization data.
- `coin_MC_real` (string): Realized market capitalization data.
Simple Position CalculatorThis indicator provides a real-time position sizing calculator designed for fast momentum trading. It instantly calculates optimal trade size based on your risk parameters, entry/exit prices, and exchange conditions (fees/slippage). Perfect for high-speed entries during candle closes and breakouts.
SUPER-MAGFLXMAGFLX
Made a bunch of these for different sectors, then realized they’re all basically the same—so you really only need one.
Here it is, with a few extra features like customizable display position and metric options.
Track 1 to 20+ tickers, your way, all in one clean, versatile template.
Features & Uses
Custom Ticker List: Enter any tickers you want to track—mix and match sectors or asset classes freely.
Flexible Display: Choose where the table appears on your chart (top-right, top-left, bottom-right, bottom-left).
Metric Options: Toggle on/off daily percentage change, current price, and price difference columns based on what you want to monitor.
Highlight Movers: Automatically spot and highlight the biggest gainer and biggest loser each day for quick insights.
Compact & Efficient: Fits neatly on your chart without clutter, whether tracking 1 ticker or 20+.
Color-Coded Data: Intuitive colors make it easy to spot gains, losses, and key movers at a glance.
User-Friendly: No coding needed—simply input your tickers and preferences to tailor your watchlist instantly.
Use it to:
Monitor your portfolio across multiple sectors in one place.
Quickly spot daily winners and losers.
Keep an eye on price trends and changes without opening multiple charts.
Save chart space while gaining market clarity.
Any comments welcomed there is no way to tell if a public script is being used right ? so if you use and like it give it boost or a comment to let me know
Portfolio Dashboard by DTRThe Portfolio Dashboard by DTR is a sophisticated yet user-friendly Pine Script indicator for TradingView, designed to empower traders with a comprehensive tool for managing and monitoring investment portfolios. Supporting up to 10 stocks, it delivers real-time performance metrics, risk analysis, and market insights in an intuitive, customizable dashboard—perfect for traders of all experience levels.
Key Features
Real-Time Portfolio Metrics: Tracks Return on Investment (ROI), Day's Profit and Loss (PNL), Risk of Profit (ROP), and Average Daily Range (ADR) with color-coded indicators for quick insights.
Individual Stock Insights: Displays detailed data for each stock, including ticker, trading setup, Last Traded Price (LTP) or Stop Loss (SL) status, position size, risk, portfolio risk, Risk-Reward (RR) or Gain%, daily change%, portfolio impact, and optional ADR.
Market Condition Analysis: Evaluates broader market trends using NSE:CNXSMALLCAP data, categorizing conditions as CHOPPY, BULL MARKET, BEAR MARKET, SHAKEOUT, or BEAR RALLY with visual color cues.
Customization Options:
Input total capital (scalable in Thousands, Lacs, or Crores) and maximum risk percentage.
Choose from B&W, Blue, Green, Red, Purple, or Transparent themes, with Dark Mode support.
Adjust dashboard and gauge positions (top/middle/bottom, left/center/right) and text sizes (tiny to huge).
Toggle display options like LTP, % change color, total row, ADR column, RR/Gain%, and empty rows.
Risk Management Tools: Calculates position sizes, individual and portfolio-level risks, and offers visual gauges for total allocation (% invested) and open risk (% of max risk). Supports setting Stop Loss to Break-Even (SL=BE).
Chart Enhancements: Optionally displays entry and stop loss lines on the chart with customizable styles (Dashed, Dotted, Normal) and dynamic labels for precise trade management.
How It Works
Setup: Users input portfolio details—ticker symbols, quantities, entry prices, stop losses, exits, and setups—for up to 10 stocks, along with capital and risk settings.
Data Processing: The indicator fetches daily high, low, close, and previous close data to compute metrics like ADR, percentage change, and Day's PNL for each stock.
Visualization: On the last bar, it generates a detailed table summarizing portfolio and stock-level data, alongside two gauges for allocation and risk, positioned per user preferences.
Chart Integration: When enabled, entry and SL lines with labels appear on the chart for the current ticker, updating dynamically based on price action.
How to Use
Add to Chart: Apply the indicator to your TradingView chart.
Configure Settings: In the settings panel, enter your total capital, stock details, and customize themes, positions, and display preferences.
Monitor Portfolio: Use the dashboard to assess portfolio health, risk exposure, and market conditions in real time.
Manage Trades: Leverage chart lines and labels to execute and adjust trades with precision.
Benefits
Centralized Oversight: Consolidates all essential portfolio data into one view.
Enhanced Risk Control: Provides real-time risk metrics and visual tools for proactive management.
Flexible Design: Adapts to various trading strategies and aesthetic preferences.
Intuitive Interface: Combines detailed analytics with clear, visually appealing presentation.
Important Notes
Accuracy: Ensure correct ticker symbols (e.g., NSE:RELIANCE) and price inputs for reliable results.
Timeframes: Optimized for daily or intraday charts; updates occur on the last bar.
Dependencies: Market condition and ADR calculations rely on NSE:CNXSMALLCAP data availability.
Elevate your trading with the Portfolio Dashboard by DTR—a powerful, all-in-one solution for portfolio management on TradingView. Take control of your investments today!
Cross-Sectional Altcoin Portfolio [BackQuant]Cross-Sectional Altcoin Portfolio
Introducing BackQuant's Cross-Sectional Altcoin Portfolio, a sophisticated trading system designed to dynamically rotate among a selection of major altcoins. This portfolio strategy compares multiple assets based on real-time performance metrics, such as momentum and trend strength, to select the strongest-performing coins. It uses a combination of adaptive scoring and regime filters to ensure the portfolio is aligned with favorable market conditions, minimizing exposure during unfavorable trends.
This system offers a comprehensive solution for crypto traders who want to optimize portfolio allocation based on cross-asset performance, while also accounting for market regimes. It allows traders to compare multiple altcoins dynamically and allocate capital to the top performers, ensuring the portfolio is always positioned in the most promising assets.
Key Features
1. Dynamic Asset Rotation:
The portfolio constantly evaluates the relative strength of 10 major altcoins: SOLUSD, RUNEUSD, ORDIUSD, DOGEUSDT, ETHUSD, ENAUSDT, RAYUSDT, PENDLEUSD, UNIUSD, and KASUSDT.
Using a ratio matrix, the system selects the strongest asset based on momentum and trend performance, dynamically adjusting the allocation as market conditions change.
2. Long-Only Portfolio with Cash Reserve:
The portfolio only takes long positions or remains in cash. The system does not enter short positions, reducing the risk of exposure during market downturns.
A powerful regime filter ensures the system is inactive during periods of market weakness, defined by the Universal Trend Performance Indicator (TPI) and other market data.
3. Equity Tracking:
The script provides real-time visualizations of portfolio equity compared to buy-and-hold strategies.
Users can compare the performance of the portfolio against holding individual assets (e.g., BTC, ETH) and see the benefits of the dynamic allocation.
4. Performance Metrics:
The system provides key performance metrics such as:
Sharpe Ratio: Measures risk-adjusted returns.
Sortino Ratio: Focuses on downside risk.
Omega Ratio: Evaluates returns relative to risk.
Maximum Drawdown: The maximum observed loss from a peak to a trough.
These metrics allow traders to assess the effectiveness of the strategy versus simply holding the assets.
5. Regime Filter:
The system incorporates a regime filter that evaluates the overall market trend using the TPI and other indicators. If the market is in a downtrend, the system exits positions and moves to cash, avoiding exposure to negative market conditions.
Users can customize the thresholds for the long and short trends to fit their risk tolerance.
6. Customizable Parameters:
Traders can adjust key parameters, such as the backtest start date, starting capital, leverage multiplier, and visualization options, including equity plot colors and line widths.
The system supports different levels of customizations for traders to optimize their strategies.
7. Equity and Buy-and-Hold Comparisons:
This script enables traders to see the side-by-side comparison of the portfolio’s equity curve and the equity curve of a buy-and-hold strategy for each asset.
The comparison allows users to evaluate the performance of the dynamic strategy versus holding the altcoins in isolation.
8. Forward Test (Out-of-Sample Testing):
The system includes a note that the portfolio provides out-of-sample forward tests, ensuring the robustness of the strategy. This is crucial for assessing the portfolio's performance beyond historical backtesting and validating its ability to adapt to future market conditions.
9. Visual Feedback:
The system offers detailed visual feedback on the current asset allocation and performance. Candles are painted according to the trend of the selected assets, and key metrics are displayed in real-time, including the momentum scores for each asset.
10. Alerts and Notifications:
Real-time alerts notify traders when the system changes asset allocations or moves to cash, ensuring they stay informed about portfolio adjustments.
Visual labels on the chart provide instant feedback on which asset is currently leading the portfolio allocation.
How the Rotation Works
The portfolio evaluates 10 different assets and calculates a momentum score for each based on their price action. This score is processed through a ratio matrix, which compares the relative performance of each asset.
Based on the rankings, the portfolio allocates capital to the top performers, ensuring it rotates between the strongest assets while minimizing exposure to underperforming assets.
If no asset shows strong performance, the system defaults to cash to preserve capital.
Final Thoughts
BackQuant’s Cross-Sectional Altcoin Portfolio provides a dynamic and systematic approach to altcoin portfolio management. By employing real-time performance metrics, adaptive scoring, and regime filters, this strategy aims to optimize returns while minimizing exposure to market downturns. The inclusion of out-of-sample forward tests ensures that the system remains robust in live market conditions, making it an ideal tool for crypto traders seeking to enhance their portfolio's performance with a data-driven, momentum-based approach.
Momentum Pullback SignalThunderPancake's momentum pullback to be used with support/resistance leves, >2:1 R/R, Volume indicator and ATR/ADR for stops.
Session HighlightsCrypto relevant global equity market open/close indicator, high opacity background highlights follow the following color scheme & daily time ranges (times in EST):
Orange: 8:00 PM to 9:30 PM (Sunday - Thursday): Japan/South Korea
Yellow: 9:30 PM to +1D 4:00 AM (Sunday - Thursday): Hong Kong
Aqua: 8:00 AM to 9:30 AM (Monday - Friday): US Premarket / Macro Data Release
Blue: 9:30 AM to 4:00 PM (Monday - Friday): US
White: 4:00 PM to +2D 6:00 PM (Friday - Sunday): Weekend
*Market Holidays not accounted for
The Green MachineThe Green Machine
The Green Machine is a trend-following strategy that uses a dynamic, volatility-based trailing stop to manage positions. It automatically flips between long and short positions based on market behavior, aiming to ride trends while cutting losses early.
🔍 Strategy Logic
A trailing stop is calculated using historical volatility.
When price breaches the trailing stop, the strategy closes the position and opens a trade in the opposite direction.
Each new position resets the trailing logic based on current price conditions.
This strategy does not use external indicators; it relies solely on statistical volatility for dynamic stop adjustment.
⚙️ Default Strategy Settings
Account Size: $10,000
Risk per Trade: 1% of equity
Commission: 0.1% per trade (applied via strategy() settings)
Slippage: 1 tick per trade
Backtest Dataset: All available data on selected timeframe
Minimum Trades Required: 100+ for statistical evaluation
These assumptions reflect common retail trading conditions and are intended to present realistic results.
📈 Best Use Cases
Trending markets (e.g., crypto, forex, momentum stocks)
Timeframes: Works best on 15m–4h for active trading, daily for swing setups
Can be paired with other entry filters (like RSI, MA crossovers, or volume-based entries)
⚠️ Important Notes
The script flips bias automatically; it is not intended for manual trade confirmation.
Use in demo/backtest mode first to understand the behavior.
All logic and calculations are embedded directly in the script. No external dependencies.
This script is provided for educational and research purposes. Past performance is not indicative of future results. Always test thoroughly before using in live environments.
Kappa Weighted IndexI have created an indicator with options to select if you invested in separate stocks to get one price index I hope you will find helpful.
Any questions on that please give me a shout
Risk-Adjusted Momentum Oscillator# Risk-Adjusted Momentum Oscillator (RAMO): Momentum Analysis with Integrated Risk Assessment
## 1. Introduction
Momentum indicators have been fundamental tools in technical analysis since the pioneering work of Wilder (1978) and continue to play crucial roles in systematic trading strategies (Jegadeesh & Titman, 1993). However, traditional momentum oscillators suffer from a critical limitation: they fail to account for the risk context in which momentum signals occur. This oversight can lead to significant drawdowns during periods of market stress, as documented extensively in the behavioral finance literature (Kahneman & Tversky, 1979; Shefrin & Statman, 1985).
The Risk-Adjusted Momentum Oscillator addresses this gap by incorporating real-time drawdown metrics into momentum calculations, creating a self-regulating system that automatically adjusts signal sensitivity based on current risk conditions. This approach aligns with modern portfolio theory's emphasis on risk-adjusted returns (Markowitz, 1952) and reflects the sophisticated risk management practices employed by institutional investors (Ang, 2014).
## 2. Theoretical Foundation
### 2.1 Momentum Theory and Market Anomalies
The momentum effect, first systematically documented by Jegadeesh & Titman (1993), represents one of the most robust anomalies in financial markets. Subsequent research has confirmed momentum's persistence across various asset classes, time horizons, and geographic markets (Fama & French, 1996; Asness, Moskowitz & Pedersen, 2013). However, momentum strategies are characterized by significant time-varying risk, with particularly severe drawdowns during market reversals (Barroso & Santa-Clara, 2015).
### 2.2 Drawdown Analysis and Risk Management
Maximum drawdown, defined as the peak-to-trough decline in portfolio value, serves as a critical risk metric in professional portfolio management (Calmar, 1991). Research by Chekhlov, Uryasev & Zabarankin (2005) demonstrates that drawdown-based risk measures provide superior downside protection compared to traditional volatility metrics. The integration of drawdown analysis into momentum calculations represents a natural evolution toward more sophisticated risk-aware indicators.
### 2.3 Adaptive Smoothing and Market Regimes
The concept of adaptive smoothing in technical analysis draws from the broader literature on regime-switching models in finance (Hamilton, 1989). Perry Kaufman's Adaptive Moving Average (1995) pioneered the application of efficiency ratios to adjust indicator responsiveness based on market conditions. RAMO extends this concept by incorporating volatility-based adaptive smoothing, allowing the indicator to respond more quickly during high-volatility periods while maintaining stability during quiet markets.
## 3. Methodology
### 3.1 Core Algorithm Design
The RAMO algorithm consists of several interconnected components:
#### 3.1.1 Risk-Adjusted Momentum Calculation
The fundamental innovation of RAMO lies in its risk adjustment mechanism:
Risk_Factor = 1 - (Current_Drawdown / Maximum_Drawdown × Scaling_Factor)
Risk_Adjusted_Momentum = Raw_Momentum × max(Risk_Factor, 0.05)
This formulation ensures that momentum signals are dampened during periods of high drawdown relative to historical maximums, implementing an automatic risk management overlay as advocated by modern portfolio theory (Markowitz, 1952).
#### 3.1.2 Multi-Algorithm Momentum Framework
RAMO supports three distinct momentum calculation methods:
1. Rate of Change: Traditional percentage-based momentum (Pring, 2002)
2. Price Momentum: Absolute price differences
3. Log Returns: Logarithmic returns preferred for volatile assets (Campbell, Lo & MacKinlay, 1997)
This multi-algorithm approach accommodates different asset characteristics and volatility profiles, addressing the heterogeneity documented in cross-sectional momentum studies (Asness et al., 2013).
### 3.2 Leading Indicator Components
#### 3.2.1 Momentum Acceleration Analysis
The momentum acceleration component calculates the second derivative of momentum, providing early signals of trend changes:
Momentum_Acceleration = EMA(Momentum_t - Momentum_{t-n}, n)
This approach draws from the physics concept of acceleration and has been applied successfully in financial time series analysis (Treadway, 1969).
#### 3.2.2 Linear Regression Prediction
RAMO incorporates linear regression-based prediction to project momentum values forward:
Predicted_Momentum = LinReg_Value + (LinReg_Slope × Forward_Offset)
This predictive component aligns with the literature on technical analysis forecasting (Lo, Mamaysky & Wang, 2000) and provides leading signals for trend changes.
#### 3.2.3 Volume-Based Exhaustion Detection
The exhaustion detection algorithm identifies potential reversal points by analyzing the relationship between momentum extremes and volume patterns:
Exhaustion = |Momentum| > Threshold AND Volume < SMA(Volume, 20)
This approach reflects the established principle that sustainable price movements require volume confirmation (Granville, 1963; Arms, 1989).
### 3.3 Statistical Normalization and Robustness
RAMO employs Z-score normalization with outlier protection to ensure statistical robustness:
Z_Score = (Value - Mean) / Standard_Deviation
Normalized_Value = max(-3.5, min(3.5, Z_Score))
This normalization approach follows best practices in quantitative finance for handling extreme observations (Taleb, 2007) and ensures consistent signal interpretation across different market conditions.
### 3.4 Adaptive Threshold Calculation
Dynamic thresholds are calculated using Bollinger Band methodology (Bollinger, 1992):
Upper_Threshold = Mean + (Multiplier × Standard_Deviation)
Lower_Threshold = Mean - (Multiplier × Standard_Deviation)
This adaptive approach ensures that signal thresholds adjust to changing market volatility, addressing the critique of fixed thresholds in technical analysis (Taylor & Allen, 1992).
## 4. Implementation Details
### 4.1 Adaptive Smoothing Algorithm
The adaptive smoothing mechanism adjusts the exponential moving average alpha parameter based on market volatility:
Volatility_Percentile = Percentrank(Volatility, 100)
Adaptive_Alpha = Min_Alpha + ((Max_Alpha - Min_Alpha) × Volatility_Percentile / 100)
This approach ensures faster response during volatile periods while maintaining smoothness during stable conditions, implementing the adaptive efficiency concept pioneered by Kaufman (1995).
### 4.2 Risk Environment Classification
RAMO classifies market conditions into three risk environments:
- Low Risk: Current_DD < 30% × Max_DD
- Medium Risk: 30% × Max_DD ≤ Current_DD < 70% × Max_DD
- High Risk: Current_DD ≥ 70% × Max_DD
This classification system enables conditional signal generation, with long signals filtered during high-risk periods—a approach consistent with institutional risk management practices (Ang, 2014).
## 5. Signal Generation and Interpretation
### 5.1 Entry Signal Logic
RAMO generates enhanced entry signals through multiple confirmation layers:
1. Primary Signal: Crossover between indicator and signal line
2. Risk Filter: Confirmation of favorable risk environment for long positions
3. Leading Component: Early warning signals via acceleration analysis
4. Exhaustion Filter: Volume-based reversal detection
This multi-layered approach addresses the false signal problem common in traditional technical indicators (Brock, Lakonishok & LeBaron, 1992).
### 5.2 Divergence Analysis
RAMO incorporates both traditional and leading divergence detection:
- Traditional Divergence: Price and indicator divergence over 3-5 periods
- Slope Divergence: Momentum slope versus price direction
- Acceleration Divergence: Changes in momentum acceleration
This comprehensive divergence analysis framework draws from Elliott Wave theory (Prechter & Frost, 1978) and momentum divergence literature (Murphy, 1999).
## 6. Empirical Advantages and Applications
### 6.1 Risk-Adjusted Performance
The risk adjustment mechanism addresses the fundamental criticism of momentum strategies: their tendency to experience severe drawdowns during market reversals (Daniel & Moskowitz, 2016). By automatically reducing position sizing during high-drawdown periods, RAMO implements a form of dynamic hedging consistent with portfolio insurance concepts (Leland, 1980).
### 6.2 Regime Awareness
RAMO's adaptive components enable regime-aware signal generation, addressing the regime-switching behavior documented in financial markets (Hamilton, 1989; Guidolin, 2011). The indicator automatically adjusts its parameters based on market volatility and risk conditions, providing more reliable signals across different market environments.
### 6.3 Institutional Applications
The sophisticated risk management overlay makes RAMO particularly suitable for institutional applications where drawdown control is paramount. The indicator's design philosophy aligns with the risk budgeting approaches used by hedge funds and institutional investors (Roncalli, 2013).
## 7. Limitations and Future Research
### 7.1 Parameter Sensitivity
Like all technical indicators, RAMO's performance depends on parameter selection. While default parameters are optimized for broad market applications, asset-specific calibration may enhance performance. Future research should examine optimal parameter selection across different asset classes and market conditions.
### 7.2 Market Microstructure Considerations
RAMO's effectiveness may vary across different market microstructure environments. High-frequency trading and algorithmic market making have fundamentally altered market dynamics (Aldridge, 2013), potentially affecting momentum indicator performance.
### 7.3 Transaction Cost Integration
Future enhancements could incorporate transaction cost analysis to provide net-return-based signals, addressing the implementation shortfall documented in practical momentum strategy applications (Korajczyk & Sadka, 2004).
## References
Aldridge, I. (2013). *High-Frequency Trading: A Practical Guide to Algorithmic Strategies and Trading Systems*. 2nd ed. Hoboken, NJ: John Wiley & Sons.
Ang, A. (2014). *Asset Management: A Systematic Approach to Factor Investing*. New York: Oxford University Press.
Arms, R. W. (1989). *The Arms Index (TRIN): An Introduction to the Volume Analysis of Stock and Bond Markets*. Homewood, IL: Dow Jones-Irwin.
Asness, C. S., Moskowitz, T. J., & Pedersen, L. H. (2013). Value and momentum everywhere. *Journal of Finance*, 68(3), 929-985.
Barroso, P., & Santa-Clara, P. (2015). Momentum has its moments. *Journal of Financial Economics*, 116(1), 111-120.
Bollinger, J. (1992). *Bollinger on Bollinger Bands*. New York: McGraw-Hill.
Brock, W., Lakonishok, J., & LeBaron, B. (1992). Simple technical trading rules and the stochastic properties of stock returns. *Journal of Finance*, 47(5), 1731-1764.
Calmar, T. (1991). The Calmar ratio: A smoother tool. *Futures*, 20(1), 40.
Campbell, J. Y., Lo, A. W., & MacKinlay, A. C. (1997). *The Econometrics of Financial Markets*. Princeton, NJ: Princeton University Press.
Chekhlov, A., Uryasev, S., & Zabarankin, M. (2005). Drawdown measure in portfolio optimization. *International Journal of Theoretical and Applied Finance*, 8(1), 13-58.
Daniel, K., & Moskowitz, T. J. (2016). Momentum crashes. *Journal of Financial Economics*, 122(2), 221-247.
Fama, E. F., & French, K. R. (1996). Multifactor explanations of asset pricing anomalies. *Journal of Finance*, 51(1), 55-84.
Granville, J. E. (1963). *Granville's New Key to Stock Market Profits*. Englewood Cliffs, NJ: Prentice-Hall.
Guidolin, M. (2011). Markov switching models in empirical finance. In D. N. Drukker (Ed.), *Missing Data Methods: Time-Series Methods and Applications* (pp. 1-86). Bingley: Emerald Group Publishing.
Hamilton, J. D. (1989). A new approach to the economic analysis of nonstationary time series and the business cycle. *Econometrica*, 57(2), 357-384.
Jegadeesh, N., & Titman, S. (1993). Returns to buying winners and selling losers: Implications for stock market efficiency. *Journal of Finance*, 48(1), 65-91.
Kahneman, D., & Tversky, A. (1979). Prospect theory: An analysis of decision under risk. *Econometrica*, 47(2), 263-291.
Kaufman, P. J. (1995). *Smarter Trading: Improving Performance in Changing Markets*. New York: McGraw-Hill.
Korajczyk, R. A., & Sadka, R. (2004). Are momentum profits robust to trading costs? *Journal of Finance*, 59(3), 1039-1082.
Leland, H. E. (1980). Who should buy portfolio insurance? *Journal of Finance*, 35(2), 581-594.
Lo, A. W., Mamaysky, H., & Wang, J. (2000). Foundations of technical analysis: Computational algorithms, statistical inference, and empirical implementation. *Journal of Finance*, 55(4), 1705-1765.
Markowitz, H. (1952). Portfolio selection. *Journal of Finance*, 7(1), 77-91.
Murphy, J. J. (1999). *Technical Analysis of the Financial Markets: A Comprehensive Guide to Trading Methods and Applications*. New York: New York Institute of Finance.
Prechter, R. R., & Frost, A. J. (1978). *Elliott Wave Principle: Key to Market Behavior*. Gainesville, GA: New Classics Library.
Pring, M. J. (2002). *Technical Analysis Explained: The Successful Investor's Guide to Spotting Investment Trends and Turning Points*. 4th ed. New York: McGraw-Hill.
Roncalli, T. (2013). *Introduction to Risk Parity and Budgeting*. Boca Raton, FL: CRC Press.
Shefrin, H., & Statman, M. (1985). The disposition to sell winners too early and ride losers too long: Theory and evidence. *Journal of Finance*, 40(3), 777-790.
Taleb, N. N. (2007). *The Black Swan: The Impact of the Highly Improbable*. New York: Random House.
Taylor, M. P., & Allen, H. (1992). The use of technical analysis in the foreign exchange market. *Journal of International Money and Finance*, 11(3), 304-314.
Treadway, A. B. (1969). On rational entrepreneurial behavior and the demand for investment. *Review of Economic Studies*, 36(2), 227-239.
Wilder, J. W. (1978). *New Concepts in Technical Trading Systems*. Greensboro, NC: Trend Research.
Blaxks WatermarkPaging watermark for clear chart users, this allows one to input text to remind themselves of their plans, rule to be innovative during their trading sessions.
Money Risk Management with Trade Tracking
Overview
The Money Risk Management with Trade Tracking indicator is a powerful tool designed for traders on TradingView to simplify trade simulation and risk management. Unlike the TradingView Strategy Tester, which can be complex for beginners, this indicator provides an intuitive, beginner-friendly interface to evaluate trading strategies in a realistic manner, mirroring real-world trading conditions.
Built on the foundation of open-source contributions from LuxAlgo and TCP, this indicator integrates external indicator signals, overlays take-profit (TP) and stop-loss (SL) levels, and provides detailed money management analytics. It empowers traders to visualize potential profits, losses, and risk-reward ratios, making it easier to understand the financial outcomes of their strategies.
Key Features
Signal Integration: Seamlessly integrates with external long and short signals from other indicators, allowing traders to overlay TP/SL levels based on their preferred strategies.
Realistic Trade Simulation: Simulates trades as they would occur in real-world scenarios, accounting for initial capital, risk percentage, leverage, and compounding effects.
Money Management Dashboard: Displays critical metrics such as current capital, unrealized P&L, risk amount, potential profit, risk-reward ratio, and trade status in a customizable, beginner-friendly table.
TP/SL Visualization: Plots TP and SL levels on the chart with customizable styles (solid, dashed, dotted) and colors, along with optional labels for clarity.
Performance Tracking: Tracks total trades, win/loss counts, win rate, and profit factor, providing a clear overview of strategy performance.
Liquidation Risk Alerts: Warns traders if stop-loss levels risk liquidation based on leverage settings, enhancing risk awareness.
Benefits for Traders
Beginner-Friendly: Simplifies the complexities of the TradingView Strategy Tester, offering an intuitive interface for new traders to simulate and evaluate trades without confusion.
Real-World Insights: Helps traders understand the actual profit or loss potential of their strategies by factoring in capital, risk, and leverage, bridging the gap between theoretical backtesting and real-world execution.
Enhanced Decision-Making: Provides clear, real-time analytics on risk-reward ratios, unrealized P&L, and trade performance, enabling informed trading decisions.
Customizable and Flexible: Allows customization of TP/SL settings, table positions, colors, and sizes, catering to individual trader preferences.
Risk Management Focus: Encourages disciplined trading by highlighting risk amounts, potential profits, and liquidation risks, fostering better financial planning.
Why This Indicator Stands Out
Many traders struggle to translate backtested strategy results into real-world outcomes due to the abstract nature of percentage-based profitability metrics. This indicator addresses that challenge by providing a practical, user-friendly tool that simulates trades with real-world parameters like capital, leverage, and compounding. Its open-source nature ensures accessibility, while its integration with other indicators makes it versatile for various trading styles.
How to Use
Add to TradingView: Copy the Pine Script code into TradingView’s Pine Editor and add it to your chart.
Configure Inputs: Set your initial capital, risk percentage, leverage, and TP/SL values in the indicator settings. Select external long/short signal sources if integrating with other indicators.
Monitor Dashboards: Use the Money Management and Target Dashboard tables to track trade performance and risk metrics in real time.
Analyze Results: Review win rates, profit factors, and P&L to refine your trading strategy.
Credits
This indicator builds upon the open-source contributions of LuxAlgo and TCP , whose efforts in sharing their code have made this tool possible. Their dedication to the trading community is deeply appreciated.
Daily Target & Consistency Tracker (Fixed + Win Rate)Updated this script. Realized that the suggested daily target calculations was giving the wrong number of profit to make per day to stay within the 20% or below level. Good luck to all and happy trading.
Calcolatore Contratti DMT🧠 DMT Contract Calculator – Deep Market Trader
This indicator is a risk management tool designed for traders of U.S. futures (NQ, MNQ, ES, MES, YM, MYM), with a focus on intraday and scalping strategies.
📌 What it does
Automatically calculates the correct number of contracts to trade based on your dollar risk and stop loss in ticks.
Displays the effective risk and highlights it in red if it exceeds your preset risk.
Adapts to the selected asset with the appropriate tick value.
Presents the results in a clean table at the top right of the chart.
⚙️ How to use it
Choose your asset (e.g., MNQ) from the dropdown menu.
Set:
Your dollar risk (e.g., $100)
Your stop loss in ticks (e.g., 10 ticks)
The calculator will show:
Number of contracts to trade
Actual risk in dollars
A visual alert if the effective risk exceeds the preset value
Macro Context v1 - NobruzeraaaHMacro Context v1
Advanced Multi-Asset Correlation Analysis for Professional Trading
"In institutional trading, correlation is king. This panel puts the crown on your charts."
Overview
This is a sophisticated real-time market analysis tool that monitors critical institutional correlations across traditional and cryptocurrency markets. This indicator provides traders with actionable insights based on academic research and institutional trading patterns.
Features
- **Multi-Asset Correlation Engine**
- **13 Advanced Analysis Layers** covering macro, crypto, and institutional flows
- **Real-time Correlation Detection** between BTC, equities, bonds, and commodities
- **Institutional Divergence Alerts** for early trend identification
- **Risk Sentiment Analysis** using VIX, DXY, and yield curve data
**Professional Grade Analytics**
- **NDX/SPX vs BTC Correlation** - Critical tech-crypto relationship monitoring
- **VIX Breakout Detection** - Institutional panic (>30) and dangerous complacency (<15) alerts
- **Yield Curve Inversion Monitoring** - Recession signal detection via US10Y-US2Y spread
- **Institutional Flow Tracking** - Real proxies using MSTR/COIN performance
- **DXY Critical Levels** - USD dominance (>105) and weakness (<95) thresholds
**Smart Actionable Signals**
- **Opportunity Detection** in altcoins during confirmed risk-on periods
- **Divergence Warnings** when BTC-Tech correlations break down
- **Volatility Preparation** alerts during market complacency
- **Hedge Recommendations** during institutional flight to quality
Correlation Matrix Monitored
**Traditional Markets**
| Asset | Function | Institutional Significance |
|-------|----------|---------------------------|
| **SPX** | Equity benchmark | Risk-on/off sentiment |
| **NDX** | Tech growth proxy | Innovation capital flows |
| **VIX** | Volatility index | Fear/greed institutional gauge |
| **DXY** | Dollar strength | Global liquidity flows |
| **US10Y-US2Y** | Yield curve | Recession probability |
| **Gold** | Safe haven | Inflation hedge demand |
| **Copper** | Industrial metal | Growth expectations |
**Cryptocurrency Markets**
| Asset | Function | Institutional Significance |
|-------|----------|---------------------------|
| **BTC** | Digital store of value | Institutional adoption gauge |
| **ETH** | Smart contract platform | DeFi institutional interest |
| **BTC.D** | Bitcoin dominance | Crypto capital allocation |
| **USDT.D** | Stablecoin dominance | Risk-off crypto indicator |
| **TOTAL3** | Alt market cap | Retail vs institutional flow |
**Institutional Proxies**
| Asset | Function | Why It Matters |
|-------|----------|----------------|
| **MSTR** | MicroStrategy stock | Corporate BTC holdings proxy |
| **COIN** | Coinbase stock | Crypto institutional gateway |
---
Critical Correlations Detected
**1. Tech-Led Risk-On Confirmation**
**Trigger:** NDX outperforming SPX + BTC rising + VIX declining
**Signal:** Strong institutional appetite for growth assets
**Action:** Opportunity in tech and crypto momentum
**2. BTC-Tech Divergence Warning**
**Trigger:** NDX/SPX ratio positive + BTC declining significantly
**Signal:** Potential institutional crypto exit while maintaining tech exposure
**Action:** Monitor for broader crypto weakness
**3. Institutional Panic Mode**
**Trigger:** VIX > 30 + USDT.D rising + BTC/equities declining
**Signal:** Fear-driven liquidations across all risk assets
**Action:** Wait for clarity, prepare for volatility
**4. Dangerous Complacency**
**Trigger:** VIX < 15 + low volatility across assets
**Signal:** Market complacency reaching dangerous levels
**Action:** Prepare for sudden volatility spike
**5. Yield Curve Recession Signal**
**Trigger:** US10Y-US2Y spread deeply inverted (<-0.5%)
**Signal:** Bond market pricing in economic slowdown
**Action:** Defensive positioning, reduce risk exposure
**6. USD Super-Dominance**
**Trigger:** DXY > 105 + gold declining + risk assets under pressure
**Signal:** Extreme USD strength creating global liquidity stress
**Action:** Monitor emerging market stress, dollar-denominated debt concerns
**7. Altseason Confirmation**
**Trigger:** BTC.D declining + USDT.D declining + TOTAL3 outperforming + low VIX
**Signal:** Capital rotating from BTC to altcoins in risk-on environment
**Action:** Opportunity in alternative cryptocurrencies
---
Advanced Analytics Provided
**Risk Sentiment Classification**
- 🔴 **Fear in System** - Multiple fear indicators triggered
- 🟡 **Cautious Mode** - Mixed signals, proceed carefully
- 🟢 **Risk Appetite** - Confirmed risk-on environment
- 🟢 **Strong Risk-On** - Multiple bullish confirmations
- 🟠 **Dangerous Complacency** - Excessive optimism warning
**Macro Context Analysis**
- 💪 **Dollar Dominant** - USD strength driving global flows
- 🌍 **USD Weakening** - Emerging market and commodity positive
- ⚠️ **Market Stress** - Multiple stress indicators active
- 🚀 **Solid Bull Market** - Confirmed uptrend across assets
- 🏭 **Growth Acceleration** - Copper/Gold ratio signaling expansion
- 🛡️ **Defensive Rotation** - Flight to quality assets
**Actionable Intelligence**
- ✅ **Opportunity in Alts** - Multiple confirmations for altcoin exposure
- ⚠️ **Wait for Clarity** - High uncertainty, avoid new positions
- 🏛️ **Consider Hedge** - Defensive positioning recommended
- 📈 **Ride Momentum** - Trend continuation likely
- 🔍 **Monitor Divergence** - Correlation breakdown warning
- ⚠️ **Prepare for Volatility** - Complacency extreme reached
Technical Implementation
**Data Sources**
- **Traditional Markets:** TradingView real-time feeds
- **Cryptocurrency:** Binance spot prices and market cap data
- **Macro Data:** US Treasury yields, volatility indices
- **Update Frequency:** Every minute during market hours
**Calculation Methodology**
- **24-hour percentage changes** for all assets
- **Real-time price levels** for VIX and DXY thresholds
- **Spread calculations** for yield curve analysis
- **Ratio analysis** for relative performance metrics
**Multi-Language Support**
- 🇺🇸 **English** - Full professional terminology
- 🇪🇸 **Spanish** - Complete translation for Latin American markets
- 🇧🇷 **Portuguese** - Brazilian market terminology
---
Academic Foundation
This indicator is built upon peer-reviewed research and institutional trading patterns:
**Research-Based Correlations**
- **Bitcoin-NASDAQ correlation studies** (2024 academic papers)
- **VIX threshold analysis** from institutional trading desks
- **Yield curve inversion** recession prediction models
- **Dollar index breakout** historical analysis
- **Cryptocurrency dominance** flow studies
**Institutional Insights**
- **Fear & Greed Index** methodology adaptation
- **Professional volatility** threshold implementation
- **Corporate treasury** Bitcoin adoption tracking
- **Institutional proxy** correlation validation
---
Quick Start Guide
**Configuration**
- **Language Selection:** Choose your preferred language
- **Asset Selection:** Enable/disable specific asset monitoring
- **Timezone:** Set your preferred timezone for timestamp display
**Interpretation**
- **Green indicators:** Bullish/risk-on signals
- **Red indicators:** Bearish/risk-off signals
- **Yellow indicators:** Neutral/mixed signals
- **Orange indicators:** Warning/extreme conditions
---
Use Cases
**Traders**
- **Portfolio allocation** based on institutional flows
- **Risk management** through correlation monitoring
- **Market timing** using sentiment extremes
- **Divergence trading** opportunities
**Analysts**
- **Multi-asset correlation** research
- **Macro theme** identification
- **Risk sentiment** quantification
- **Flow analysis** across asset classes
**Cryptocurrency Investors**
- **Altseason timing** through dominance analysis
- **Macro correlation** understanding
- **Institutional adoption** tracking
- **Risk-on/off** positioning
---
Important Disclaimers
- **Not Financial Advice:** This tool provides analytical insights, not investment recommendations
- **Market Risk:** All trading involves substantial risk of loss
- **Correlation Changes:** Market correlations can shift rapidly during crisis periods
- **Supplementary Tool:** Should be used alongside other analysis methods
This indicator represents cutting-edge market analysis combining traditional finance and cryptocurrency insights. Regular updates ensure continued accuracy as market structures evolve.
**Version:** 1.0
**Last Updated:** 2025
**Compatibility:** Pine Script v6
**Category:** Multi-Asset Analysis
The LEAP Contest - Symbol & Max Position Table TrackerDescription:
This indicator tracks the maximum contracts allowed to be traded for TradingView’s *"The Leap"* Contest. It displays a horizontal table at the bottom right of your chart showing up to 20 symbols along with their maximum allowable open contract positions.
Use case:
Designed specifically for traders participating in *The Leap* Contest on TradingView.
Users need to enter the symbol and the maximum contracts allowed for that symbol in the settings menu for each new contest.
It provides a quick reference to ensure compliance with contest rules on maximum position sizes.
How it works:
The table shows two rows: the top row displays the symbol name, and the bottom row shows the max contract limit.
If the currently loaded chart symbol matches any symbol in the list, its text color changes to yellow .
Customization:
Symbols and limits must be updated in the indicator’s settings before each contest to reflect the current rules.
Futures Margin Lookup TableThis script applies a table to the upper right corner of the screen, which provides the intraday and overnight margin requirements of the currently selected symbol.
In this indicator the user must provide the broker data in the form of specifically formatted text blocks. The data for which should be found on the broker website.
The purpose for it's creation is due to the non-standard way each individual broker may price their margins and lack of information within TradingView when connected to some (maybe all) brokers, including when paper trading, as the flat percentage rule is not accurate.
An example of information for NinjaTrader could look like this
MES;Micro S&P;$50;$2406
ES;E-Mini S&P;$500;$24,053
GC;Gold;$500;$16500
NQ;E-Mini Nasdaq;$1,000;$34,810
FDAX;Dax Index;€2,000;€44,311
Each symbol begins a new line, and the values on that line are separated by semicolons (;)
Each line consists of the following...
SYMBOL : Search string used to match to the beginning of the current chart symbol.
NAME: Human readable name
INTRA: Intraday trading margin requirement per contract
OVERNIGHT: Overnight trading margin requirement per contract
The script simply finds a matching line within your provided information using the current chart symbol.
So for example the continuous chart for NQ1! would match to the user specified line starting with NQ... as would the individual contract dates such as NQM2025, NQK2025, etc.
NOTES:
There is a possibility that symbols with similar starting characters could match.
If this is the case put the longer symbol higher in the list.
There is also a line / character limit to the text input fields within pinescript
Ensure the text you paste into them is not truncated.
If so there are 3 input fields for just this purpose.
Find the last complete line and continue the remaining symbol lines on the subsequent inputs.
PCA Regime-Adjusted MomentumSummary
The PCA Regime-Adjusted Momentum (PCA-RAM) is an advanced market analysis tool designed to provide nuanced insights into market momentum and structural stability. It moves beyond traditional indicators by using Principal Component Analysis (PCA) to deconstruct market data into its most essential patterns.
The indicator provides two key pieces of information:
A smoothed momentum signal based on the market's dominant underlying trend.
A dynamic regime filter that gauges the stability and clarity of the market's structure, advising you when to trust or fade the momentum signals.
This allows traders to not only identify potential shifts in momentum but also to understand the context and confidence behind those signals.
Core Concepts & Methodology
The strength of this indicator lies in its sound, data-driven methodology.
1. Principal Component Analysis (PCA)
At its core, the indicator analyzes a rolling window (default 50 periods) of standardized market data (Open, High, Low, Close, and Volume). PCA is a powerful statistical technique that distills this complex, 5-dimensional data into its fundamental, uncorrelated components of variance. We focus on the First Principal Component (PC1), which represents the single most dominant pattern or "theme" driving the market's behavior in the lookback window.
2. The Momentum Signal
Instead of just looking at price, we project the current market data onto this dominant underlying pattern (PC1). This gives us a raw "projection score" that measures how strongly the current bar aligns with the historically dominant market structure. This raw score is then smoothed using two an exponential moving averages (a fast and a slow line) to create a clear, actionable momentum signal, similar in concept to a MACD.
3. The Dynamic Regime Filter
This is arguably the indicator's most powerful feature. It answers the question: "How clear is the current market picture?"
It calculates the Market Concentration Ratio, which is the percentage of total market variance explained by PC1 alone.
A high ratio indicates that the market is moving in a simple, one-dimensional way (e.g., a clear, strong trend).
A low ratio indicates the market is complex, multi-dimensional, and choppy, with no single dominant theme.
Crucially, this filter is dynamic. It compares the current concentration ratio to its own recent average, allowing it to adapt to any asset or timeframe. It automatically learns what "normal" and "choppy" look like for the specific chart you are viewing.
How to Interpret the Indicator
The indicator is displayed in a separate pane with two key visual elements:
The Momentum Lines (White & Gold)
White Line: The "Fast Line," representing the current momentum.
Gold Line: The "Slow Line," acting as the trend confirmation.
Bullish Signal: A crossover of the White Line above the Gold Line suggests a shift to positive momentum.
Bearish Signal: A crossover of the White Line below the Gold Line suggests a shift to negative momentum.
The Regime Filter (Purple & Dark Red Background)
This is your confidence gauge.
Navy Blue Background (High Concentration): The market structure is stable, simple, and trending. Momentum signals are more reliable and should be given higher priority.
Dark Red Background (Low Concentration): The market structure is complex, choppy, or directionless. Momentum signals are unreliable and prone to failure or "whipsaws." This is a signal to be cautious, tighten stops, or potentially stay out of the market.
Potential Trading Strategies
This tool is versatile and can be used in several ways:
1. Primary Signal Strategy
Condition: Wait for the background to turn Purple, confirming a stable, high-confidence regime.
Entry: Take the next crossover signal from the momentum lines (White over Gold for long, White under Gold for short).
Exit/Filter: Consider exiting positions or ignoring new signals when the background turns Navy.
2. As a Confirmation or Filter for Your Existing Strategy
Do you have a trend-following system? Only enable its long and short signals when the PCA-RAM background is Purple.
Do you have a range-trading or mean-reversion system? It might be most effective when the PCA-RAM background is Navy, indicating a lack of a clear trend.
3. Advanced Divergence Analysis
Look for classic divergences between price and the momentum lines. For example, if the price is making a new high, but the Gold Line is making a lower high, it may indicate underlying weakness in the trend, even on a Purple background. This divergence signal is more powerful because it shows that the new price high is not being confirmed by the market's dominant underlying pattern.
Correlation MA – 15 Assets + Average (Optional)This indicator calculates the moving average of the correlation coefficient between your charted asset and up to 15 user-selected symbols. It helps identify uncorrelated or inversely correlated assets for diversification, pair trading, or hedging.
Features:
✅ Compare your current chart against up to 15 assets
✅ Toggle assets on/off individually
✅ Custom correlation and MA lengths
✅ Real-time average correlation line across enabled assets
✅ Horizontal lines at +1, 0, and -1 for easy visual reference
Ideal for:
Portfolio diversification analysis
Finding low-correlation stocks
Mean-reversion & pair trading setups
Crypto, equities, ETFs
To use: set the benchmark chart (e.g. TSLA), choose up to 15 assets, and adjust settings as needed. Look for assets with correlation near 0 or negative values for uncorrelated performance.