本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Indicador de Rotación Sectorial", overlay=false, max_bars_back=5000, max_labels_count=500)
grp_assets = "Activos"
ticker_a = input.symbol("SP:IXT", "ETF A", group=grp_assets, display=display.none)
ticker_b = input.symbol("SP:IXR", "ETF B", group=grp_assets, display=display.none)
ticker_c = input.symbol("", "ETF C", group=grp_assets, display=display.none)
ticker_d = input.symbol("", "ETF D", group=grp_assets, display=display.none)
ticker_e = input.symbol("", "ETF E", group=grp_assets, display=display.none)
grp_params = "Parámetros del Indicador"
string sec_tf = "D"
ma_trend_len = input.int(200, "Media Móvil de Tendencia (SMA)", group=grp_params, display=display.none)
buffer_pct = input.float(2.0, "Buffer de Rotación (%) [solo aplica en modo 3-5 ETF]", step=0.1, group=grp_params, display=display.none)
bool use_abs_mom = false
bool use_catchup = true
color red_matte = color.rgb(168, 52, 52)
grp_bb = "Bandas de Bollinger"
show_bb = input.bool(true, "Mostrar Bandas de Bollinger", group=grp_bb, display=display.none)
bb_len = input.int(20, "Longitud BB", minval=1, group=grp_bb, display=display.none)
bb_ma_type = input.string("SMA", "Tipo MA BB", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group=grp_bb, display=display.none)
bb_mult = input.float(2.0, "Desviación Estándar BB", minval=0.001, maxval=50, group=grp_bb, display=display.none)
bb_offset = input.int(0, "Offset BB", minval=-500, maxval=500, group=grp_bb, display=display.none)
bb_intraday_mode = input.string("Velas del gráfico", "BB por debajo de 1 hora", options=["Velas del gráfico", "Equivalente en días", "Usar velas diarias"], group=grp_bb, display=display.none)
bb_hourly_mode = input.string("Equivalente en días", "BB de 1 hora en adelante (1h, 4h...)", options=["Equivalente en días", "Velas del gráfico", "Usar velas diarias"], group=grp_bb, display=display.none)
string index_ticker = "SP:SPX"
bool use_regime = true
grp_guard = "FILTRO ANTI-ROTACION"
use_guard = input.bool(true, "Activar filtro en zona de riesgo", group=grp_guard, display=display.none)
use_calm = input.bool(true, "Activar filtro en zona sin riesgo", group=grp_guard, display=display.none)
bool guard_ema = false
bool calm_ema = false
int guard_exit_days = 5
float guard_gap = 100.0
float rot_gap = 0.0
string guard_def = "Auto (menor volatilidad)"
int guard_vol_len = 60
int guard_window = 60
string calm_def = "Auto (mayor volatilidad)"
float calm_gap = 100.0
int calm_exit_days = 5
int calm_window = 60
grp_metrics = "RSI en Métricas (SPX)"
use_rsi_spx_metrics = input.bool(true, "RSI del SPX", group=grp_metrics, display=display.none)
use_rsi_comb_metrics = input.bool(false, "RSI combinado", group=grp_metrics, display=display.none)
grp_visual = "Ajuste Visual"
grp_kernel = "Coloreado de Velas (Kernel Regression)"
use_kernel_color = input.bool(true, "Activar coloreado de velas por Kernel Regression", group=grp_kernel, display=display.none)
kr_bandwidth = input.int(45, "Bandwidth (h)", group=grp_kernel, minval=2, maxval=200, display=display.none)
kr_mid_len = input.int(150, "Mid Lookback (SMA de AV)", group=grp_kernel, minval=10, maxval=500, display=display.none)
kr_cyan = input.color(#00E5FF, "Color Alcista", group=grp_kernel, display=display.none)
kr_fuchsia = input.color(#FF12F7, "Color Bajista", group=grp_kernel, display=display.none)
kr_intraday_mode = input.string("Adaptar al gráfico", "Kernel en intradía", options=["Adaptar al gráfico", "Usar velas diarias"], group=grp_kernel, display=display.none)
kr_bars_per_day_in = input.int(0, "Velas por día (0 = auto)", minval=0, maxval=100, group=grp_kernel, display=display.none)
grp_dom = "Dominancia en Intradía"
dom_intraday_mode = input.string("Adaptar al gráfico", "Dominancia en intradía", options=["Adaptar al gráfico", "Usar velas diarias"], group=grp_dom, display=display.none)
grp_risk = "Riesgo Sistemático (SPX)"
int brm_short_percentile = 504
int brm_long_percentile = 1260
int brm_vol_regime_period = 252
int brm_base_maturity = 20
float brm_transition_resist = 0.7
bool brm_use_adaptive_smooth = true
int brm_extreme_smoothing = 21
float extreme_critical_threshold = 0.30
int extreme_normal_smoothing = 9
float extreme_zone_offset = 0.15
use_extreme_risk = input.bool(true, "Activar Extreme Risk", group=grp_risk, display=display.none)
int extreme_risk_cooldown_bars = 23
float early_critical_threshold = 0.30
int early_normal_smoothing = 5
float early_zone_offset = -0.15
use_early_risk = input.bool(true, "Activar Early Risk", group=grp_risk, display=display.none)
use_extreme_risk_rsi = input.bool(true, "Activar Risk RSI", inline="risk_rsi", group=grp_risk, display=display.none)
extreme_rsi_threshold = input.float(23.0, "", inline="risk_rsi", minval=0.0, maxval=100.0, step=0.1, group=grp_risk, display=display.none)
show_risk_rsi_value = input.bool(true, "Mostrar valor de Risk RSI en la línea de estado", group=grp_risk, display=display.none)
show_risk_plot = input.bool(true, "Mostrar Plot de Score Sistémico", group=grp_risk, display=display.none)
show_ema_fast = input.bool(false, "Fast EMA", inline="ema_fast", group=grp_visual, display=display.none)
ema_fast_len = input.int(10, "", inline="ema_fast", minval=1, group=grp_visual, display=display.none)
show_ema_slow = input.bool(true, "Slow EMA", inline="ema_slow", group=grp_visual, display=display.none)
ema_slow_len = input.int(200, "", inline="ema_slow", minval=1, group=grp_visual, display=display.none)
float scale_min = 1.0
int scale_win = 300
int breadth_ad_ma_len = 50
int breadth_hl_len = 10
int breadth_pct_lookback = 252
bool use_breadth_in_composite = true
bool use_a = ticker_a != ""
bool use_b = ticker_b != ""
bool use_c = ticker_c != ""
bool use_d = ticker_d != ""
bool use_e = ticker_e != ""
bool is_multi = use_c or use_d or use_e
req_c = use_c ? ticker_c : (use_a ? ticker_a : "SP:SPX")
req_d = use_d ? ticker_d : (use_a ? ticker_a : "SP:SPX")
req_e = use_e ? ticker_e : (use_a ? ticker_a : "SP:SPX")
float W_CHAR = 1.0
float W_SPACE = 0.5
float W_EMOJI = 10.0
f_visual_width(string txt) =>
string remaining = txt
float total = 0.0
if str.contains(remaining, "🟢")
total += W_EMOJI
remaining := str.replace_all(remaining, "🟢", "")
if str.contains(remaining, "🟡")
total += W_EMOJI
remaining := str.replace_all(remaining, "🟡", "")
if str.contains(remaining, "🟠")
total += W_EMOJI
remaining := str.replace_all(remaining, "🟠", "")
if str.contains(remaining, "🔴")
total += W_EMOJI
remaining := str.replace_all(remaining, "🔴", "")
if str.contains(remaining, "⚪")
total += W_EMOJI
remaining := str.replace_all(remaining, "⚪", "")
if str.contains(remaining, "🟣")
total += W_EMOJI
remaining := str.replace_all(remaining, "🟣", "")
int len_sin_emoji = str.length(remaining)
string sin_espacios = str.replace_all(remaining, " ", "")
int n_espacios = len_sin_emoji - str.length(sin_espacios)
int n_normales = str.length(sin_espacios)
total + n_normales * W_CHAR + n_espacios * W_SPACE
f_pad_center_weighted(string txt, float target_visual) =>
float current = f_visual_width(txt)
float remaining = target_visual - current
int total_spaces = remaining > 0 ? math.round(remaining / W_SPACE) : 0
string result = txt
if total_spaces > 0
int left_pad = total_spaces / 2
int right_pad = total_spaces - left_pad
result := str.repeat(" ", left_pad) + txt + str.repeat(" ", right_pad)
result
f_ma(source, length, _type) =>
switch _type
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
f_bb(len, ma_type, mult) =>
float basis = f_ma(close, len, ma_type)
float dev = mult * ta.stdev(close, len)
[basis, basis + dev, basis - dev]
f_calc_tail_risk_score(float c1, float c2, float c3, float c4) =>
arr = array.new_float(4)
array.set(arr, 0, nz(c1, 50.0))
array.set(arr, 1, nz(c2, 50.0))
array.set(arr, 2, nz(c3, 50.0))
array.set(arr, 3, nz(c4, 50.0))
array.sort(arr, order.ascending)
float_idx = 0.7 * 3.0
lower_idx = math.floor(float_idx)
upper_idx = math.min(3, lower_idx + 1)
weight = float_idx - lower_idx
lower_val = array.get(arr, int(lower_idx))
upper_val = array.get(arr, int(upper_idx))
quantile_score = lower_val * (1 - weight) + upper_val * weight
max_comp = array.max(arr)
tail_penalty = max_comp > 85 ? (max_comp - 85) * 0.3 : 0.0
(100.0 - math.min(100.0, quantile_score + tail_penalty)) / 100.0
f_risk_bundle(short_len, long_len, vol_period, critical_thr, base_maturity, transition_resist, use_adapt, normal_smooth, extreme_smooth, early_smooth) =>
close_252 = nz(close[252], close)
yoy_return_raw = (close - close_252) / close_252 * 100
yoy_pct_short = ta.percentrank(yoy_return_raw, short_len)
yoy_pct_long = ta.percentrank(yoy_return_raw, long_len)
daily_return = close - nz(close[1], close)
positive_days = math.sum(daily_return > 0 ? 1.0 : 0.0, 63)
persistence_raw = positive_days / 63.0 * 100.0
pers_pct_short = ta.percentrank(persistence_raw, short_len)
pers_pct_long = ta.percentrank(persistence_raw, long_len)
ma200_val = ta.sma(close, 200)
atr200_val = ta.atr(200)
ma_dist_raw = atr200_val > 0 ? (close - ma200_val) / atr200_val : 0.0
ma_pct_short = ta.percentrank(ma_dist_raw, short_len)
ma_pct_long = ta.percentrank(ma_dist_raw, long_len)
close_63 = nz(close[63], close)
ret_63_raw = (close - close_63) / close_63 * 100
atr_63_val = ta.atr(63)
price_level_63 = ta.sma(close, 63)
norm_atr_raw = price_level_63 > 0 ? atr_63_val / price_level_63 * 100 : 1.0
efficiency_raw = norm_atr_raw > 0 ? ret_63_raw / norm_atr_raw : 0.0
eff_pct_short = ta.percentrank(efficiency_raw, short_len)
eff_pct_long = ta.percentrank(efficiency_raw, long_len)
comp1_raw = math.max(yoy_pct_short, yoy_pct_long)
comp2_raw = math.max(pers_pct_short, pers_pct_long)
comp3_raw = math.max(ma_pct_short, ma_pct_long)
comp4_raw = math.max(eff_pct_short, eff_pct_long)
atr_14_val = ta.atr(14)
price_14_val = ta.sma(close, 14)
norm_atr_regime = price_14_val > 0 ? atr_14_val / price_14_val * 100 : 1.0
vol_percentile = ta.percentrank(norm_atr_regime, vol_period)
vol_maturity_scalar = vol_percentile < 25 ? 1.5 : vol_percentile > 75 ? 0.6 : 1.0
regime_scaled_maturity = base_maturity * vol_maturity_scalar
raw_score = f_calc_tail_risk_score(comp1_raw, comp2_raw, comp3_raw, comp4_raw)
var float smoothed_score = na
is_in_extreme = raw_score < 0.3 or raw_score > 0.8
smooth_period = use_adapt ? (is_in_extreme ? extreme_smooth : normal_smooth) : normal_smooth
alpha = 2.0 / (smooth_period + 1.0)
smoothed_score := na(smoothed_score) ? raw_score : smoothed_score + alpha * (raw_score - smoothed_score)
var float early_smoothed = na
early_period = use_adapt ? (is_in_extreme ? extreme_smooth : early_smooth) : early_smooth
early_alpha = 2.0 / (early_period + 1.0)
early_smoothed := na(early_smoothed) ? raw_score : early_smoothed + early_alpha * (raw_score - early_smoothed)
var int state_code = 2
var int bars_in_state = 0
var float state_confidence = 0.0
proposed_code = smoothed_score < critical_thr ? 0 : smoothed_score < critical_thr + 0.2 ? 1 : 2
state_maturity = math.min(1.0, bars_in_state / regime_scaled_maturity)
score_supports_state = (state_code == 0 and smoothed_score < critical_thr + 0.05) or
(state_code == 1 and smoothed_score >= critical_thr - 0.05 and smoothed_score < critical_thr + 0.25) or
(state_code == 2 and smoothed_score >= critical_thr + 0.15)
state_confidence := score_supports_state ? math.min(1.0, state_confidence + 0.05) : math.max(0.0, state_confidence - 0.1)
transition_allowed = state_maturity < 0.5 or state_confidence < transition_resist or
(proposed_code != state_code and
((proposed_code == 0 and smoothed_score < critical_thr - 0.05) or
(proposed_code == 2 and smoothed_score > critical_thr + 0.25)))
if transition_allowed and proposed_code != state_code
state_code := proposed_code
bars_in_state := 1
state_confidence := 0.3
else
bars_in_state := bars_in_state + 1
[state_code, smoothed_score, early_smoothed]
f_ad_parts(int ma_len, int pct_lookback) =>
float ad_line = ta.cum(nz(close))
float ad_dev = ad_line - ta.sma(ad_line, ma_len)
float ad_pct = ta.percentrank(ad_dev, pct_lookback)
[ad_dev, ad_pct]
f_score_txt(float v) =>
na(v) ? "-" : str.tostring(v, "#")
f_breadth_label(float score) =>
na(score) ? "-" : score >= 60 ? "Sana" : score >= 40 ? "Neutral" : "Débil"
f_vix_stress_weight(float vix) =>
na(vix) ? 0.0 : math.max(0.0, math.min(1.0, (vix - 25.0) / 10.0))
f_vix_base_risk(float vix) =>
float r = 95.0
if vix <= 10.0
r := 10.0
else if vix <= 15.0
r := 10.0 + (vix - 10.0) / 5.0 * 15.0
else if vix <= 25.0
r := 25.0 + (vix - 15.0) / 10.0 * 25.0
else if vix <= 37.0
r := 50.0 + (vix - 25.0) / 12.0 * 25.0
else if vix <= 50.0
r := 75.0 + (vix - 37.0) / 13.0 * 20.0
r
f_vix_risk_score(float vix) =>
math.max(0.0, math.min(100.0, f_vix_base_risk(vix)))
f_rsi_risk_score(float rsi) =>
float oversold = 100.0 - rsi
float overbought = 50.0 * math.max(0.0, math.min(1.0, (rsi - 65.0) / 25.0))
math.max(0.0, math.min(100.0, math.max(oversold, overbought)))
f_breadth_risk_score(float b_score, float vix) =>
float base = 100.0 - b_score
float s = f_vix_stress_weight(vix)
base + s * math.max(0.0, 50.0 - base)
f_composite_metrics_score(float vix, float rsi, float b_score) =>
float acc = 0.0
float w = 0.0
if not na(vix)
acc += f_vix_risk_score(vix) * 0.4
w += 0.4
if not na(rsi)
acc += f_rsi_risk_score(rsi) * 0.3
w += 0.3
if not na(b_score)
acc += f_breadth_risk_score(b_score, vix) * 0.3
w += 0.3
w > 0 ? math.max(0.0, math.min(100.0, acc / w)) : na
bool la_daily = timeframe.isdaily and timeframe.multiplier == 1
f_get_index_data(sym, tf, trend_len) =>
request.security(sym, tf, [close, ta.rsi(close, 14), ta.ema(close, 21), ta.ema(close, 80), ta.ema(close, 90), ta.ema(close, 200), ta.sma(close, trend_len)], gaps = barmerge.gaps_off, lookahead = la_daily ? barmerge.lookahead_on : barmerge.lookahead_off)
f_get_asset_data(sym, tf, trend_len, vol_len) =>
request.security(sym, tf, [close, ta.rsi(close, 14), ta.sma(close, trend_len), ((ta.ema(close, 20) / ta.ema(close, 60)) - 1) * 100, ta.stdev(close / close[1] - 1, vol_len)], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
bool sc_native = timeframe.isintraday and dom_intraday_mode == "Adaptar al gráfico"
f_bpd_estimate() =>
float sess_min = (syminfo.type == "crypto" or syminfo.type == "forex") ? 1440.0 : 390.0
math.max(1, math.round(sess_min / (timeframe.in_seconds() / 60.0)))
f_live_bpd(int fb, int fixed) =>
var int cnt = 0
var int days_seen = 0
var int cur = fb
var int[] hist = array.new_int()
if timeframe.change("D")
if days_seen >= 2 and cnt > 0
array.push(hist, cnt)
if array.size(hist) > 5
array.shift(hist)
cur := math.max(1, math.round(array.median(hist)))
days_seen += 1
cnt := 1
else
cnt += 1
fixed > 0 ? fixed : cur
f_ema_dyn(float src, int len) =>
var float e = na
float a = 2.0 / (len + 1.0)
e := na(src) ? e : (na(e) ? src : e + a * (src - e))
e
f_rma_dyn(float src, int len) =>
var float r = na
float a = 1.0 / len
r := na(src) ? r : (na(r) ? src : r + a * (src - r))
r
f_ma_dyn(float source, int length, string _type) =>
switch _type
"SMA" => ta.sma(source, length)
"EMA" => f_ema_dyn(source, length)
"SMMA (RMA)" => f_rma_dyn(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
f_score_live(int fb, int fixed) =>
int bpd = f_live_bpd(fb, fixed)
float ef = f_ema_dyn(close, 20 * bpd)
float es = f_ema_dyn(close, 60 * bpd)
((ef / es) - 1) * 100
f_get_score_native(sym, int fb, int fixed) =>
request.security(sym, timeframe.period, f_score_live(fb, fixed), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
int bpd_est = f_bpd_estimate()
int bpd_live = f_live_bpd(bpd_est, 0)
int bpd_chart = kr_bars_per_day_in > 0 ? kr_bars_per_day_in : bpd_live
int sc_fixed = sc_native ? kr_bars_per_day_in : 1
[index_close, rsi_spx, ema21_spx, ema80_index, ema90_spx, ema200_spx, index_sma] = f_get_index_data(index_ticker, sec_tf, ma_trend_len)
[close_a, rsi_a, sma_a, score_a_raw, vola_a] = f_get_asset_data(ticker_a, sec_tf, ma_trend_len, guard_vol_len)
[close_b, rsi_b, sma_b, score_b_raw, vola_b] = f_get_asset_data(ticker_b, sec_tf, ma_trend_len, guard_vol_len)
[close_c, rsi_c, sma_c, score_c_raw, vola_c] = f_get_asset_data(req_c, sec_tf, ma_trend_len, guard_vol_len)
[close_d, rsi_d, sma_d, score_d_raw, vola_d] = f_get_asset_data(req_d, sec_tf, ma_trend_len, guard_vol_len)
[close_e, rsi_e, sma_e, score_e_raw, vola_e] = f_get_asset_data(req_e, sec_tf, ma_trend_len, guard_vol_len)
float score_a_nat = f_get_score_native(ticker_a, bpd_est, sc_fixed)
float score_b_nat = f_get_score_native(ticker_b, bpd_est, sc_fixed)
float score_c_nat = f_get_score_native(req_c, bpd_est, sc_fixed)
float score_d_nat = f_get_score_native(req_d, bpd_est, sc_fixed)
float score_e_nat = f_get_score_native(req_e, bpd_est, sc_fixed)
[brm_state_code, brm_score, early_score] = request.security("SP:SPX", sec_tf, f_risk_bundle(brm_short_percentile, brm_long_percentile, brm_vol_regime_period, extreme_critical_threshold, brm_base_maturity, brm_transition_resist, brm_use_adaptive_smooth, extreme_normal_smoothing, brm_extreme_smoothing, early_normal_smoothing), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
[rsi_tech_fixed, score_tech_fixed] = request.security("SP:IXT", sec_tf, [ta.rsi(close, 14), ((ta.ema(close, 20) / ta.ema(close, 60)) - 1) * 100], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
[rsi_staples_fixed, score_staples_fixed] = request.security("SP:IXR", sec_tf, [ta.rsi(close, 14), ((ta.ema(close, 20) / ta.ema(close, 60)) - 1) * 100], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
rsi_spx_fixed = request.security("SP:SPX", sec_tf, ta.rsi(close, 14), gaps = barmerge.gaps_off, lookahead = la_daily ? barmerge.lookahead_on : barmerge.lookahead_off)
float avg_rsi_fixed = (rsi_spx_fixed + rsi_tech_fixed + rsi_staples_fixed) / 3.0
bool riesgo_extremo_rsi_cond = avg_rsi_fixed < extreme_rsi_threshold
float rsi_eq_sum = nz(rsi_spx_fixed, 0.0)
int rsi_eq_n = na(rsi_spx_fixed) ? 0 : 1
if use_a and not na(rsi_a)
rsi_eq_sum += rsi_a
rsi_eq_n += 1
if use_b and not na(rsi_b)
rsi_eq_sum += rsi_b
rsi_eq_n += 1
if use_c and not na(rsi_c)
rsi_eq_sum += rsi_c
rsi_eq_n += 1
if use_d and not na(rsi_d)
rsi_eq_sum += rsi_d
rsi_eq_n += 1
if use_e and not na(rsi_e)
rsi_eq_sum += rsi_e
rsi_eq_n += 1
float avg_rsi_weighted = rsi_eq_n > 0 ? rsi_eq_sum / rsi_eq_n : avg_rsi_fixed
float rsi_metrics = use_rsi_comb_metrics ? avg_rsi_weighted : (use_rsi_spx_metrics ? rsi_spx_fixed : na)
vix_close_fixed = request.security("TVC:VIX", sec_tf, close, gaps = barmerge.gaps_off, lookahead = la_daily ? barmerge.lookahead_on : barmerge.lookahead_off)
f_vix_category(float v) =>
v <= 10.0 ? "Euforia" : v <= 20.0 ? "Calma" : v <= 30.0 ? "Neutral" : v < 44.0 ? "Miedo" : "Pánico"
string vix_category_text = f_vix_category(vix_close_fixed)
[_, ad_score] = request.security("USI:ADD", sec_tf, f_ad_parts(breadth_ad_ma_len, breadth_pct_lookback), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
float nyse_highs_avg = request.security("INDEX:HIGN", sec_tf, ta.sma(close, breadth_hl_len), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
float nyse_lows_avg = request.security("INDEX:LOWN", sec_tf, ta.sma(close, breadth_hl_len), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
float hl_total = nyse_highs_avg + nyse_lows_avg
float hl_score = na(hl_total) ? na : (hl_total > 0 ? (nyse_highs_avg - nyse_lows_avg) / hl_total * 50.0 + 50.0 : 50.0)
float pct_above_200 = request.security("INDEX:S5TH", sec_tf, close, gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
float pct_above_50 = request.security("INDEX:S5FI", sec_tf, close, gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
float ma_score = (na(pct_above_200) and na(pct_above_50)) ? na : (nz(pct_above_200, pct_above_50) + nz(pct_above_50, pct_above_200)) / 2.0
float breadth_sum = 0.0
int breadth_n = 0
if not na(ad_score)
breadth_sum += ad_score
breadth_n += 1
if not na(hl_score)
breadth_sum += hl_score
breadth_n += 1
if not na(ma_score)
breadth_sum += ma_score
breadth_n += 1
float breadth_score = breadth_n > 0 ? math.max(0.0, math.min(100.0, breadth_sum / breadth_n)) : na
float breadth_for_composite = use_breadth_in_composite ? breadth_score : na
float composite_metrics_score = f_composite_metrics_score(vix_close_fixed, rsi_metrics, breadth_for_composite)
string composite_metrics_circle = "⚪"
if na(composite_metrics_score)
composite_metrics_circle := "⚪"
else if composite_metrics_score >= 65
composite_metrics_circle := "🔴"
else if composite_metrics_score <= 35
composite_metrics_circle := "🟢"
bool sub_hour = timeframe.isintraday and timeframe.in_seconds() < 3600
string bb_mode_eff = sub_hour ? bb_intraday_mode : (timeframe.isintraday ? bb_hourly_mode : "Usar velas diarias")
bool bb_native = timeframe.isintraday and bb_mode_eff != "Usar velas diarias"
int bb_n = (bb_native and bb_mode_eff == "Equivalente en días") ? math.max(2, math.min(bb_len * bpd_chart, 4900)) : bb_len
[bb_basis_d, bb_upper_d, bb_lower_d] = request.security(syminfo.tickerid, sec_tf, f_bb(bb_len, bb_ma_type, bb_mult), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
float bb_basis_n = f_ma_dyn(close, bb_n, bb_ma_type)
float bb_dev_n = bb_mult * ta.stdev(close, bb_n)
float chart_bb_basis = bb_native ? bb_basis_n : bb_basis_d
float chart_bb_upper = bb_native ? bb_basis_n + bb_dev_n : bb_upper_d
float chart_bb_lower = bb_native ? bb_basis_n - bb_dev_n : bb_lower_d
bool bb_upper_pierce = low > chart_bb_upper
bool bb_lower_pierce = high < chart_bb_lower
var bool upper_signaled = false
var bool lower_signaled = false
if close <= chart_bb_basis
upper_signaled := false
if close >= chart_bb_basis
lower_signaled := false
bool bb_upper_pierce_first = bb_upper_pierce and not upper_signaled
if bb_upper_pierce_first
upper_signaled := true
bool bb_lower_pierce_first = bb_lower_pierce and not lower_signaled
if bb_lower_pierce_first
lower_signaled := true
is_bull_market = (not use_regime) or (index_close > index_sma)
bool blue_band_active = is_bull_market and (index_close < ema80_index)
bool red_band_active = not is_bull_market
bool tf_changed_day = timeframe.change("D")
bool new_day = timeframe.isdwm or tf_changed_day
int day_step = 0
if new_day
day_step := timeframe.isintraday ? 1 :
timeframe.isdaily ? timeframe.multiplier :
timeframe.isweekly ? 5 * timeframe.multiplier :
timeframe.ismonthly ? 21 * timeframe.multiplier : 1
int raw_zone = red_band_active ? 2 : (blue_band_active ? 1 : 0)
int ZONE_CONFIRM_BARS = 3
var int confirmed_zone_rsi = 0
var int zone_streak_rsi = 0
bool zone_changed_rsi = false
if raw_zone == confirmed_zone_rsi
zone_streak_rsi := 0
else if day_step > 0
zone_streak_rsi := zone_streak_rsi + day_step
if zone_streak_rsi >= ZONE_CONFIRM_BARS
zone_changed_rsi := true
confirmed_zone_rsi := raw_zone
zone_streak_rsi := 0
var bool extreme_rsi_alert_fired = false
if zone_changed_rsi
extreme_rsi_alert_fired := false
bool in_risk_band = blue_band_active or red_band_active
int EXTREME_BAND_END_CONFIRM_BARS = 15
var int bars_outside_band = 0
if in_risk_band
bars_outside_band := 0
else if day_step > 0
bars_outside_band := bars_outside_band + day_step
bool band_episode_ended = bars_outside_band >= EXTREME_BAND_END_CONFIRM_BARS
int ciclo_val = 1
string ciclo_name = "ESPERANDO"
color ciclo_color = color.gray
if index_close > ema21_spx
float dist = index_close - ema21_spx
float norm = math.min(1.0, dist / (ema21_spx * 0.05))
ciclo_val := math.max(1, math.round(21 - norm * 20))
ciclo_name := "Auge"
ciclo_color:= color.green
else if index_close >= ema90_spx and index_close <= ema21_spx
float range_size = ema21_spx - ema90_spx
float pos = range_size > 0 ? (ema21_spx - index_close) / range_size : 0.0
ciclo_val := math.round(22 + pos * (90 - 22))
ciclo_name := "Expansión"
ciclo_color:= color.blue
else if index_close >= ema200_spx and index_close < ema90_spx
float range_size = ema90_spx - ema200_spx
float pos = range_size > 0 ? (ema90_spx - index_close) / range_size : 0.0
ciclo_val := math.round(91 + pos * (200 - 91))
ciclo_name := "Crisis"
ciclo_color:= color.orange
else
float dist = ema200_spx - index_close
float norm = dist / (ema200_spx * 0.05)
ciclo_val := math.round(200 + math.min(50, norm * 50))
ciclo_name := "Recesión"
ciclo_color:= color.red
float score_a_ind = use_a ? (sc_native ? score_a_nat : score_a_raw) : -1.0
float score_b_ind = use_b ? (sc_native ? score_b_nat : score_b_raw) : -1.0
float score_c_ind = use_c ? (sc_native ? score_c_nat : score_c_raw) : -1.0
float score_d_ind = use_d ? (sc_native ? score_d_nat : score_d_raw) : -1.0
float score_e_ind = use_e ? (sc_native ? score_e_nat : score_e_raw) : -1.0
bool score_above_extreme_zone = brm_score >= (extreme_critical_threshold + extreme_zone_offset)
bool riesgo_extremo_cond = score_above_extreme_zone and (blue_band_active or red_band_active) and (score_staples_fixed > score_tech_fixed) and not extreme_rsi_alert_fired
bool score_above_early_zone = early_score >= (early_critical_threshold + early_zone_offset)
bool score_in_mid_zone = brm_score >= extreme_critical_threshold and brm_score < (extreme_critical_threshold + 0.2)
bool riesgo_early_cond = score_above_early_zone and blue_band_active and (score_staples_fixed > score_tech_fixed) and score_in_mid_zone
string riesgo_sist_text = ""
color riesgo_sist_color = color.gray
color riesgo_sist_txt = color.white
bool riesgo_extremo_display_cond = (use_extreme_risk and riesgo_extremo_cond) or (use_extreme_risk_rsi and riesgo_extremo_rsi_cond)
if brm_state_code == 0
riesgo_sist_text := "🟢 Bajo Riesgo"
riesgo_sist_color := color.green
riesgo_sist_txt := color.white
else if brm_state_code == 1
riesgo_sist_text := "⚪ Riesgo Neutral"
riesgo_sist_color := color.gray
riesgo_sist_txt := color.white
else if riesgo_extremo_display_cond
riesgo_sist_text := "🟣 Riesgo Extremo"
riesgo_sist_color := color.new(#7f1d1d, 0)
riesgo_sist_txt := color.white
else
riesgo_sist_text := "🔴 Riesgo Alto"
riesgo_sist_color := red_matte
riesgo_sist_txt := color.white
var string active_asset = "ESPERANDO"
var string extreme_close_pending = ""
var int bars_outside_blue = 0
if blue_band_active
bars_outside_blue := 0
else if day_step > 0
bars_outside_blue := bars_outside_blue + day_step
float extreme_label_step = ta.atr(14) * 1.2
var bool extreme_alert_fired = false
if band_episode_ended
extreme_alert_fired := false
var int bars_since_extreme_alert = 999999
bars_since_extreme_alert := bars_since_extreme_alert + day_step
var int bars_since_risk_event = 999999
bars_since_risk_event := bars_since_risk_event + day_step
bool extreme_cooldown_ok = bars_since_extreme_alert >= extreme_risk_cooldown_bars
bool extreme_fired_this_bar = false
if use_extreme_risk and riesgo_extremo_cond and not extreme_alert_fired and extreme_cooldown_ok and barstate.isconfirmed
string extreme_risk_text = extreme_close_pending == "" ? ("Extreme Risk\nClose " + active_asset) : "Extreme Risk"
label.new(bar_index, high, extreme_risk_text, style=label.style_label_down, color=color.new(#7f1d1d, 0), textcolor=color.white, size=size.tiny, force_overlay=true)
extreme_alert_fired := true
bars_since_extreme_alert := 0
bars_since_risk_event := 0
if extreme_close_pending == ""
extreme_close_pending := str.substring(active_asset, 4)
extreme_fired_this_bar := true
var bool early_alert_fired = false
if bars_outside_blue >= 5
early_alert_fired := false
bool early_fired_this_bar = false
if use_early_risk and riesgo_early_cond and not early_alert_fired and not extreme_fired_this_bar and barstate.isconfirmed
label.new(bar_index, high + extreme_label_step, "Early Risk", style=label.style_label_down, color=color.new(#b45309, 0), textcolor=color.white, size=size.tiny, force_overlay=true)
early_alert_fired := true
early_fired_this_bar := true
bool rsi_fired_this_bar = false
if use_extreme_risk_rsi and riesgo_extremo_rsi_cond and not extreme_rsi_alert_fired and barstate.isconfirmed
string risk_rsi_text = extreme_close_pending == "" ? ("Risk RSI\nClose " + active_asset) : "Risk RSI"
label.new(bar_index, high + extreme_label_step * 2, risk_rsi_text, style=label.style_label_down, color=color.new(#4c1d95, 0), textcolor=color.white, size=size.tiny, force_overlay=true)
if extreme_close_pending == ""
extreme_close_pending := str.substring(active_asset, 4)
extreme_rsi_alert_fired := true
bars_since_risk_event := 0
rsi_fired_this_bar := true
abs_momentum_a = not use_abs_mom or (close_a > sma_a)
abs_momentum_b = not use_abs_mom or (close_b > sma_b)
abs_momentum_c = not use_abs_mom or (close_c > sma_c)
abs_momentum_d = not use_abs_mom or (close_d > sma_d)
abs_momentum_e = not use_abs_mom or (close_e > sma_e)
bool risk_red = brm_state_code == 2 or brm_score >= extreme_critical_threshold + 0.2
bool below_ema200 = index_close < ema200_spx
var bool danger_zone = false
var int guard_calm_days = 0
if not use_guard
danger_zone := false
guard_calm_days := 0
else if risk_red and (not guard_ema or below_ema200)
danger_zone := true
guard_calm_days := 0
else if day_step > 0
guard_calm_days := risk_red ? 0 : guard_calm_days + day_step
if guard_calm_days >= guard_exit_days
danger_zone := false
bool risk_green = not risk_red and (brm_state_code == 0 or brm_score < extreme_critical_threshold)
bool above_ema200 = index_close > ema200_spx
var bool calm_zone = false
var int calm_off_days = 0
var int bars_since_calm = 999999
bars_since_calm := bars_since_calm + day_step
bool calm_was = calm_zone
if not use_calm
calm_zone := false
calm_off_days := 0
else if risk_green and (not calm_ema or above_ema200)
calm_zone := true
calm_off_days := 0
else if day_step > 0
calm_off_days := risk_green ? 0 : calm_off_days + day_step
if calm_off_days >= calm_exit_days
calm_zone := false
if calm_zone and not calm_was
bars_since_calm := 0
bool calm_active = calm_zone and not danger_zone
string target_asset = active_asset
if not is_multi
bool cross_to_a = ta.crossover(score_a_ind, score_b_ind)
bool cross_to_b = ta.crossover(score_b_ind, score_a_ind)
bool a_leads = score_a_ind > score_b_ind
bool b_leads = score_b_ind > score_a_ind
bool trig_a = cross_to_a or (use_catchup and a_leads and active_asset != "ETF A")
bool trig_b = cross_to_b or (use_catchup and b_leads and active_asset != "ETF B")
bool cond_a = abs_momentum_a and trig_a
bool cond_b = abs_momentum_b and trig_b
if cond_a
target_asset := "ETF A"
else if cond_b
target_asset := "ETF B"
else if active_asset == "ESPERANDO"
target_asset := use_b ? "ETF B" : "ETF A"
else
float current_score = na
if active_asset == "ETF A"
current_score := score_a_ind
else if active_asset == "ETF B"
current_score := score_b_ind
else if active_asset == "ETF C"
current_score := score_c_ind
else if active_asset == "ETF D"
current_score := score_d_ind
else if active_asset == "ETF E"
current_score := score_e_ind
float best_score_val = na
string best_asset = ""
if use_a and abs_momentum_a and not na(score_a_ind) and (best_asset == "" or score_a_ind > best_score_val)
best_score_val := score_a_ind
best_asset := "ETF A"
if use_b and abs_momentum_b and not na(score_b_ind) and (best_asset == "" or score_b_ind > best_score_val)
best_score_val := score_b_ind
best_asset := "ETF B"
if use_c and abs_momentum_c and not na(score_c_ind) and (best_asset == "" or score_c_ind > best_score_val)
best_score_val := score_c_ind
best_asset := "ETF C"
if use_d and abs_momentum_d and not na(score_d_ind) and (best_asset == "" or score_d_ind > best_score_val)
best_score_val := score_d_ind
best_asset := "ETF D"
if use_e and abs_momentum_e and not na(score_e_ind) and (best_asset == "" or score_e_ind > best_score_val)
best_score_val := score_e_ind
best_asset := "ETF E"
if is_bull_market
if best_asset != "" and best_asset != active_asset
if na(current_score) or (best_score_val > current_score + math.abs(current_score) * (buffer_pct / 100.0))
target_asset := best_asset
else
if best_asset != ""
target_asset := best_asset
if target_asset == "ESPERANDO" and best_asset != ""
target_asset := best_asset
if active_asset != "ESPERANDO" and target_asset != active_asset
float sc_act = active_asset == "ETF A" ? score_a_ind : active_asset == "ETF B" ? score_b_ind : active_asset == "ETF C" ? score_c_ind : active_asset == "ETF D" ? score_d_ind : score_e_ind
float sc_tgt = target_asset == "ETF A" ? score_a_ind : target_asset == "ETF B" ? score_b_ind : target_asset == "ETF C" ? score_c_ind : target_asset == "ETF D" ? score_d_ind : score_e_ind
float v_act = active_asset == "ETF A" ? vola_a : active_asset == "ETF B" ? vola_b : active_asset == "ETF C" ? vola_c : active_asset == "ETF D" ? vola_d : vola_e
float v_tgt = target_asset == "ETF A" ? vola_a : target_asset == "ETF B" ? vola_b : target_asset == "ETF C" ? vola_c : target_asset == "ETF D" ? vola_d : vola_e
bool guard_risk_down = guard_def == "Auto (menor volatilidad)" ? (v_tgt < v_act) : (guard_def != "Ninguno" and target_asset == guard_def)
bool guard_free = guard_risk_down or bars_since_risk_event <= guard_window
bool calm_free = calm_def == "Auto (mayor volatilidad)" ? (v_tgt > v_act) : calm_def == "Auto (menor volatilidad)" ? (v_tgt < v_act) : (calm_def != "Ninguno" and target_asset == calm_def)
calm_free := calm_free or bars_since_calm <= calm_window
float gap_req = rot_gap
if danger_zone and not guard_free
gap_req := guard_gap
else if calm_active and not calm_free
gap_req := calm_gap
if gap_req > 0 and not (sc_tgt > sc_act + gap_req)
target_asset := active_asset
active_asset := target_asset
bool buy_a = active_asset == "ETF A"
bool buy_b = active_asset == "ETF B"
bool buy_c = active_asset == "ETF C"
bool buy_d = active_asset == "ETF D"
bool buy_e = active_asset == "ETF E"
float final_display_score = -1.0
string leader_name = "ESPERANDO"
if not is_multi
if active_asset == "ETF A"
final_display_score := score_a_ind
leader_name := "ETF A"
else if active_asset == "ETF B"
final_display_score := score_b_ind
leader_name := "ETF B"
else
if score_a_ind >= score_b_ind
final_display_score := score_a_ind
leader_name := "ETF A"
else
final_display_score := score_b_ind
leader_name := "ETF B"
else
if use_a and not na(score_a_ind) and (leader_name == "ESPERANDO" or score_a_ind > final_display_score)
final_display_score := score_a_ind
leader_name := "ETF A"
if use_b and not na(score_b_ind) and (leader_name == "ESPERANDO" or score_b_ind > final_display_score)
final_display_score := score_b_ind
leader_name := "ETF B"
if use_c and not na(score_c_ind) and (leader_name == "ESPERANDO" or score_c_ind > final_display_score)
final_display_score := score_c_ind
leader_name := "ETF C"
if use_d and not na(score_d_ind) and (leader_name == "ESPERANDO" or score_d_ind > final_display_score)
final_display_score := score_d_ind
leader_name := "ETF D"
if use_e and not na(score_e_ind) and (leader_name == "ESPERANDO" or score_e_ind > final_display_score)
final_display_score := score_e_ind
leader_name := "ETF E"
string dom_interp = ""
color dom_color = color.gray
color dom_txt_color = color.black
if final_display_score >= 5.0
dom_interp := "🟢 DOMINANCIA FUERTE " + leader_name + " 🟢"
dom_color := color.green
dom_txt_color := color.black
else if final_display_score >= 1.0
dom_interp := "🟡 VENTAJA MODERADA " + leader_name + " 🟡"
dom_color := color.orange
dom_txt_color := color.black
else if final_display_score >= -1.0
dom_interp := "⚪ EQUILIBRIO / POSIBLE ROTACIÓN ⚪"
dom_color := color.white
dom_txt_color := color.black
else
dom_interp := "🔴 DOMINANCIA BAJISTA " + leader_name + " 🔴"
dom_color := color.red
dom_txt_color := color.white
var string last_long = "ESPERANDO"
var color last_long_color = color.gray
if buy_a and not buy_a[1]
last_long := "ETF A"
last_long_color := color.fuchsia
else if buy_b and not buy_b[1]
last_long := "ETF B"
last_long_color := color.orange
else if buy_c and not buy_c[1]
last_long := "ETF C"
last_long_color := color.aqua
else if buy_d and not buy_d[1]
last_long := "ETF D"
last_long_color := color.yellow
else if buy_e and not buy_e[1]
last_long := "ETF E"
last_long_color := color.purple
var string prev_asset = "ESPERANDO"
bool has_changed = (active_asset != prev_asset)
string cambio_text = has_changed ? ("Cambio a " + active_asset + " (Score: " + str.tostring(final_display_score, "#.##") + "%)") : "Sin cambios"
color cambio_bg = has_changed ? color.navy : color.white
color cambio_txt = has_changed ? color.white : color.black
prev_asset := active_asset
f_signal_label(cond_now, cond_prev, letter, col_long, pending) =>
bool consumed = false
if cond_now and not cond_prev
label.new(bar_index, low, "Long " + letter, style=label.style_label_up, color=color.new(col_long, 0), textcolor=color.white, size=size.tiny, force_overlay=true)
if cond_prev and not cond_now
if pending == letter
consumed := true
else
label.new(bar_index, high, "Close " + letter, style=label.style_label_down, color=color.new(color.gray, 0), textcolor=color.white, size=size.tiny, force_overlay=true)
consumed
if f_signal_label(buy_a, buy_a[1], "A", color.fuchsia, extreme_close_pending)
extreme_close_pending := ""
if f_signal_label(buy_b, buy_b[1], "B", color.orange, extreme_close_pending)
extreme_close_pending := ""
if f_signal_label(buy_c, buy_c[1], "C", color.aqua, extreme_close_pending)
extreme_close_pending := ""
if f_signal_label(buy_d, buy_d[1], "D", color.yellow, extreme_close_pending)
extreme_close_pending := ""
if f_signal_label(buy_e, buy_e[1], "E", color.purple, extreme_close_pending)
extreme_close_pending := ""
alertcondition((buy_a and not buy_a[1]) and barstate.isconfirmed, "Rotación a ETF A", "Rotación de activo: entrar en ETF A")
alertcondition((buy_b and not buy_b[1]) and barstate.isconfirmed, "Rotación a ETF B", "Rotación de activo: entrar en ETF B")
alertcondition((buy_c and not buy_c[1]) and barstate.isconfirmed, "Rotación a ETF C", "Rotación de activo: entrar en ETF C")
alertcondition((buy_d and not buy_d[1]) and barstate.isconfirmed, "Rotación a ETF D", "Rotación de activo: entrar en ETF D")
alertcondition((buy_e and not buy_e[1]) and barstate.isconfirmed, "Rotación a ETF E", "Rotación de activo: entrar en ETF E")
alertcondition(((buy_a and not buy_a[1]) or (buy_b and not buy_b[1]) or (buy_c and not buy_c[1]) or (buy_d and not buy_d[1]) or (buy_e and not buy_e[1])) and barstate.isconfirmed, "Cualquier Rotación", "Se ha producido un cambio de activo dominante")
alertcondition(extreme_fired_this_bar, "Extreme Risk", "Extreme Risk: riesgo sistémico extremo, valorar cerrar posición")
alertcondition(early_fired_this_bar, "Early Risk", "Early Risk: aviso temprano de riesgo sistémico")
alertcondition(rsi_fired_this_bar, "Risk RSI", "Risk RSI: RSI medio por debajo del umbral, valorar cerrar posición")
float alert_ema_slow_d = request.security(syminfo.tickerid, sec_tf, ta.ema(close, ema_slow_len), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
float alert_ema_fast_d = request.security(syminfo.tickerid, sec_tf, ta.ema(close, ema_fast_len), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
alertcondition(ta.crossunder(close, alert_ema_slow_d) and barstate.isconfirmed, "Gráfico bajo EMA 200", "El gráfico ha cruzado por debajo de la EMA 200")
alertcondition(ta.crossover(close, alert_ema_slow_d) and barstate.isconfirmed, "Gráfico sobre EMA 200", "El gráfico ha recuperado la EMA 200")
alertcondition(ta.crossover(alert_ema_fast_d, alert_ema_slow_d) and barstate.isconfirmed, "Fast EMA sobre Slow EMA", "La Fast EMA ha cruzado por encima de la Slow EMA")
alertcondition(ta.crossunder(alert_ema_fast_d, alert_ema_slow_d) and barstate.isconfirmed, "Fast EMA bajo Slow EMA", "La Fast EMA ha cruzado por debajo de la Slow EMA")
bgcolor(red_band_active ? color.new(color.red, 90) : (blue_band_active ? color.new(color.blue, 90) : na))
f_kr_daily(int h, int mid_len) =>
var float[] w_ep = array.new_float()
var float[] w_lo = array.new_float()
var float[] w_wa = array.new_float()
if array.size(w_ep) == 0
for i = 0 to h
float u = (i * i) / (h * h)
float uw = i / h
array.push(w_ep, u <= 1.0 ? 0.75 * (1.0 - u) : 0.0)
array.push(w_lo, 1.0 / (math.exp(u) + 2.0 + math.exp(-u)))
array.push(w_wa, math.cos(uw * math.pi / 2.0) * (1.0 - uw))
float s_ep = 0.0
float s_lo = 0.0
float s_wa = 0.0
float sw_ep = 0.0
float sw_lo = 0.0
float sw_wa = 0.0
for i = 0 to h
float c = close[i]
float w1 = array.get(w_ep, i)
float w2 = array.get(w_lo, i)
float w3 = array.get(w_wa, i)
s_ep += c * w1
s_lo += c * w2
s_wa += c * w3
sw_ep += w1
sw_lo += w2
sw_wa += w3
float ep = sw_ep > 0 ? s_ep / sw_ep : close
float lo = sw_lo > 0 ? s_lo / sw_lo : close
float wa = sw_wa > 0 ? s_wa / sw_wa : close
float ep_dev = ep != 0 ? (close - ep) / ep : 0.0
float lo_dev = lo != 0 ? (close - lo) / lo : 0.0
float wa_dev = wa != 0 ? (close - wa) / wa : 0.0
float av = (ep_dev + lo_dev + wa_dev) / 3.0
float mid = ta.sma(av, mid_len)
[av, mid]
f_kr_dyn(int n, int stride, int mid_len, bool sub) =>
var float[] w_ep = array.new_float()
var float[] w_lo = array.new_float()
var float[] w_wa = array.new_float()
var int last_n = -1
if n != last_n
array.clear(w_ep)
array.clear(w_lo)
array.clear(w_wa)
for i = 0 to n
float u = (i * i) / (n * n)
float uw = i / n
array.push(w_ep, u <= 1.0 ? 0.75 * (1.0 - u) : 0.0)
array.push(w_lo, 1.0 / (math.exp(u) + 2.0 + math.exp(-u)))
array.push(w_wa, math.cos(uw * math.pi / 2.0) * (1.0 - uw))
last_n := n
float s_ep = 0.0
float s_lo = 0.0
float s_wa = 0.0
float sw_ep = 0.0
float sw_lo = 0.0
float sw_wa = 0.0
for i = 0 to n
float c = close[i * stride]
if not na(c)
float w1 = array.get(w_ep, i)
float w2 = array.get(w_lo, i)
float w3 = array.get(w_wa, i)
s_ep += c * w1
s_lo += c * w2
s_wa += c * w3
sw_ep += w1
sw_lo += w2
sw_wa += w3
float ep = sw_ep > 0 ? s_ep / sw_ep : close
float lo = sw_lo > 0 ? s_lo / sw_lo : close
float wa = sw_wa > 0 ? s_wa / sw_wa : close
float ep_dev = ep != 0 ? (close - ep) / ep : 0.0
float lo_dev = lo != 0 ? (close - lo) / lo : 0.0
float wa_dev = wa != 0 ? (close - wa) / wa : 0.0
float av = (ep_dev + lo_dev + wa_dev) / 3.0
float mid_sma = ta.sma(av, math.min(mid_len, 4000))
float mid_ema = f_ema_dyn(av, mid_len)
float mid = (sub and (mid_len > 4000 or na(mid_sma))) ? mid_ema : mid_sma
[av, mid]
int KR_MAX_SAMPLES = 120
int KR_MAX_BACK = 4900
bool kr_native = timeframe.isintraday and kr_intraday_mode == "Adaptar al gráfico"
bool kr_sub = kr_native and sub_hour
int kr_bpd = kr_native ? bpd_chart : 1
int kr_span = kr_native ? math.max(2, math.min(kr_bandwidth * kr_bpd, kr_sub ? KR_MAX_BACK : 1000)) : 2
int kr_stride = kr_sub ? math.max(1, math.ceil(kr_span / KR_MAX_SAMPLES)) : 1
int kr_n = kr_sub ? math.max(2, math.round(kr_span / kr_stride)) : kr_span
int kr_mid = kr_native ? math.max(10, kr_sub ? kr_mid_len * kr_bpd : math.min(kr_mid_len * kr_bpd, 4000)) : 10
[kr_AV_d, kr_Mid_d] = request.security(syminfo.tickerid, sec_tf, f_kr_daily(kr_bandwidth, kr_mid_len), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
[kr_AV_n, kr_Mid_n] = f_kr_dyn(kr_n, kr_stride, kr_mid, kr_sub)
kr_AV = kr_native ? kr_AV_n : kr_AV_d
kr_Mid = kr_native ? kr_Mid_n : kr_Mid_d
kr_isBullish = kr_AV > kr_Mid
float ema_fast_d = request.security(syminfo.tickerid, sec_tf, ta.ema(close, ema_fast_len), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
float ema_slow_d = request.security(syminfo.tickerid, sec_tf, ta.ema(close, ema_slow_len), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
kr_candleColor = kr_isBullish ? kr_cyan : kr_fuchsia
barcolor(use_kernel_color ? kr_candleColor : na, title="Color de Velas (Kernel Regression)")
float plot_a = score_a_ind
float plot_b = score_b_ind
float plot_c = score_c_ind
float plot_d = score_d_ind
float plot_e = score_e_ind
float plot_risk = brm_score
float plot_bb_b = chart_bb_basis
float plot_bb_u = chart_bb_upper
float plot_bb_l = chart_bb_lower
float plot_ef = ema_fast_d
float plot_es = ema_slow_d
plot(plot_a, title="Fuerza A", color=color.fuchsia, linewidth=2, display=use_a ? display.pane : display.none)
plot(plot_b, title="Fuerza B", color=color.orange, linewidth=2, display=use_b ? display.pane : display.none)
plot(plot_c, title="Fuerza C", color=color.aqua, linewidth=2, display=use_c ? display.pane : display.none)
plot(plot_d, title="Fuerza D", color=color.yellow, linewidth=2, display=use_d ? display.pane : display.none)
plot(plot_e, title="Fuerza E", color=color.purple, linewidth=2, display=use_e ? display.pane : display.none)
plot(0, title="Fuerza: Cero", color=color.new(#2b2b2b, 70), style=plot.style_line, linewidth=1, display=display.pane)
f_score_zone_color(float score) =>
score < extreme_critical_threshold ? color.green : score < extreme_critical_threshold + 0.2 ? color.gray : color.red
score_plot_scale = 30.0
color score_plot_color = f_score_zone_color(brm_score)
plot(show_risk_plot ? 0.0 : na, title="Score Sistémico: Línea 0.5", color=color.new(#2b2b2b, 70), style=plot.style_line, linewidth=1, display=show_risk_plot ? display.pane : display.none)
plot(show_risk_plot ? (plot_risk - 0.5) * score_plot_scale : na, title="Score Sistémico (Suavizado)", color=score_plot_color, linewidth=2, display=show_risk_plot ? display.pane : display.none)
plot(show_bb ? plot_bb_b : na, "BB Basis (Chart)", color=#2962FF, offset=bb_offset, force_overlay=true, display=display.pane)
plot(show_bb ? plot_bb_u : na, "BB Upper (Chart)", color=#F23645, offset=bb_offset, force_overlay=true, display=display.pane)
plot(show_bb ? plot_bb_l : na, "BB Lower (Chart)", color=#089981, offset=bb_offset, force_overlay=true, display=display.pane)
plot(show_ema_fast ? plot_ef : na, title="Fast EMA", color=color.green, linewidth=1, force_overlay=true, display=display.pane)
plot(show_ema_slow ? plot_es : na, title="Slow EMA", color=color.yellow, linewidth=1, force_overlay=true, display=display.pane)
float amp_now = math.max(
use_a ? nz(math.abs(plot_a)) : 0.0, use_b ? nz(math.abs(plot_b)) : 0.0,
use_c ? nz(math.abs(plot_c)) : 0.0, use_d ? nz(math.abs(plot_d)) : 0.0,
use_e ? nz(math.abs(plot_e)) : 0.0,
show_risk_plot ? nz(math.abs((plot_risk - 0.5) * score_plot_scale)) : 0.0)
float amp_hi = ta.highest(amp_now, scale_win)
float scale_lim = math.max(scale_min, amp_hi * 1.15)
plot(-scale_lim, title="Suelo de Escala", color=color.new(color.white, 100), display=display.pane)
plot( scale_lim, title="Techo de Escala", color=color.new(color.white, 100), display=display.pane)
plot(rsi_a, title="RSI ETF A", color=color.fuchsia, display=use_a ? display.status_line : display.none)
plot(rsi_b, title="RSI ETF B", color=color.orange, display=use_b ? display.status_line : display.none)
plot(rsi_c, title="RSI ETF C", color=color.aqua, display=use_c ? display.status_line : display.none)
plot(rsi_d, title="RSI ETF D", color=color.yellow, display=use_d ? display.status_line : display.none)
plot(rsi_e, title="RSI ETF E", color=color.purple, display=use_e ? display.status_line : display.none)
plot(rsi_spx, title="RSI SPX (Índice)", color=color.black, display=display.status_line)
plot(avg_rsi_fixed, title="RSI Risk", color=color.red, display=show_risk_rsi_value ? display.status_line : display.none)
plot(vix_close_fixed, title="VIX", color=color.silver, display=display.status_line)
plot(composite_metrics_score, title="METRICAS (SPX)", color=color.blue, display=display.status_line)
if buy_a and not buy_a[1]
label.new(bar_index, -scale_lim * 0.9, "A", style=label.style_label_up, color=color.new(color.fuchsia, 0), textcolor=color.white, size=size.tiny)
if buy_b and not buy_b[1]
label.new(bar_index, -scale_lim * 0.9, "B", style=label.style_label_up, color=color.new(color.orange, 0), textcolor=color.white, size=size.tiny)
if buy_c and not buy_c[1]
label.new(bar_index, -scale_lim * 0.9, "C", style=label.style_label_up, color=color.new(color.aqua, 0), textcolor=color.white, size=size.tiny)
if buy_d and not buy_d[1]
label.new(bar_index, -scale_lim * 0.9, "D", style=label.style_label_up, color=color.new(color.yellow, 0), textcolor=color.white, size=size.tiny)
if buy_e and not buy_e[1]
label.new(bar_index, -scale_lim * 0.9, "E", style=label.style_label_up, color=color.new(color.purple, 0), textcolor=color.white, size=size.tiny)
plotchar(bb_upper_pierce_first, title="+1P BB Superior", char="", location=location.abovebar, color=color.green, text="+1P", size=size.tiny, force_overlay=true, display=display.pane)
plotchar(bb_lower_pierce_first, title="-1P BB Inferior", char="", location=location.belowbar, color=color.red, text="-1P", size=size.tiny, force_overlay=true, display=display.pane)
var table rsiTable = table.new(
position = position.bottom_right,
columns = 8,
rows = 9,
bgcolor = color.white,
border_width = 2,
border_color = color.black,
frame_width = 1,
frame_color = color.black)
if barstate.isfirst
table.cell(rsiTable, 0, 0, "CENTRO OPERATIVO", text_color=color.white, bgcolor=color.rgb(20, 20, 20), text_halign=text.align_center, text_size=size.tiny)
table.merge_cells(rsiTable, 0, 0, 7, 0)
table.cell(rsiTable, 0, 1, "RIESGO SISTEMÁTICO", text_color=color.black, bgcolor=color.rgb(230, 230, 230), text_halign=text.align_center, text_size=size.tiny)
table.merge_cells(rsiTable, 0, 1, 1, 1)
table.cell(rsiTable, 2, 1, "", text_color=color.white, bgcolor=color.gray, text_halign=text.align_center, text_size=size.tiny)
table.merge_cells(rsiTable, 2, 1, 7, 1)
table.cell(rsiTable, 0, 2, "CICLO / TENDENCIA", text_color=color.black, bgcolor=color.rgb(230, 230, 230), text_halign=text.align_center, text_size=size.tiny)
table.merge_cells(rsiTable, 0, 2, 1, 2)
table.cell(rsiTable, 2, 2, "", text_color=color.white, bgcolor=color.gray, text_halign=text.align_center, text_size=size.tiny)
table.merge_cells(rsiTable, 2, 2, 4, 2)
table.cell(rsiTable, 5, 2, "", text_color=color.white, bgcolor=color.gray, text_halign=text.align_center, text_size=size.tiny)
table.merge_cells(rsiTable, 5, 2, 7, 2)
table.cell(rsiTable, 0, 3, "METRICAS (SPX)", text_color=color.black, bgcolor=color.rgb(230, 230, 230), text_halign=text.align_center, text_size=size.tiny)
table.merge_cells(rsiTable, 0, 3, 1, 3)
table.cell(rsiTable, 2, 3, "", text_color=color.black, bgcolor=color.white, text_halign=text.align_center, text_size=size.tiny)
table.merge_cells(rsiTable, 2, 3, 3, 3)
table.cell(rsiTable, 4, 3, "", text_color=color.black, bgcolor=color.white, text_halign=text.align_center, text_size=size.tiny)
table.merge_cells(rsiTable, 4, 3, 5, 3)
table.cell(rsiTable, 6, 3, "", text_color=color.black, bgcolor=color.white, text_halign=text.align_center, text_size=size.tiny)
table.merge_cells(rsiTable, 6, 3, 7, 3)
table.cell(rsiTable, 0, 4, "DOMINANCIA", text_color=color.black, bgcolor=color.rgb(230, 230, 230), text_halign=text.align_center, text_size=size.tiny)
table.merge_cells(rsiTable, 0, 4, 1, 4)
table.cell(rsiTable, 2, 4, "", text_color=color.white, bgcolor=color.gray, text_halign=text.align_center, text_size=size.tiny)
table.merge_cells(rsiTable, 2, 4, 7, 4)
table.cell(rsiTable, 0, 5, "FUERZA DE DOMINANCIA", text_color=color.black, bgcolor=color.rgb(230, 230, 230), text_halign=text.align_center, text_size=size.tiny)
table.merge_cells(rsiTable, 0, 5, 1, 5)
table.cell(rsiTable, 2, 5, "", text_color=color.black, bgcolor=color.gray, text_halign=text.align_center, text_size=size.tiny)
table.merge_cells(rsiTable, 2, 5, 7, 5)
table.cell(rsiTable, 0, 6, "CAMBIO TENDENCIA", text_color=color.black, bgcolor=color.rgb(230, 230, 230), text_halign=text.align_center, text_size=size.tiny)
table.merge_cells(rsiTable, 0, 6, 1, 6)
table.cell(rsiTable, 2, 6, "", text_color=color.white, bgcolor=color.white, text_halign=text.align_center, text_size=size.tiny)
table.merge_cells(rsiTable, 2, 6, 7, 6)
table.cell(rsiTable, 0, 7, "ESTADO DE VELA", text_color=color.black, bgcolor=color.rgb(230, 230, 230), text_halign=text.align_center, text_size=size.tiny)
table.merge_cells(rsiTable, 0, 7, 1, 7)
table.cell(rsiTable, 2, 7, "", text_color=color.black, bgcolor=color.white, text_halign=text.align_center, text_size=size.tiny)
table.merge_cells(rsiTable, 2, 7, 7, 7)
string ciclo_text = ciclo_name + " (EMA " + str.tostring(ciclo_val) + ")"
string tendencia_name = ""
color tendencia_color = color.gray
color tendencia_text_color = color.white
if ciclo_val <= 21
tendencia_name := "🟢 Alcista"
tendencia_color := color.rgb(0, 100, 0)
tendencia_text_color := color.white
else if ciclo_val >= 22 and ciclo_val <= 55
tendencia_name := "🟡 Neutral-Alcista"
tendencia_color := color.yellow
tendencia_text_color := color.black
else if ciclo_val >= 56 and ciclo_val <= 90
tendencia_name := "🟠 Neutral-Bajista"
tendencia_color := color.orange
tendencia_text_color := color.black
else
tendencia_name := "🔴 Bajista"
tendencia_color := red_matte
tendencia_text_color := color.white
if barstate.islast
int table_pad_per_col = 5
int table_pad_target = table_pad_per_col * 3
int table_pad_target_third = table_pad_per_col * 2
int table_pad_target_full = table_pad_per_col * 6
table.cell(rsiTable, 2, 1, f_pad_center_weighted(riesgo_sist_text, table_pad_target_full), text_color=riesgo_sist_txt, bgcolor=riesgo_sist_color, text_halign=text.align_center, text_size=size.tiny)
string ciclo_text_padded = f_pad_center_weighted(ciclo_text, table_pad_target)
string tendencia_name_padded = f_pad_center_weighted(tendencia_name, table_pad_target)
table.cell(rsiTable, 2, 2, ciclo_text_padded, text_color=color.white, bgcolor=ciclo_color, text_halign=text.align_center, text_size=size.tiny)
table.cell(rsiTable, 5, 2, tendencia_name_padded, text_color=tendencia_text_color, bgcolor=tendencia_color, text_halign=text.align_center, text_size=size.tiny)
string composite_score_txt = na(composite_metrics_score) ? "-" : str.tostring(composite_metrics_score, "#")
table.cell(rsiTable, 0, 3, composite_metrics_circle + " METRICAS (SPX) (" + composite_score_txt + ")", text_color=color.black, bgcolor=color.rgb(230, 230, 230), text_halign=text.align_center, text_size=size.tiny)
bool vix_alert = not na(vix_close_fixed) and vix_close_fixed >= 30.0
color vix_bg = vix_alert ? red_matte : color.white
color vix_txt = vix_alert ? color.white : color.black
string vix_display_text = "VIX: " + str.tostring(vix_close_fixed, "#.##") + " (" + vix_category_text + ")"
string rsi_display_text = "RSI: " + (na(rsi_metrics) ? "-" : str.tostring(rsi_metrics, "#.##"))
string vix_display_text_padded = f_pad_center_weighted(vix_display_text, table_pad_target_third)
string rsi_display_text_padded = f_pad_center_weighted(rsi_display_text, table_pad_target_third)
table.cell(rsiTable, 2, 3, vix_display_text_padded, text_color=vix_txt, bgcolor=vix_bg, text_halign=text.align_center, text_size=size.tiny)
table.cell(rsiTable, 4, 3, rsi_display_text_padded, text_color=color.black, bgcolor=color.white, text_halign=text.align_center, text_size=size.tiny)
string breadth_label_txt = f_breadth_label(breadth_score)
string breadth_display_text = "Amp: " + f_score_txt(breadth_score) + " (" + breadth_label_txt + ")"
string breadth_display_text_padded = f_pad_center_weighted(breadth_display_text, table_pad_target_third)
string breadth_tooltip = "A/D: " + f_score_txt(ad_score) + " | Nuevos Máx/Mín: " + f_score_txt(hl_score) + " | % > medias: " + f_score_txt(ma_score) + "\nS&P 500 > SMA200: " + f_score_txt(pct_above_200) + "% | > SMA50: " + f_score_txt(pct_above_50) + "%"
table.cell(rsiTable, 6, 3, breadth_display_text_padded, text_color=color.black, bgcolor=color.white, text_halign=text.align_center, text_size=size.tiny, tooltip=breadth_tooltip)
table.cell(rsiTable, 2, 4, f_pad_center_weighted(last_long, table_pad_target_full), text_color=color.white, bgcolor=last_long_color, text_halign=text.align_center, text_size=size.tiny)
string interp_display_text = dom_interp + " (" + str.tostring(final_display_score, "#.##") + "%)"
table.cell(rsiTable, 2, 5, f_pad_center_weighted(interp_display_text, table_pad_target_full), text_color=dom_txt_color, bgcolor=dom_color, text_halign=text.align_center, text_size=size.tiny)
table.cell(rsiTable, 2, 6, f_pad_center_weighted(cambio_text, table_pad_target_full), text_color=cambio_txt, bgcolor=cambio_bg, text_halign=text.align_center, text_size=size.tiny)
string estado_vela_text = kr_isBullish ? "Alcista" : "Bajista"
color estado_vela_color = kr_isBullish ? kr_cyan : kr_fuchsia
table.cell(rsiTable, 2, 7, f_pad_center_weighted(estado_vela_text, table_pad_target_full), text_color=estado_vela_color, bgcolor=color.white, text_halign=text.align_center, text_size=size.tiny)