bl-esw-pinbar-market-lab.pine
Copy
//@version=6
indicator(title="BL-ESW Pinbar Market Lab", shorttitle="BLEMBI", overlay=true, max_labels_count=500)
// ============================================================
// Inputs
// ============================================================
price_src = input.source(close, "Source")
exponential = input.bool(true, "Exponential MA")
// Pinbar
grp_pin = "Pinbar"
show_pinbar = input.bool(true, "Show Pinbar Black", group=grp_pin)
pin_ratio = input.float(2.0, "Wick Body Ratio", minval=1.0, step=0.1, group=grp_pin)
// Market Lab(与 marketlab 项目 JS 的 prefix-causal 口径同步)
grp_lab = "Market Lab"
show_lab = input.bool(true, "Enable Cost Strategy", group=grp_lab)
show_cost_band = input.bool(true, "Show Cost Band", group=grp_lab)
show_delta_band = input.bool(true, "Show GetDelta Band", group=grp_lab)
show_lab_bg = input.bool(true, "Show Discount Premium BG", group=grp_lab)
show_lab_panel = input.bool(true, "Show Status Panel", group=grp_lab)
show_legend = input.bool(true, "Show Legend", group=grp_lab)
auto_adapt = input.bool(false, "Auto Adapt Profile (extension, OFF=site aligned)", group=grp_lab)
relax_mode = input.bool(false, "Relax Mode (extension, OFF=site aligned)", group=grp_lab)
trading_sessions_per_year = input.int(365, "Trading Sessions / Year", options=[365, 252, 242, 179], group=grp_lab)
delta_slope = input.float(0.30, "GetDelta Local Slope d", minval=0.0, step=0.01, group=grp_lab)
lp_range_width = input.float(0.10, "LP Range Width", minval=0.001, maxval=0.95, step=0.01, group=grp_lab)
lp_skew = input.float(1.0, "LP Skew", minval=0.01, step=0.05, group=grp_lab)
show_lp_band = input.bool(true, "Show LP Range", group=grp_lab)
show_position_row = input.bool(true, "Show Position Row", group=grp_lab)
show_match_row = input.bool(true, "Show Match Row", group=grp_lab)
profile = input.string("Balanced", "Profile", options=["Conservative", "Balanced", "Aggressive"], group=grp_lab)
// ============================================================
// MA / BBI
// ============================================================
ema_10 = ta.ema(price_src, 10)
sma_10 = ta.sma(price_src, 10)
ema_20 = ta.ema(price_src, 20)
sma_20 = ta.sma(price_src, 20)
ema_200 = ta.ema(price_src, 200)
sma_200 = ta.sma(price_src, 200)
ema_55 = ta.ema(price_src, 55)
sma_55 = ta.sma(price_src, 55)
ma8 = exponential ? ema_10 : sma_10
ma13 = exponential ? ema_20 : sma_20
ma21 = exponential ? ema_200 : sma_200
ma55 = exponential ? ema_55 : sma_55
M1 = ta.sma(close, 6)
M2 = ta.sma(close, 12)
M3 = ta.sma(close, 24)
BBI = (M1 + M2 + M3) / 3
buy_cond = ta.cross(ma21, ma55) and ma8 > ma13 and ma21 > ma55
sell_cond = ta.cross(ma21, ma55) and ma8 < ma13 and ma21 < ma55
// ============================================================
// Prefix-causal windows / cost anchor
// 每根历史 K 线只用当时可见前缀,追加未来数据不能改写旧值。
// cost=max(5,floor(sqrt(prefix_n)));recent=max(3,floor(sqrt(cost)));vol=cost;ATR=recent。
// ============================================================
prefix_n = bar_index + 1
cost_window = math.max(5, int(math.floor(math.sqrt(prefix_n))))
recent_window = math.max(3, int(math.floor(math.sqrt(cost_window))))
vol_window = cost_window
cost_observed = math.min(prefix_n, cost_window)
return_observed = math.max(1, math.min(bar_index, vol_window))
atr_observed = math.max(1, math.min(bar_index, recent_window))
typical_price = (high + low + close) / 3.0
cost_vol_sum = math.sum(volume, cost_observed)
cost_weighted_sum = math.sum(typical_price * volume, cost_observed)
cost_sma = ta.sma(typical_price, cost_observed)
cost_anchor = cost_vol_sum > 0 ? cost_weighted_sum / cost_vol_sum : cost_sma
// ============================================================
// Volatility / band(同步 JS rollingCost 的 sample stdev 口径)
// ============================================================
log_ret = not na(close[1]) and close[1] > 0 ? math.log(close / close[1]) : 0.0
annual_vol_raw = nz(ta.stdev(log_ret, return_observed, false), 0.0) * math.sqrt(trading_sessions_per_year)
annual_vol = annual_vol_raw
annual_vol_valid = bar_index >= 5 and annual_vol > 0
true_range = na(close[1]) ? 0.0 : math.max(high - low, math.max(math.abs(high - close[1]), math.abs(low - close[1])))
atr_recent = nz(ta.sma(true_range, atr_observed), 0.0)
atr_pct = close > 0 ? atr_recent / close : 0.0
vol_estimate_raw = nz(ta.stdev(log_ret, return_observed, false), 0.0)
vol_estimate = vol_estimate_raw * math.sqrt(math.min(recent_window, return_observed))
min_band = math.max(vol_estimate * 0.25, 0.005)
band_width = math.max(vol_estimate, min_band)
cost_low = cost_anchor * (1 - band_width)
cost_high = cost_anchor * (1 + band_width)
lp_lower = cost_anchor * math.max(1 - lp_range_width, 0.001)
lp_upper = cost_anchor * (1 + lp_range_width * lp_skew)
position_label = close > cost_high ? "高于成本带" : close < cost_low ? "低于成本带" : "成本带内"
momentum_fast = bar_index >= recent_window and close[recent_window] > 0 ? close / close[recent_window] - 1 : 0.0
cost_slope_recent = bar_index >= recent_window and cost_anchor[recent_window] > 0 ? cost_anchor / cost_anchor[recent_window] - 1 : 0.0
// ============================================================
// Expanding AR(1)-through-origin / dynamic recovery horizon
// rho 是前缀样本估计;H 是冻结当前成本沿目标后的条件情景坐标,不是预测。
// side 由 close 相对 cost_anchor 决定;long/short 分别以 cost_low/cost_high 为目标。
// cycle start 优先取当前自适应成本窗口的 low/high 极值;若目标不严格位于极值与锚之间,
// 则回扫最近一次当日 low<动态 cost_low / high>动态 cost_high 的穿越,并用当前目标/锚复核。
// q=(target-cycleStart)/(anchor-cycleStart)(按 side 归一方向),H=HL*log2(1/(1-q)).
// ============================================================
cost_distance = cost_anchor > 0 ? (close - cost_anchor) / cost_anchor : na
ar_xy = not na(cost_distance[1]) ? cost_distance * cost_distance[1] : 0.0
ar_x2 = not na(cost_distance[1]) ? cost_distance[1] * cost_distance[1] : 0.0
ar_sum_xy = ta.cum(ar_xy)
ar_sum_x2 = ta.cum(ar_x2)
rho = prefix_n >= 5 and ar_sum_x2 > 0 ? ar_sum_xy / ar_sum_x2 : na
rho_valid = not na(rho) and rho > 0 and rho < 1
ar_decay = rho_valid ? -math.log(rho) : na
half_life_sessions = rho_valid and ar_decay > 0 ? math.log(2.0) / ar_decay : na
cycle_side_short = close > cost_anchor
target_price = cycle_side_short ? cost_high : cost_low
target_source = cycle_side_short ? "adaptive-cost-upper" : "adaptive-cost-lower"
window_low_extreme = ta.lowest(low, cost_observed)
window_high_extreme = ta.highest(high, cost_observed)
window_cycle_start = cycle_side_short ? window_high_extreme : window_low_extreme
window_structure_valid = cycle_side_short ? window_cycle_start > target_price and target_price > cost_anchor : window_cycle_start < target_price and target_price < cost_anchor
// 保存逐日前缀中真正发生过的动态成本沿穿越;当前窗口极值无效时从最新记录向前回扫。
var lower_cross_prices = array.new_float()
var upper_cross_prices = array.new_float()
lower_crossed = low > 0 and cost_low > 0 and low < cost_low
upper_crossed = high > 0 and cost_high > 0 and high > cost_high
if lower_crossed
array.push(lower_cross_prices, low)
if upper_crossed
array.push(upper_cross_prices, high)
float fallback_cycle_start = na
int scan_index = na
if not window_structure_valid
scan_index := (cycle_side_short ? array.size(upper_cross_prices) : array.size(lower_cross_prices)) - 1
while scan_index >= 0 and na(fallback_cycle_start)
scan_price = cycle_side_short ? array.get(upper_cross_prices, scan_index) : array.get(lower_cross_prices, scan_index)
scan_structure_valid = cycle_side_short ? scan_price > target_price and target_price > cost_anchor : scan_price < target_price and target_price < cost_anchor
if scan_structure_valid
fallback_cycle_start := scan_price
scan_index := scan_index - 1
cycle_start_price = window_structure_valid ? window_cycle_start : not na(fallback_cycle_start) ? fallback_cycle_start : window_cycle_start
cycle_start_source = window_structure_valid ? (cycle_side_short ? "adaptive-cost-window-high-extreme" : "adaptive-cost-window-low-extreme") : not na(fallback_cycle_start) ? (cycle_side_short ? "recent-dynamic-upper-crossing" : "recent-dynamic-lower-crossing") : (cycle_side_short ? "adaptive-cost-window-high-extreme" : "adaptive-cost-window-low-extreme")
cycle_direction = cycle_side_short ? -1.0 : 1.0
anchor_gap = (cost_anchor - cycle_start_price) * cycle_direction
target_gap = (target_price - cycle_start_price) * cycle_direction
recovery_fraction = not na(cycle_start_price) and anchor_gap != 0 ? target_gap / anchor_gap : na
recovery_valid = anchor_gap > 0 and target_gap > 0 and not na(recovery_fraction) and recovery_fraction > 0 and recovery_fraction < 1
formula_horizon_raw_sessions = rho_valid and recovery_valid ? half_life_sessions * math.log(1.0 / (1.0 - recovery_fraction)) / math.log(2.0) : na
formula_horizon_sessions = not na(formula_horizon_raw_sessions) and formula_horizon_raw_sessions > 0 ? int(math.ceil(formula_horizon_raw_sessions)) : na
dynamic_horizon_valid = not na(formula_horizon_sessions) and formula_horizon_sessions > 0
// ============================================================
// GetDelta band(P=当时成本锚,T=动态恢复周期,d=deltaSlope)
// JS: timeScale = sqrt(T/(N·2π)); wave = s·timeScale; r_T = ((1+wave)/(1-wave))²
// longCost = P·(d·r_T - d + 1)²/r_T;high = longCost·r_T;low = longCost/r_T
// ============================================================
effective_iv = annual_vol
wave = dynamic_horizon_valid and annual_vol_valid ? effective_iv * math.sqrt(formula_horizon_sessions / (trading_sessions_per_year * 2.0 * math.pi)) : na
delta_ok = show_lab and dynamic_horizon_valid and annual_vol_valid and close > 0 and wave > 0 and wave < 1
// 网站 formulaPath.js: entryPrice = costPath[index].anchor,不是 close
// 这意味着 GetDelta 上下沿是围绕成本锚展开的价格带,不是围绕现价
entry_price = cost_anchor
raw_ratio = delta_ok ? math.pow((1 + wave) / (1 - wave), 2) : na
long_ratio = raw_ratio
long_cost = delta_ok ? entry_price * math.pow(delta_slope * long_ratio - delta_slope + 1, 2) / long_ratio : na
long_high = delta_ok ? long_cost * long_ratio : na
long_low = delta_ok ? long_cost / long_ratio : na
short_ratio = delta_ok ? 1 / long_ratio : na
short_cost = delta_ok ? entry_price * math.pow(delta_slope * short_ratio - delta_slope + 1, 2) / short_ratio : na
short_high = delta_ok ? short_cost / short_ratio : na
// ============================================================
// Profile(数值同步 JS strategyProfile.js)
// ============================================================
// auto_profile 是 pine 私有:高波动期偏保守,低波动期偏激进
annual_vol_mean = ta.cum(annual_vol) / prefix_n
annual_vol_ratio = annual_vol_mean > 0 ? annual_vol / annual_vol_mean : 1.0
auto_profile = annual_vol_ratio > 1.25 ? "Conservative" : annual_vol_ratio < 0.80 ? "Aggressive" : "Balanced"
active_profile = auto_adapt ? auto_profile : profile
// JS 数值:Conservative(1.15/0.5/0.75) Balanced(1.0/0.25/0.6) Aggressive(0.75/0/0.45)
edge_sigma_base = active_profile == "Conservative" ? 1.15 : active_profile == "Balanced" ? 1.00 : 0.75
momentum_sigma_base = active_profile == "Conservative" ? 0.50 : active_profile == "Balanced" ? 0.25 : 0.00
cost_slope_sigma_base = active_profile == "Conservative" ? 0.75 : active_profile == "Balanced" ? 0.60 : 0.45
// Relax Mode 下统一放宽门槛(pine 私有;默认 false 保持 JS 口径)
edge_sigma = relax_mode ? edge_sigma_base * 0.65 : edge_sigma_base
momentum_sigma = relax_mode ? momentum_sigma_base - 0.30 : momentum_sigma_base
cost_slope_sigma = relax_mode ? cost_slope_sigma_base * 0.75 : cost_slope_sigma_base
session_vol = annual_vol / math.sqrt(trading_sessions_per_year)
vol_ratio = session_vol / 0.02
// JS scaleProfileToMarket:minEdge = max(edgeSigma * atr * 0.3, 0.005)
// buildEntryTiming: minEdge_used = max(atr * edgeAtr, profile.minEdge)
js_min_edge = math.max(edge_sigma * atr_pct * 0.3, 0.005)
min_edge = math.max(atr_pct * edge_sigma, js_min_edge)
trim_edge = min_edge
momentum_min = momentum_sigma * session_vol
// JS: costStillFalling = costSlopeRecent < -max(atr * costSlopeAtr, costSlopeMin)
// costSlopeAtr = costSlopeSigma * volRatio
// costSlopeMin = max(costSlopeSigma * dailyVol * 0.3, 0.003)
cost_slope_threshold = math.max(atr_pct * cost_slope_sigma * vol_ratio, math.max(cost_slope_sigma * session_vol * 0.3, 0.003))
buy_edge = cost_anchor > close ? (cost_anchor - close) / close : 0.0
sell_edge = close > cost_anchor ? (close - cost_anchor) / close : 0.0
// ============================================================
// Signals(按 JS buildEntryTiming 的 5 个核心分支)
// ============================================================
formula_ready = delta_ok
below_cost = show_lab and formula_ready and close < cost_low
above_cost = show_lab and formula_ready and close > cost_high
inside_long_band = formula_ready and close >= long_low
inside_short_band = formula_ready and close <= short_high
cost_still_falling = cost_slope_recent < -cost_slope_threshold
momentum_rising = momentum_fast > momentum_min
// 1) Deep Discount: 低于成本下沿 且 低于 GetDelta 长仓下沿(超出默认入场带)
lab_deep_discount = below_cost and not inside_long_band
// 2) Wait Stop: 低于成本下沿 但止跌条件未同时满足
lab_wait_stop = below_cost and inside_long_band and (cost_still_falling or not momentum_rising)
// 3) Low Buy: 低于成本下沿 且条件全部满足
lab_buy = below_cost and inside_long_band and not cost_still_falling and momentum_rising and buy_edge >= min_edge
// 4) No Chase: 高于成本上沿 且 高于 GetDelta 空仓上沿
lab_overheat = above_cost and not inside_short_band
// 5) Trim: 高于成本上沿 且溢价幅度达到阈值
lab_sell = above_cost and inside_short_band and sell_edge >= trim_edge
// 状态切换(首根触发)
lab_buy_sig = lab_buy and not lab_buy[1]
lab_sell_sig = lab_sell and not lab_sell[1]
lab_wait_sig = lab_wait_stop and not lab_wait_stop[1]
lab_deep_sig = lab_deep_discount and not lab_deep_discount[1]
lab_overheat_sig = lab_overheat and not lab_overheat[1]
// ============================================================
// z-score(只在公式周期有效时输出)
// ============================================================
period_vol = formula_ready ? annual_vol * math.sqrt(formula_horizon_sessions / trading_sessions_per_year) : na
z_score = formula_ready and period_vol > 0 ? cost_distance / period_vol : na
z_abs = math.abs(z_score)
z_strength = not formula_ready ? "不可用" : z_abs < 0.5 ? "弱" : z_abs < 1.5 ? "中" : "强"
norm_cdf_abs(x) =>
a1 = 0.254829592
a2 = -0.284496736
a3 = 1.421413741
a4 = -1.453152027
a5 = 1.061405429
p = 0.3275911
sign_x = x >= 0 ? 1.0 : -1.0
abs_x = math.abs(x)
t = 1.0 / (1.0 + p * abs_x)
y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * math.exp(-abs_x * abs_x)
0.5 * (1.0 + sign_x * y)
phi_z = norm_cdf_abs(z_abs / math.sqrt(2.0))
match_pct = formula_ready ? (z_abs >= 8.0 ? 1.0 : math.max(0.0, math.min(1.0, 2.0 * phi_z - 1.0))) : na
// 状态文字
lab_state = not formula_ready ? "Cycle unavailable" : lab_buy ? "Low Buy" : lab_sell ? "Trim" : lab_deep_discount ? "Deep Discount" : lab_overheat ? "No Chase" : lab_wait_stop ? "Wait Stop" : z_abs < 0.5 ? "Neutral" : "Wait"
lab_reason = not rho_valid ? "rho must be in (0,1)" : not recovery_valid ? "q must be in (0,1)" : not annual_vol_valid ? "need >=5 causal returns" : lab_buy ? "Discount + 止跌 + 折扣边际达标" : lab_sell ? "Premium + 溢价边际达标" : lab_deep_discount ? "Below GetDelta lower band" : lab_overheat ? "Above GetDelta upper band" : lab_wait_stop ? "Discount but 成本仍跌或动量未起" : z_abs < 0.5 ? "偏离 < 0.5σ,等待" : "未达到信号条件"
// ============================================================
// Plots(极简单色:黑/灰/蓝/橙)
// ============================================================
// MA / BBI 主线:保留辨识度高的暖色调
plot(ma21, color=color.new(#f47608, 0), title="200", linewidth=2)
plot(ma55, color=color.new(#e49b13, 0), title="55", linewidth=2)
plot(BBI, color=color.new(#000000, 50), linewidth=2, title="BBI")
plotshape(buy_cond, title="MA Buy", style=shape.triangleup, location=location.belowbar, color=color.new(color.lime, 35), text="Buy", textcolor=color.new(color.lime, 35), size=size.normal)
plotshape(sell_cond, title="MA Sell", style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 35), text="Sell", textcolor=color.new(color.red, 35), size=size.normal)
// Cost band:紫罗兰主锚 + 红/绿上下沿(白底优化,下冷上暖)
cost_low_plot = plot(show_lab and show_cost_band ? cost_low : na, title="ML Cost Low", color=color.new(#059669, 15), linewidth=2)
cost_high_plot = plot(show_lab and show_cost_band ? cost_high : na, title="ML Cost High", color=color.new(#dc2626, 15), linewidth=2)
plot(show_lab and show_cost_band ? cost_anchor : na, title="ML Cost", color=color.new(#7c3aed, 0), linewidth=3)
// 不填充 cost zone(极简风格)
fill(cost_low_plot, cost_high_plot, color=na, title="ML Cost Zone")
// GetDelta band:与成本沿同色系但更淡(下青上橙,与短头红区分层级)
plot(show_lab and show_delta_band ? long_low : na, title="GetDelta Long Low", color=color.new(#0891b2, 55), linewidth=1)
plot(show_lab and show_delta_band ? long_high : na, title="GetDelta Long High", color=color.new(#f97316, 55), linewidth=1)
plot(show_lab and show_delta_band ? short_high : na, title="GetDelta Short High", color=color.new(#dc2626, 50), linewidth=1)
plot(show_lab and show_lp_band ? lp_lower : na, title="LP Range Low", color=color.new(#a855f7, 40), linewidth=1, style=plot.style_circles)
plot(show_lab and show_lp_band ? lp_upper : na, title="LP Range High", color=color.new(#a855f7, 40), linewidth=1, style=plot.style_circles)
// 折扣 / 溢价区背景:极淡(绿冷红暖)
bgcolor(show_lab and show_lab_bg and below_cost ? color.new(#10b981, 95) : na, title="Discount BG")
bgcolor(show_lab and show_lab_bg and above_cost ? color.new(#dc2626, 95) : na, title="Premium BG")
// 信号 plotshape(5 类核心信号,下冷上暖)
plotshape(lab_buy_sig, title="ML Low Buy", style=shape.triangleup, location=location.belowbar, color=color.new(#10b981, 15), size=size.small)
plotshape(lab_wait_sig, title="ML Wait Stop", style=shape.circle, location=location.belowbar, color=color.new(#0891b2, 50), size=size.tiny)
plotshape(lab_deep_sig, title="ML Deep Discount", style=shape.diamond, location=location.belowbar, color=color.new(#7c3aed, 25), size=size.tiny)
plotshape(lab_sell_sig, title="ML Trim", style=shape.triangledown, location=location.abovebar, color=color.new(#f97316, 15), size=size.small)
plotshape(lab_overheat_sig, title="ML No Chase", style=shape.xcross, location=location.abovebar, color=color.new(#dc2626, 25), size=size.tiny)
// ============================================================
// Pinbar
// ============================================================
body_size = math.abs(close - open)
upper_wick = high - math.max(close, open)
lower_wick = math.min(close, open) - low
is_bull_pin = lower_wick > body_size * pin_ratio and lower_wick > upper_wick
is_bear_pin = upper_wick > body_size * pin_ratio and upper_wick > lower_wick
is_pinbar = show_pinbar and (is_bull_pin or is_bear_pin)
p_open = is_pinbar ? open : na
pin_high = is_pinbar ? high : na
p_low_candle = is_pinbar ? low : na
p_close = is_pinbar ? close : na
barcolor(is_pinbar ? color.black : na, title="Pinbar Body Color")
plotcandle(p_open, pin_high, p_low_candle, p_close, title="Pinbar Black Overlay", color=color.black, wickcolor=color.black, bordercolor=color.black)
// ============================================================
// Status Panel
// ============================================================
var table lab_table = table.new(position.top_right, 2, 10, border_width=1)
if barstate.islast
table.clear(lab_table, 0, 0, 1, 9)
if barstate.islast and show_lab and show_lab_panel
state_color = lab_buy ? color.new(#10b981, 15) : lab_sell ? color.new(#f97316, 15) : lab_deep_discount ? color.new(#7c3aed, 75) : lab_overheat ? color.new(#dc2626, 75) : lab_wait_stop ? color.new(#0891b2, 75) : color.new(color.gray, 88)
table.cell(lab_table, 0, 0, "Market Lab", text_color=color.white, bgcolor=color.black)
profile_label = active_profile + " (auto: " + (auto_adapt ? "on" : "off") + (relax_mode ? ", relax" : "") + ")"
table.cell(lab_table, 1, 0, profile_label, text_color=color.white, bgcolor=color.black)
if show_position_row
table.cell(lab_table, 0, 1, "Position", text_color=color.black, bgcolor=color.white)
table.cell(lab_table, 1, 1, position_label, text_color=color.black, bgcolor=color.white)
if show_match_row
table.cell(lab_table, 0, 2, "Match", text_color=color.black, bgcolor=color.white)
table.cell(lab_table, 1, 2, str.tostring(match_pct * 100, "#") + "%", text_color=color.black, bgcolor=color.white)
table.cell(lab_table, 0, 3, "State", text_color=color.black, bgcolor=color.white)
table.cell(lab_table, 1, 3, lab_state, text_color=color.black, bgcolor=state_color)
table.cell(lab_table, 0, 4, "Cost Dev", text_color=color.black, bgcolor=color.white)
table.cell(lab_table, 1, 4, str.tostring(cost_distance * 100, "#.##") + "%", text_color=color.black, bgcolor=color.white)
table.cell(lab_table, 0, 5, "Z (H=" + (formula_ready ? str.tostring(formula_horizon_sessions) : "—") + " sessions)", text_color=color.black, bgcolor=color.white)
table.cell(lab_table, 1, 5, str.tostring(z_score, "#.##") + "σ · " + z_strength, text_color=color.black, bgcolor=color.white)
table.cell(lab_table, 0, 6, "Ann Vol", text_color=color.black, bgcolor=color.white)
table.cell(lab_table, 1, 6, str.tostring(annual_vol * 100, "#.##") + "%", text_color=color.black, bgcolor=color.white)
table.cell(lab_table, 0, 7, "ATR%", text_color=color.black, bgcolor=color.white)
table.cell(lab_table, 1, 7, str.tostring(atr_pct * 100, "#.##") + "%", text_color=color.black, bgcolor=color.white)
table.cell(lab_table, 0, 8, "Cost", text_color=color.black, bgcolor=color.white)
table.cell(lab_table, 1, 8, str.tostring(cost_anchor, "#.##"), text_color=color.black, bgcolor=color.white)
table.cell(lab_table, 0, 9, "Reason", text_color=color.black, bgcolor=color.white)
table.cell(lab_table, 1, 9, lab_reason, text_color=color.black, bgcolor=color.white)
// ============================================================
// Legend(5 类核心信号)
// ============================================================
var table legend_table = table.new(position.bottom_right, 2, 6, border_width=1)
if barstate.islast
table.clear(legend_table, 0, 0, 1, 5)
if barstate.islast and show_lab and show_legend
table.cell(legend_table, 0, 0, "Symbol", text_color=color.white, bgcolor=color.black)
table.cell(legend_table, 1, 0, "Meaning", text_color=color.white, bgcolor=color.black)
table.cell(legend_table, 0, 1, "▲", text_color=#10b981, bgcolor=color.white)
table.cell(legend_table, 1, 1, "Low Buy", text_color=color.black, bgcolor=color.white)
table.cell(legend_table, 0, 2, "●", text_color=#0891b2, bgcolor=color.white)
table.cell(legend_table, 1, 2, "Wait Stop", text_color=color.black, bgcolor=color.white)
table.cell(legend_table, 0, 3, "◆", text_color=#7c3aed, bgcolor=color.white)
table.cell(legend_table, 1, 3, "Deep Discount", text_color=color.black, bgcolor=color.white)
table.cell(legend_table, 0, 4, "▼", text_color=#f97316, bgcolor=color.white)
table.cell(legend_table, 1, 4, "Trim", text_color=color.black, bgcolor=color.white)
table.cell(legend_table, 0, 5, "✕", text_color=#dc2626, bgcolor=color.white)
table.cell(legend_table, 1, 5, "No Chase", text_color=color.black, bgcolor=color.white)
// ============================================================
// Alerts
// ============================================================
alertcondition(buy_cond, title="MA Buy Condition", message="MA Buy Condition Alert")
alertcondition(sell_cond, title="MA Sell Condition", message="MA Sell Condition Alert")
alertcondition(lab_buy_sig, title="ML Low Buy", message="Market Lab Low Buy")
alertcondition(lab_sell_sig, title="ML Trim", message="Market Lab Premium Trim")
alertcondition(lab_wait_sig, title="ML Wait Stop", message="Market Lab Discount But Wait")
alertcondition(lab_deep_sig, title="ML Deep Discount", message="Market Lab Below GetDelta Lower Band")
alertcondition(lab_overheat_sig, title="ML No Chase", message="Market Lab Above GetDelta Upper Band")
Show all 399 lines