//@version=6
indicator("alzaem RSPS - Optimized", overlay=false)
// --- Imports ---
import alzaem/PerformanceRatios/1 as ratios
import alzaem/AlzaemBacktesting/1 as metrics
import TradingView/ta/9 as ta
import alzaem/TrendAnalysisLibrary/1 as trendLib
// --- Inputs (Must be declared before usage) ---
// General Settings
startTimestamp = input.time(timestamp("1 Jan 2024 00:00 +0000"), "Start Date", group="General Settings")
display_winners_anyways = input.bool(false, "Force Display Winners", group="General Settings")
leverageInput = 1
rank_choice = input.string("Rank 1", "Rank Choice for Display and Equity", options=["Rank 1", "Rank 2", "Rank 3", "Rank 1 & 2", "Rank 1 & 3", "Rank 2 & 3"], group="General Settings")
analysis_timeframe = input.string("240", "Analysis Timeframe", ["60", "90", "120", "240", "480", "720", "D", "2D", "W"], group="General Settings")
minimumScore = input.int(2, "Minimum Score", group="General Settings", minval=0, maxval=35)
// Scoring Methods Options
grp_scoring = "Scoring Methods"
useTSI = input.bool(true, "Use TSI (Gate)", group=grp_scoring)
useIVO = input.bool(true, "Use IVO", group=grp_scoring)
useVQI = input.bool(true, "Use VQI", group=grp_scoring)
useATM = input.bool(true, "Use ATM", group=grp_scoring)
useMomentum = input.bool(true, "Use Momentum (Compmom)", group=grp_scoring)
// Momentum Competition Scoring
grp_mom = "Scoring: Momentum Competition"
momPeriod = input.int(5, "Momentum Period", group=grp_mom, minval=1)
compmom = input.int(13, "Relative Momentum Period", group=grp_mom, minval=1)
// TSI Settings
grp_tsi = "Scoring: TSI Settings"
tsi_vwma_length = input.int(21, "VWMA Length", group=grp_tsi)
tsi_atr_length = input.int(14, "ATR Length", group=grp_tsi)
tsi_trend_enter = input.float(0.5, "Trend Enter", group=grp_tsi)
tsi_trend_exit = input.float(0.1, "Trend Exit", group=grp_tsi)
// IVO Settings
grp_ivo = "Scoring: IVO Settings"
ivo_bars = input.int(20, "Bars", group=grp_ivo)
ivo_mult = input.float(1.5, "Multiplier", group=grp_ivo)
ivo_impact = input.float(0.5, "Volume Impact", group=grp_ivo)
ivo_ma_type = input.string("EMA", "MA Type", ["SMA", "EMA", "VWMA", "HULL"], group=grp_ivo)
ivo_smooth = input.int(3, "Smooth", group=grp_ivo)
ivo_trend_threshold = input.float(1.0, "Trend Threshold", group=grp_ivo)
ivo_reversion_threshold = input.float(-1.0, "Reversion Threshold", group=grp_ivo)
ivo_display_smooth_period = input.int(5, "Display Smooth", group=grp_ivo)
// VQI Settings
grp_vqi = "Scoring: VQI Settings"
vqi_len = input.int(14, "Length", group=grp_vqi)
vqi_smoothing_len = input.int(5, "Smoothing", group=grp_vqi)
vqi_stdev_mult1 = input.float(1.0, "StDev Mult 1", group=grp_vqi)
vqi_stdev_mult2 = input.float(2.0, "StDev Mult 2", group=grp_vqi)
vqi_stdev_mult3 = input.float(3.0, "StDev Mult 3", group=grp_vqi)
vqi_normalize = input.bool(true, "Normalize", group=grp_vqi)
vqi_normalization_length = input.int(50, "Normalization Length", group=grp_vqi)
// ATM Settings
grp_atm = "Scoring: ATM Settings"
atm_ema_fast_len = input.int(12, "Fast EMA", group=grp_atm)
atm_ema_slow_len = input.int(26, "Slow EMA", group=grp_atm)
atm_trend_strength_period = input.int(14, "Trend Strength Period", group=grp_atm)
atm_rsi_length = input.int(14, "RSI Length", group=grp_atm)
atm_oversold_level = input.int(30, "RSI Oversold", group=grp_atm)
atm_overbought_level = input.int(70, "RSI Overbought", group=grp_atm)
// Asset Definitions as Inputs
asset1_symbol = input.symbol("BINANCE:XRPUSDT", "Asset 1 Symbol", group="Asset Settings")
asset2_symbol = input.symbol("BINANCE:BNBUSDT", "Asset 2 Symbol", group="Asset Settings")
asset3_symbol = input.symbol("BINANCE:ADAUSDT", "Asset 3 Symbol", group="Asset Settings")
asset4_symbol = input.symbol("BINANCE:TRXUSDT", "Asset 4 Symbol", group="Asset Settings")
asset5_symbol = input.symbol("BINANCE:LINKUSDT", "Asset 5 Symbol", group="Asset Settings")
asset6_symbol = input.symbol("BINANCE:AVAXUSDT", "Asset 6 Symbol", group="Asset Settings")
asset7_symbol = input.symbol("BINANCE:TONUSDT", "Asset 7 Symbol", group="Asset Settings")
asset8_symbol = input.symbol("BINANCE:DOTUSDT", "Asset 8 Symbol", group="Asset Settings")
asset9_symbol = input.symbol("BINANCE:NEARUSDT", "Asset 9 Symbol", group="Asset Settings")
asset10_symbol = input.symbol("BINANCE:TAOUSDT", "Asset 10 Symbol", group="Asset Settings")
asset11_symbol = input.symbol("BINANCE:RENDERUSDT", "Asset 11 Symbol", group="Asset Settings")
asset12_symbol = input.symbol("BINANCE:SEIUSDT", "Asset 12 Symbol", group="Asset Settings")
asset13_symbol = input.symbol("BINANCE:ARBUSDT", "Asset 13 Symbol", group="Asset Settings")
asset14_symbol = input.symbol("BINANCE:WLDUSDT", "Asset 14 Symbol", group="Asset Settings")
asset15_symbol = input.symbol("BINANCE:GMTUSDT", "Asset 15 Symbol", group="Asset Settings")
asset16_symbol = input.symbol("BINANCE:CFXUSDT", "Asset 16 Symbol", group="Asset Settings")
asset17_symbol = input.symbol("BINANCE:APTUSDT", "Asset 17 Symbol", group="Asset Settings")
asset18_symbol = input.symbol("BINANCE:POLUSDT", "Asset 18 Symbol", group="Asset Settings")
asset19_symbol = input.symbol("BINANCE:JUPUSDT", "Asset 19 Symbol", group="Asset Settings")
asset20_symbol = input.symbol("BINANCE:FETUSDT", "Asset 20 Symbol", group="Asset Settings")
asset21_symbol = input.symbol("BINANCE:CHZUSDT", "Asset 21 Symbol", group="Asset Settings")
asset22_symbol = input.symbol("BINANCE:ATOMUSDT", "Asset 22 Symbol", group="Asset Settings")
asset23_symbol = input.symbol("BINANCE:DOGEUSDT", "Asset 23 Symbol", group="Asset Settings")
asset24_symbol = input.symbol("BINANCE:FILUSDT", "Asset 24 Symbol", group="Asset Settings")
asset25_symbol = input.symbol("BINANCE:SUSDT", "Asset 25 Symbol", group="Asset Settings")
asset26_symbol = input.symbol("BINANCE:GALAUSDT", "Asset 26 Symbol", group="Asset Settings")
asset27_symbol = input.symbol("BINANCE:ROSEUSDT", "Asset 27 Symbol", group="Asset Settings")
asset28_symbol = input.symbol("BINANCE:LTCUSDT", "Asset 28 Symbol", group="Asset Settings")
asset29_symbol = input.symbol("BINANCE:OPUSDT", "Asset 29 Symbol", group="Asset Settings")
asset30_symbol = input.symbol("BINANCE:NEOUSDT", "Asset 30 Symbol", group="Asset Settings")
selectedAsset1 = input.int(1, "Selected Asset 1", minval=1, maxval=30, group="Selected Assets")
selectedAsset2 = input.int(2, "Selected Asset 2", minval=1, maxval=30, group="Selected Assets")
selectedAsset3 = input.int(3, "Selected Asset 3", minval=1, maxval=30, group="Selected Assets")
selectedAsset4 = input.int(4, "Selected Asset 4", minval=1, maxval=30, group="Selected Assets")
selectedAsset5 = input.int(5, "Selected Asset 5", minval=1, maxval=30, group="Selected Assets")
// Design Setup
LABEL = input.bool(false, "Long/Cash Signal Label", group="Visual | QuantEdgeB", tooltip="Display labels for Long/Cash signals on the chart.")
// --- Global Variables ---
// final_indices stores the 0-based index (0 to 29) of the top performing assets, used for trading.
var int[] final_indices = array.new_int(0)
// Store the 0-based index of the asset traded in the previous bar
var int prev_ranked_idx1 = na
var int prev_ranked_idx2 = na
// Store the closing prices of the assets chosen in the previous bar (0-indexed array)
var float[] asset_closes_prev = array.new_float(30, na)
// final_winners (1-based index array) kept primarily for compatibility with previous logic structure, now derived from final_indices logic.
var int[] final_winners = array.new_int(0)
// --- Utility Functions ---
f_remove_exchange_name(name) =>
string[] parts = str.split(name, ":")
array.size(parts) > 1 ? array.get(parts, 1) : name
// Timeframe parsing
get_tf_min(string tf) =>
switch tf
"60" => 60
"90" => 90
"120" => 120
"240" => 240
"480" => 480
"720" => 720
"D" => 1440
"2D" => 2880
"W" => 10080
=> na
// Get analysis and chart mins
analysis_min = get_tf_min(analysis_timeframe)
chart_min = get_tf_min(timeframe.period)
// Asset symbols array
asset_symbols = array.from(asset1_symbol, asset2_symbol, asset3_symbol, asset4_symbol, asset5_symbol, asset6_symbol, asset7_symbol, asset8_symbol, asset9_symbol, asset10_symbol, asset11_symbol, asset12_symbol, asset13_symbol, asset14_symbol, asset15_symbol, asset16_symbol, asset17_symbol, asset18_symbol, asset19_symbol, asset20_symbol, asset21_symbol, asset22_symbol, asset23_symbol, asset24_symbol, asset25_symbol, asset26_symbol, asset27_symbol, asset28_symbol, asset29_symbol, asset30_symbol)
// --- Scoring Logic ---
f_calculate_total_score() =>
tsi = trendLib.calculate_tsi(close, tsi_vwma_length, tsi_atr_length, tsi_trend_enter, tsi_trend_exit)
ivo = trendLib.calculate_ivo(close, ivo_bars, ivo_mult, ivo_impact, ivo_ma_type, ivo_smooth, ivo_trend_threshold, ivo_reversion_threshold, ivo_display_smooth_period)
vqi = trendLib.calculate_vqi(close, vqi_len, vqi_smoothing_len, vqi_stdev_mult1, vqi_stdev_mult2, vqi_stdev_mult3, vqi_normalize, vqi_normalization_length)
atm = trendLib.calculate_atm(close, atm_ema_fast_len, atm_ema_slow_len, atm_trend_strength_period, atm_rsi_length, atm_oversold_level, atm_overbought_level)
is_gate_closed = useTSI and (tsi.trend_strength <= 0)
calculated_score = 0
if not is_gate_closed
if useTSI and tsi.bull_entry_signal
calculated_score += 1
if useIVO
calculated_score += ivo.is_dorito ? 1 : 0
if useVQI
calculated_score += vqi.strong_signal ? 1 : 0
if useATM
calculated_score += atm.bullish_signal ? 1 : 0
[calculated_score, tsi.trend_strength]
// Bundles data for each asset: [close, score, close[momPeriod], close[compmom], tsi_strength]
f_get_data_for_asset() =>
[score, tsi_strength] = f_calculate_total_score()
[close, score, close[momPeriod], close[compmom], tsi_strength]
// --- Fetch Data for Assets ---
[c1, s1, ml1, cl1, tsi1] = request.security(asset1_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c2, s2, ml2, cl2, tsi2] = request.security(asset2_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c3, s3, ml3, cl3, tsi3] = request.security(asset3_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c4, s4, ml4, cl4, tsi4] = request.security(asset4_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c5, s5, ml5, cl5, tsi5] = request.security(asset5_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c6, s6, ml6, cl6, tsi6] = request.security(asset6_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c7, s7, ml7, cl7, tsi7] = request.security(asset7_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c8, s8, ml8, cl8, tsi8] = request.security(asset8_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c9, s9, ml9, cl9, tsi9] = request.security(asset9_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c10, s10, ml10, cl10, tsi10] = request.security(asset10_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c11, s11, ml11, cl11, tsi11] = request.security(asset11_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c12, s12, ml12, cl12, tsi12] = request.security(asset12_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c13, s13, ml13, cl13, tsi13] = request.security(asset13_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c14, s14, ml14, cl14, tsi14] = request.security(asset14_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c15, s15, ml15, cl15, tsi15] = request.security(asset15_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c16, s16, ml16, cl16, tsi16] = request.security(asset16_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c17, s17, ml17, cl17, tsi17] = request.security(asset17_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c18, s18, ml18, cl18, tsi18] = request.security(asset18_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c19, s19, ml19, cl19, tsi19] = request.security(asset19_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c20, s20, ml20, cl20, tsi20] = request.security(asset20_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c21, s21, ml21, cl21, tsi21] = request.security(asset21_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c22, s22, ml22, cl22, tsi22] = request.security(asset22_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c23, s23, ml23, cl23, tsi23] = request.security(asset23_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c24, s24, ml24, cl24, tsi24] = request.security(asset24_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c25, s25, ml25, cl25, tsi25] = request.security(asset25_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c26, s26, ml26, cl26, tsi26] = request.security(asset26_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c27, s27, ml27, cl27, tsi27] = request.security(asset27_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c28, s28, ml28, cl28, tsi28] = request.security(asset28_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c29, s29, ml29, cl29, tsi29] = request.security(asset29_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
[c30, s30, ml30, cl30, tsi30] = request.security(asset30_symbol, analysis_timeframe, f_get_data_for_asset(), lookahead = barmerge.lookahead_off)
// --- Initial Asset Scores, Closes, Momentum Lags ---
initial_asset_scores = array.from(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30)
tsi_strengths = array.from(tsi1, tsi2, tsi3, tsi4, tsi5, tsi6, tsi7, tsi8, tsi9, tsi10, tsi11, tsi12, tsi13, tsi14, tsi15, tsi16, tsi17, tsi18, tsi19, tsi20, tsi21, tsi22, tsi23, tsi24, tsi25, tsi26, tsi27, tsi28, tsi29, tsi30)
asset_closes_all = array.from(c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20, c21, c22, c23, c24, c25, c26, c27, c28, c29, c30)
asset_ml_all = array.from(ml1, ml2, ml3, ml4, ml5, ml6, ml7, ml8, ml9, ml10, ml11, ml12, ml13, ml14, ml15, ml16, ml17, ml18, ml19, ml20, ml21, ml22, ml23, ml24, ml25, ml26, ml27, ml28, ml29, ml30)
asset_cl_all = array.from(cl1, cl2, cl3, cl4, cl5, cl6, cl7, cl8, cl9, cl10, cl11, cl12, cl13, cl14, cl15, cl16, cl17, cl18, cl19, cl20, cl21, cl22, cl23, cl24, cl25, cl26, cl27, cl28, cl29, cl30)
// --- Momentum Condition Function ---
f_condition(float price_k, float price_m, float mom_lag_k, float mom_lag_m, float comp_lag_k, float comp_lag_m) =>
if na(price_k) or na(price_m) or na(mom_lag_k) or na(mom_lag_m) or na(comp_lag_k) or na(comp_lag_m)
0
else
mom_k = price_k - mom_lag_k
mom_m = price_m - mom_lag_m
mom_ratio = if comp_lag_m == 0 or comp_lag_k == 0
0.0
else
(price_k / price_m) - (comp_lag_k / comp_lag_m)
if na(mom_k) or na(mom_m) or na(mom_ratio)
0
else
(mom_m > 0 and mom_ratio > 0) or (mom_m < 0 and mom_k > 0) or (mom_m < 0 and mom_k < 0 and mom_ratio > 0) or (mom_m == 0 and mom_k > 0) ? 1 : 0
// --- Calculate Relative Strength Momentum Scores (Vectorized) ---
asset_mom_scores = array.new_int(30, 0)
// Calculate momentum score for each asset against all 29 others
for i = 0 to 29 // Asset K (the one being scored)
float mom_score = 0.0
price_k = array.get(asset_closes_all, i)
ml_k = array.get(asset_ml_all, i)
cl_k = array.get(asset_cl_all, i)
// Check if asset K data is available
if not na(price_k) and price_k > 0
for j = 0 to 29 // Asset M (the comparison asset)
if i != j
price_m = array.get(asset_closes_all, j)
ml_m = array.get(asset_ml_all, j)
cl_m = array.get(asset_cl_all, j)
// f_condition handles NA inputs internally
mom_score += f_condition(price_k, price_m, ml_k, ml_m, cl_k, cl_m)
array.set(asset_mom_scores, i, int(mom_score))
// --- Combine Scores and Filter ---
asset_scores = array.new_int(30, 0)
for i = 0 to 29
s = array.get(initial_asset_scores, i)
mom_s = array.get(asset_mom_scores, i)
current_close = array.get(asset_closes_all, i)
// Check if asset data is valid
if not na(current_close)
final_score = s > 0 and useMomentum ? mom_s : s >= minimumScore ? s : 0
array.set(asset_scores, i, final_score)
else
array.set(asset_scores, i, 0)
// --- Ranking Calculation ---
asset_ranks = array.new_float(30)
for i = 0 to 29
int rankfinalscore = 1
for j = 0 to 29
if i != j and array.get(asset_scores, i) < array.get(asset_scores, j)
rankfinalscore := rankfinalscore + 1
array.set(asset_ranks, i, rankfinalscore)
// --- System State & Winner Population ---
var bool inPosition = false
// Array Population for Indices and Winners
if barstate.isconfirmed
array.clear(final_indices)
array.clear(final_winners)
int max_rank = int(array.max(asset_ranks))
for rank = 1 to max_rank
for i = 0 to 29
// Filter by final score > 0 (including momentum score if used)
if array.get(asset_ranks, i) == rank and array.get(asset_scores, i) > 0
array.push(final_indices, i) // Store 0-based index for trading
array.push(final_winners, i + 1) // Store 1-based index for compatibility/display
// System status based on whether we have tradeable assets
inPosition := array.size(final_indices) > 0
// --- Table Visualization Setup ---
var table myTable = table.new(position.middle_right, columns=6, rows=18, frame_color=color.black, frame_width=3, bgcolor=color.rgb(0,0,0,0), border_color=color.black, border_width=1)
if barstate.isfirst
table.cell(myTable, 0, 0, "🚀 Relative Strength Matrix Portfolio 🚀", text_color=color.rgb(248, 199, 67), text_size=size.large, text_formatting=text.format_bold)
table.merge_cells(myTable, 0, 0, 5, 0)
table.cell(myTable, 0, 1, "👀 System 👀", text_color=color.rgb(248, 199, 67), text_formatting=text.format_bold)
table.merge_cells(myTable, 0, 1, 5, 1)
table.cell(myTable, 5, 2, "Net Profit", text_color=color.white)
table.cell(myTable, 0, 2, "Sharpe", text_color=color.white)
table.cell(myTable, 1, 2, "Sortino", text_color=color.white)
table.cell(myTable, 2, 2, "Omega", text_color=color.white)
table.cell(myTable, 3, 2, "Equity DD", text_color=color.white)
table.cell(myTable, 4, 2, "", text_color=color.white)
table.cell(myTable, 0, 4, "🦴 Buy & Hold 🦴", text_color=color.rgb(248, 199, 67), text_formatting=text.format_bold)
table.merge_cells(myTable, 0, 4, 5, 4)
table.cell(myTable, 5, 5, "Net Profit", text_color=color.white)
table.cell(myTable, 0, 5, "Sharpe", text_color=color.white)
table.cell(myTable, 1, 5, "Sortino", text_color=color.white)
table.cell(myTable, 2, 5, "Omega", text_color=color.white)
table.cell(myTable, 3, 5, "Equity DD", text_color=color.white)
table.cell(myTable, 4, 5, "", text_color=color.white)
table.cell(myTable, 0, 7, "💰 Allocations 💰", text_color=color.rgb(248, 199, 67), text_formatting=text.format_bold)
table.merge_cells(myTable, 0, 7, 2, 7)
table.cell(myTable, 3, 7, "🦆 System State 🦆", text_color=color.rgb(248, 199, 67), text_formatting=text.format_bold)
table.merge_cells(myTable, 3, 7, 5, 7)
table.cell(myTable, 0, 9, "Winner 1 symbol", text_color=color.rgb(67, 116, 248))
table.cell(myTable, 1, 9, "Winner 2 symbol", text_color=color.rgb(67, 116, 248))
table.cell(myTable, 2, 9, "Winner 3 symbol", text_color=color.rgb(67, 116, 248))
table.cell(myTable, 0, 10, "We can't impose our will on a system. We can listen to what the system tells us,\n" + "and discover how its properties and our values can work together to bring forth\n" + "something much better than could ever be produced by our will alone", text_color=color.white, text_size=size.small, text_halign=text.align_center, text_formatting=text.format_italic)
table.merge_cells(myTable, 0, 10, 5, 10)
table.cell(myTable, 0, 11, "🏆 Top 5 & Selected Assets 🏆", text_color=color.rgb(248, 199, 67), text_formatting=text.format_bold)
table.merge_cells(myTable, 0, 11, 5, 11)
table.cell(myTable, 0, 12, "Top 5 Asset", text_color=color.white)
table.cell(myTable, 1, 12, "Score", text_color=color.white)
table.cell(myTable, 2, 12, "TSI", text_color=color.white)
table.cell(myTable, 3, 12, "Selected Asset", text_color=color.white)
table.cell(myTable, 4, 12, "Score", text_color=color.white)
table.cell(myTable, 5, 12, "TSI", text_color=color.white)
// --- Display Top 5 and Selected Assets ---
if barstate.isconfirmed
// Display Top 5 Winners (uses final_indices, 0-based)
for i = 0 to math.min(4, array.size(final_indices) - 1)
idx = array.get(final_indices, i)
sym = f_remove_exchange_name(array.get(asset_symbols, idx))
int score = array.get(asset_scores, idx)
float tsi_val = array.get(tsi_strengths, idx)
table.cell(myTable, 0, 13 + i, sym, text_color=color.rgb(67, 116, 248))
table.cell(myTable, 1, 13 + i, str.tostring(score), text_color=color.rgb(67, 116, 248))
table.cell(myTable, 2, 13 + i, str.tostring(math.round(tsi_val, 2)), text_color=color.rgb(67, 116, 248))
// Clear unused rows if less than 5 winners
for i = array.size(final_indices) to 4
table.cell(myTable, 0, 13 + i, "", text_color=color.rgb(67, 116, 248))
table.cell(myTable, 1, 13 + i, "", text_color=color.rgb(67, 116, 248))
table.cell(myTable, 2, 13 + i, "", text_color=color.rgb(67, 116, 248))
// Selected Assets Display
if selectedAsset1 >= 1 and selectedAsset1 <= 30
idx1 = selectedAsset1 - 1
sym1 = f_remove_exchange_name(array.get(asset_symbols, idx1))
int score1 = array.get(asset_scores, idx1)
float tsi1_val = array.get(tsi_strengths, idx1)
table.cell(myTable, 3, 13, sym1, text_color=color.rgb(67, 116, 248))
table.cell(myTable, 4, 13, str.tostring(score1), text_color=color.rgb(67, 116, 248))
table.cell(myTable, 5, 13, str.tostring(math.round(tsi1_val, 2)), text_color=color.rgb(67, 116, 248))
else
table.cell(myTable, 3, 13, "Invalid", text_color=color.gray)
table.cell(myTable, 4, 13, "", text_color=color.gray)
table.cell(myTable, 5, 13, "", text_color=color.gray)
if selectedAsset2 >= 1 and selectedAsset2 <= 30
idx2 = selectedAsset2 - 1
sym2 = f_remove_exchange_name(array.get(asset_symbols, idx2))
int score2 = array.get(asset_scores, idx2)
float tsi2_val = array.get(tsi_strengths, idx2)
table.cell(myTable, 3, 14, sym2, text_color=color.rgb(67, 116, 248))
table.cell(myTable, 4, 14, str.tostring(score2), text_color=color.rgb(67, 116, 248))
table.cell(myTable, 5, 14, str.tostring(math.round(tsi2_val, 2)), text_color=color.rgb(67, 116, 248))
else
table.cell(myTable, 3, 14, "Invalid", text_color=color.gray)
table.cell(myTable, 4, 14, "", text_color=color.gray)
table.cell(myTable, 5, 14, "", text_color=color.gray)
if selectedAsset3 >= 1 and selectedAsset3 <= 30
idx3 = selectedAsset3 - 1
sym3 = f_remove_exchange_name(array.get(asset_symbols, idx3))
int score3 = array.get(asset_scores, idx3)
float tsi3_val = array.get(tsi_strengths, idx3)
table.cell(myTable, 3, 15, sym3, text_color=color.rgb(67, 116, 248))
table.cell(myTable, 4, 15, str.tostring(score3), text_color=color.rgb(67, 116, 248))
table.cell(myTable, 5, 15, str.tostring(math.round(tsi3_val, 2)), text_color=color.rgb(67, 116, 248))
else
table.cell(myTable, 3, 15, "Invalid", text_color=color.gray)
table.cell(myTable, 4, 15, "", text_color=color.gray)
table.cell(myTable, 5, 15, "", text_color=color.gray)
if selectedAsset4 >= 1 and selectedAsset4 <= 30
idx4 = selectedAsset4 - 1
sym4 = f_remove_exchange_name(array.get(asset_symbols, idx4))
int score4 = array.get(asset_scores, idx4)
float tsi4_val = array.get(tsi_strengths, idx4)
table.cell(myTable, 3, 16, sym4, text_color=color.rgb(67, 116, 248))
table.cell(myTable, 4, 16, str.tostring(score4), text_color=color.rgb(67, 116, 248))
table.cell(myTable, 5, 16, str.tostring(math.round(tsi4_val, 2)), text_color=color.rgb(67, 116, 248))
else
table.cell(myTable, 3, 16, "Invalid", text_color=color.gray)
table.cell(myTable, 4, 16, "", text_color=color.gray)
table.cell(myTable, 5, 16, "", text_color=color.gray)
if selectedAsset5 >= 1 and selectedAsset5 <= 30
idx5 = selectedAsset5 - 1
sym5 = f_remove_exchange_name(array.get(asset_symbols, idx5))
int score5 = array.get(asset_scores, idx5)
float tsi5_val = array.get(tsi_strengths, idx5)
table.cell(myTable, 3, 17, sym5, text_color=color.rgb(67, 116, 248))
table.cell(myTable, 4, 17, str.tostring(score5), text_color=color.rgb(67, 116, 248))
table.cell(myTable, 5, 17, str.tostring(math.round(tsi5_val, 2)), text_color=color.rgb(67, 116, 248))
else
table.cell(myTable, 3, 17, "Invalid", text_color=color.gray)
table.cell(myTable, 4, 17, "", text_color=color.gray)
table.cell(myTable, 5, 17, "", text_color=color.gray)
// --- Update Allocations and System State ---
if barstate.isconfirmed
// Update Allocation Symbols
var int rank1_idx_pos = na
var int rank2_idx_pos = na
switch rank_choice
"Rank 1" => rank1_idx_pos := 0
"Rank 2" => rank1_idx_pos := 1
"Rank 3" => rank1_idx_pos := 2
"Rank 1 & 2" =>
rank1_idx_pos := 0
rank2_idx_pos := 1
"Rank 1 & 3" =>
rank1_idx_pos := 0
rank2_idx_pos := 2
"Rank 2 & 3" =>
rank1_idx_pos := 1
rank2_idx_pos := 2
// Allocation Symbol 1
if not na(rank1_idx_pos) and rank1_idx_pos < array.size(final_indices) and ((inPosition) or (display_winners_anyways))
idx1 = array.get(final_indices, rank1_idx_pos)
sym1 = f_remove_exchange_name(array.get(asset_symbols, idx1))
table.cell(myTable, 0, 9, sym1, text_color=color.rgb(67, 116, 248))
else
table.cell(myTable, 0, 9, "", text_color=color.rgb(67, 116, 248))
// Allocation Symbol 2
if not na(rank2_idx_pos) and rank2_idx_pos < array.size(final_indices) and ((inPosition) or (display_winners_anyways))
idx2 = array.get(final_indices, rank2_idx_pos)
sym2 = f_remove_exchange_name(array.get(asset_symbols, idx2))
table.cell(myTable, 1, 9, sym2, text_color=color.rgb(67, 116, 248))
else
table.cell(myTable, 1, 9, "", text_color=color.rgb(67, 116, 248))
// Allocation Symbol 3 - Placeholder
table.cell(myTable, 2, 9, "", text_color=color.rgb(67, 116, 248))
// System State Display
color sys_color = inPosition ? color.rgb(67, 248, 199) : color.rgb(248, 67, 115)
string sys_text = inPosition ? "ON" : "OFF"
table.cell(myTable, 3, 9, text=sys_text, text_color=sys_color)
table.merge_cells(myTable, 3, 9, 5, 9)
// --- Analysis Bar Detection ---
analysis_time = request.security(syminfo.tickerid, analysis_timeframe, time, lookahead = barmerge.lookahead_off)
var float prev_analysis_time = na
bool is_new_analysis_bar = analysis_time != prev_analysis_time
prev_analysis_time := analysis_time
// --- Equity Calculation ---
var float equity = 1.0
if time >= startTimestamp and barstate.isconfirmed and is_new_analysis_bar
// 1. Calculate PnL for the holding period using prices saved from the *previous* analysis bar
if inPosition // Check if we were supposed to be in position on the previous analysis bar
float float_eq_percent_change = 0.0
int valid_assets = 0
// PnL for Rank 1 asset (held from prev_ranked_idx1)
if not na(prev_ranked_idx1) and prev_ranked_idx1 >= 0
prev_price1 = array.get(asset_closes_prev, prev_ranked_idx1)
curr_price1 = array.get(asset_closes_all, prev_ranked_idx1)
// Check data validity
if not na(prev_price1) and prev_price1 != 0 and not na(curr_price1)
change1 = ((curr_price1 - prev_price1) / prev_price1) * 100
float_eq_percent_change += change1
valid_assets += 1
// PnL for Rank 2 asset (held from prev_ranked_idx2)
if not na(prev_ranked_idx2) and prev_ranked_idx2 >= 0
prev_price2 = array.get(asset_closes_prev, prev_ranked_idx2)
curr_price2 = array.get(asset_closes_all, prev_ranked_idx2)
// Check data validity
if not na(prev_price2) and prev_price2 != 0 and not na(curr_price2)
change2 = ((curr_price2 - prev_price2) / prev_price2) * 100
float_eq_percent_change += change2
valid_assets += 1
if valid_assets > 0
float_eq_percent_change_average = float_eq_percent_change / valid_assets
equity := equity * (1 + (float_eq_percent_change_average / 100) * leverageInput)
// 2. Determine indices for the *next* holding period based on current winners (final_indices)
var int rank_idx1_pos = na
var int rank_idx2_pos = na
switch rank_choice
"Rank 1" => rank_idx1_pos := 0
"Rank 2" => rank_idx1_pos := 1
"Rank 3" => rank_idx1_pos := 2
"Rank 1 & 2" =>
rank_idx1_pos := 0
rank_idx2_pos := 1
"Rank 1 & 3" =>
rank_idx1_pos := 0
rank_idx2_pos := 2
"Rank 2 & 3" =>
rank_idx1_pos := 1
rank_idx2_pos := 2
// Store 0-based index from final_indices
prev_ranked_idx1 := na(rank_idx1_pos) or rank_idx1_pos >= array.size(final_indices) ? na : array.get(final_indices, rank_idx1_pos)
prev_ranked_idx2 := na(rank_idx2_pos) or rank_idx2_pos >= array.size(final_indices) ? na : array.get(final_indices, rank_idx2_pos)
// 3. Save current prices for next bar's PnL calculation
asset_closes_prev := array.copy(asset_closes_all)
// --- Buy & Hold BTC Equity ---
[btc_price, btc_close] = request.security("BINANCE:BTCUSDT", analysis_timeframe, [open, close], lookahead = barmerge.lookahead_off)
var float equityNot = 1.0
var float entry_price = na
if time >= startTimestamp and barstate.isconfirmed and is_new_analysis_bar
if na(entry_price)
entry_price := btc_price
else
if not na(btc_close) and not na(entry_price) and entry_price != 0
pnl_pct = (btc_close - entry_price) / entry_price
equityNot := 1.0 * (1 + pnl_pct * leverageInput)
// --- Plotting ---
eq_color = inPosition ? color.rgb(230, 0, 111) : color.white
eqPlot = plot(equity, title="RSPS Equity Curve", linewidth=1, color=eq_color)
eqPlotNot = plot(equityNot, title="BTC HODL Equity Curve", linewidth=1, color=color.gray)
// --- Final Display Labels ---
if barstate.islast
label.new(x=bar_index, y=equity, text="System", style=label.style_label_left, color=color.black, textcolor=color.gray, size=size.tiny, textalign=text.align_center)
label.new(x=bar_index, y=equityNot, text="HODL BTC", style=label.style_label_left, color=color.black, textcolor=color.gray, size=size.tiny, textalign=text.align_center)
// --- Metrics Calculation and Table Population ---
// System Metrics
[Risk, Return, shrp, sortino, omega] = metrics.Equity(equity, startTimestamp)
maxDD = metrics.calculateMaxDrawdown(equity, startTimestamp)
table.cell(myTable, 0, 3, str.tostring(math.round(shrp, 2)), text_color=color.rgb(67, 116, 248))
table.cell(myTable, 1, 3, str.tostring(math.round(sortino, 2)), text_color=color.rgb(67, 116, 248))
table.cell(myTable, 2, 3, str.tostring(math.round(omega, 2)), text_color=color.rgb(67, 116, 248))
table.cell(myTable, 3, 3, str.tostring(math.round(maxDD * 100, 2)) + "%", text_color=color.rgb(248, 67, 115))
table.cell(myTable, 5, 3, str.tostring(math.round(equity, 2)) + "x", text_color=color.rgb(67, 116, 248))
// BTC HODL Metrics
[Risk1, Return1, shrp1, sortino1, omega1] = metrics.Equity(equityNot, startTimestamp)
maxDD1 = metrics.calculateMaxDrawdown(equityNot, startTimestamp)
table.cell(myTable, 0, 6, str.tostring(math.round(shrp1, 2)), text_color=color.rgb(67, 116, 248))
table.cell(myTable, 1, 6, str.tostring(math.round(sortino1, 2)), text_color=color.rgb(67, 116, 248))
table.cell(myTable, 2, 6, str.tostring(math.round(omega1, 2)), text_color=color.rgb(67, 116, 248))
table.cell(myTable, 3, 6, str.tostring(math.round(maxDD1 * 100, 2)) + "%", text_color=color.rgb(248, 67, 115))
table.cell(myTable, 5, 6, str.tostring(math.round(equityNot, 2)) + "x", text_color=color.rgb(67, 116, 248))