Monte Carlo Simulation Engine [tradewsamet]

tradewsamet · study · 773 行 · 点赞 97 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
indicator("Monte Carlo Simulation Engine [tradewsamet]", shorttitle="Monte Carlo Simulation Engine [tradewsamet]", overlay=true, max_polylines_count=100, max_lines_count=500, max_labels_count=500, max_boxes_count=500, max_bars_back=3500)
 
// ════════════════════════════════════════════════════════════════════════════
//  MONTE CARLO SIMULATION ENGINE [tradewsamet]
// ────────────────────────────────────────────────────────────────────────────
//  Purpose
//    Turns the instrument's own historical behaviour into a readable
//    probability map of the next N bars: a graded probability fan, a clear
//    direction arrow, a median projection, the terminal distribution, level
//    touch / race / time-to-touch frequencies, path excursions, risk
//    statistics — and a self-calibration test that shows how well the model's
//    bands contained real price in the past.
//
//  Overview
//    01. Return model      — log returns of the last N confirmed bars,
//                             standardized; jumps (> 3σ) separated for the
//                             jump engine.
//    02. Volatility        — Regime-Adjusted (EWMA vs lookback, constant per
//                             path), GARCH Path (volatility evolves step by
//                             step and mean-reverts) or Raw Historical.
//    03. Engines           — Bootstrap, Block Bootstrap, Geometric Brownian
//                             Motion, Student-t (fat tails) and Jump Diffusion,
//                             all with antithetic sampling.
//    04. Aggregation       — P5…P95 at checkpoints, finish-above share,
//                             terminal distribution, level touch / race /
//                             median bars-to-touch, max run-up and drawdown,
//                             VaR / Expected Shortfall, skew.
//    05. Calibration       — re-runs the model at past anchors using only the
//                             data available then and measures how often the
//                             realized price landed inside P5–P95 and P25–P75.
//    06. Visual layer      — probability fan, direction arrow, glowing median,
//                             outcome-graded paths, terminal distribution,
//                             levels, calibration marks, statistics panel.
//
//  Notes
//    • Calculated only on CONFIRMED bars (bar close). The random generator is
//      deterministic (seeded by the anchor bar), so the projection does not
//      change while a bar is forming and is reproducible on reload.
//    • "Zero Drift" means zero expected log return for every engine, so the
//      direction arrow reflects the shape of the return distribution, not a
//      built-in trend.
//    • All probabilities are frequencies inside the simulation. They describe a
//      model built from past returns — they are not forecasts.
//    • Educational tool. Not financial advice.
// ════════════════════════════════════════════════════════════════════════════
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 00. INPUTS
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 
string groupEngine = "🎲 01 — Simulation Engine"
string groupLevels = "🎯 02 — Probability Levels"
string groupCalib  = "🧪 03 — Model Calibration"
string groupVisual = "🎨 04 — Visual Layer"
string groupPanel  = "📊 05 — Statistics Panel"
string groupAlerts = "🔔 06 — Alerts"
 
string engineMode = input.string("Block Bootstrap", "🎲 Simulation Method", options=["Bootstrap", "Block Bootstrap", "Geometric Brownian Motion", "Student-t (Fat Tails)", "Jump Diffusion"], group=groupEngine, display=display.none,
     tooltip="How each future step is generated.\n• Bootstrap — random historical returns from the lookback window.\n• Block Bootstrap — consecutive blocks of historical returns, so calm and volatile stretches stay together (default).\n• Geometric Brownian Motion — normally distributed log returns.\n• Student-t (Fat Tails) — like GBM but with heavier tails, so large moves happen more often (see Degrees of Freedom).\n• Jump Diffusion — normal moves plus occasional jumps; jump frequency and size are measured from the lookback (moves beyond 3σ).")
int simulations = input.int(600, "🔁 Simulation Count", minval=100, maxval=1500, step=50, group=groupEngine, display=display.none,
     tooltip="Number of simulated paths (always an even number: every path has an antithetic mirror). More paths = smoother percentiles but longer calculation. Simulation Count × Horizon is capped internally to stay inside TradingView's limits.")
int horizon = input.int(40, "⏩ Forecast Horizon (bars)", minval=5, maxval=100, group=groupEngine, display=display.none,
     tooltip="How many bars into the future each path is simulated. Longer horizons widen the fan because uncertainty grows with time.")
int lookback = input.int(300, "📚 Historical Lookback (bars)", minval=50, maxval=1000, group=groupEngine, display=display.none,
     tooltip="How many confirmed bars of history feed the return model. Short lookbacks react to the latest regime; long lookbacks are more stable.")
int blockLen = input.int(6, "🧱 Block Length", minval=2, maxval=30, group=groupEngine, display=display.none,
     tooltip="Block Bootstrap only. Consecutive historical returns copied per draw. Larger blocks keep more of the original momentum and volatility structure.")
int tDof = input.int(4, "🦴 Student-t Degrees of Freedom", minval=3, maxval=30, group=groupEngine, display=display.none,
     tooltip="Student-t engine only. Lower values = fatter tails (more extreme moves); 30 is close to a normal distribution. The distribution is always scaled to the same volatility, only its shape changes.")
string driftMode = input.string("Zero Drift", "🧭 Drift Model", options=["Zero Drift", "Historical Drift"], group=groupEngine, display=display.none,
     tooltip="• Zero Drift — zero expected log return for every engine, so the fan and the direction arrow measure the shape of the distribution only (recommended).\n• Historical Drift — the lookback average log return is kept, so a strong past trend tilts the fan.")
string volMode = input.string("Regime-Adjusted", "🌡️ Volatility Model", options=["Regime-Adjusted", "GARCH Path", "Raw Historical"], group=groupEngine, display=display.none,
     tooltip="• Regime-Adjusted — volatility is rescaled by current EWMA volatility ÷ lookback volatility (clamped 0.5×–2×) and stays constant along the path.\n• GARCH Path — volatility starts at the current regime and evolves step by step: large simulated moves raise it, calm stretches let it decay back toward the long-run level.\n• Raw Historical — lookback volatility as it is.")
int seedInput = input.int(7, "🌱 Random Seed", minval=1, maxval=999999, group=groupEngine, display=display.none,
     tooltip="Base seed of the deterministic random generator. Same seed + same bar = same projection.")
bool lockSeed = input.bool(false, "🔒 Lock Seed Across Bars", group=groupEngine, display=display.none,
     tooltip="Off: the seed is combined with the anchor bar, so each new closed bar gets a fresh but reproducible sample.\nOn: the same random sequence is reused on every bar, isolating the effect of new price data.")
 
string levelMode = input.string("Percent", "🎯 Level Mode", options=["Percent", "ATR Multiple"], group=groupLevels, display=display.none,
     tooltip="How the probability levels are placed around the anchor: distance in percent of price, or in multiples of ATR (adapts to the instrument's typical range).")
float level1 = input.float(1.0, "🎯 Level 1 Distance", minval=0.05, step=0.05, group=groupLevels, display=display.none,
     tooltip="Inner level distance (percent or ATR multiple). Touch, race and time-to-touch are measured for this level above and below the anchor.")
float level2 = input.float(2.0, "🎯 Level 2 Distance", minval=0.05, step=0.05, group=groupLevels, display=display.none,
     tooltip="Outer level distance (percent or ATR multiple). Usually wider than Level 1.")
int atrLen = input.int(14, "📏 ATR Length", minval=2, maxval=200, group=groupLevels, display=display.none,
     tooltip="ATR length used when Level Mode is ATR Multiple.")
bool showLevels = input.bool(true, "🎯 Show Probability Levels", group=groupLevels, display=display.none,
     tooltip="Draws the four levels across the forecast window with touch frequency and the median number of bars it took the touching paths to get there.")
 
bool calibOn = input.bool(true, "🧪 Run Model Calibration", group=groupCalib, display=display.none,
     tooltip="Re-runs the model at past anchors (every Horizon bars back) using only the data available at that time, then checks where price actually was Horizon bars later. A well-calibrated model contains ~90% of outcomes in P5–P95 and ~50% in P25–P75.")
int calibSamples = input.int(12, "🧪 Calibration Anchors", minval=4, maxval=20, group=groupCalib, display=display.none,
     tooltip="How many past, non-overlapping anchors are tested. Long horizons automatically use fewer anchors to stay inside TradingView's calculation limits.")
bool showCalibMarks = input.bool(true, "🧪 Show Calibration Marks", group=groupCalib, display=display.none,
     tooltip="At every tested outcome bar: a whisker for that anchor's P5–P95 (thin) and P25–P75 (thick) range and a dot for the realized close — green when inside P5–P95, red when outside.")
 
string visualTheme = input.string("Obsidian Pro", "🎨 Visual Theme", options=["Obsidian Pro", "Midnight Blue", "Emerald Matrix", "Crimson Edge"], group=groupVisual, display=display.none,
     tooltip="Color package for the fan, paths, distribution and panel.")
string fanMode = input.string("5 Bands", "🌫️ Probability Fan", options=["5 Bands", "3 Bands", "Outer Only", "Off"], group=groupVisual, display=display.none,
     tooltip="Graded probability fan. 5 Bands: P5–95, P10–90, P20–80, P30–70, P40–60 — the darker the band, the more simulated paths pass through it.")
bool showDirection = input.bool(true, "🧭 Show Direction Arrow", group=groupVisual, display=display.none,
     tooltip="Large ▲ above the fan when most simulated paths finish above the anchor, ▼ below it when most finish below. The arrow shows the share of paths and a strength tag (STRONG / MODERATE / WEAK); weak readings are drawn smaller and fainter.")
bool showMedian = input.bool(true, "〰️ Show Median Projection", group=groupVisual, display=display.none,
     tooltip="50th percentile of simulated prices at each checkpoint, with a soft glow and an arrow head colored by direction.")
bool showPaths = input.bool(true, "🧵 Show Sample Paths", group=groupVisual, display=display.none,
     tooltip="Individual simulated paths, colored by their final outcome from deep bearish to deep bullish.")
int pathCount = input.int(24, "🧵 Sample Path Count", minval=2, maxval=50, group=groupVisual, display=display.none,
     tooltip="How many individual paths are drawn. All paths are still used for the statistics.")
bool showDist = input.bool(true, "📶 Show Terminal Distribution", group=groupVisual, display=display.none,
     tooltip="Histogram of simulated prices at the end of the horizon, drawn to the right of the fan.")
bool showAnchor = input.bool(true, "◆ Show Anchor Marker", group=groupVisual, display=display.none,
     tooltip="Marks the confirmed bar the projection starts from.")
 
bool showTable = input.bool(true, "📊 Show Statistics Panel", group=groupPanel, display=display.none,
     tooltip="Summary: direction, method, volatility, percentile range, touch / race / time-to-touch, run-up and drawdown, VaR, Expected Shortfall, skew and calibration.")
string tablePos = input.string("Top Right", "📍 Panel Position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left", "Middle Right"], group=groupPanel, display=display.none,
     tooltip="Where the statistics panel is placed.")
string tableSize = input.string("Small", "🔠 Panel Text Size", options=["Tiny", "Small", "Normal"], group=groupPanel, display=display.none,
     tooltip="Text size of the statistics panel.")
 
float biasThreshold = input.float(60.0, "🔔 Skew Threshold (%)", minval=51.0, maxval=95.0, step=1.0, group=groupAlerts, display=display.none,
     tooltip="Finish-above share that counts as a STRONG bullish skew (100 minus this = strong bearish). Alerts fire on bar close when the skew state changes.")
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 01. INTERNAL CONSTANTS
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 
int   MAX_WORK     = 80000    // main simulations × horizon cap
int   CALIB_PATHS  = 120      // paths per calibration anchor
int   CALIB_WORK   = 60000    // calibration steps cap (anchors × paths × horizon)
int   MAX_CHECK    = 25       // percentile checkpoints along the horizon
float EWMA_LAMBDA  = 0.94     // RiskMetrics decay
float VOL_LO       = 0.5
float VOL_HI       = 2.0
float GARCH_A      = 0.08     // shock weight
float GARCH_B      = 0.90     // persistence (α + β < 1 → mean reversion)
float JUMP_SIGMAS  = 3.0      // a return beyond this many σ counts as a jump
float LAM_LO       = 0.002    // jump frequency bounds per bar
float LAM_HI       = 0.05
int   DIST_BINS    = 18
int   DIST_WIDTH   = 14
int   DIST_GAP     = 3
float PM_A         = 48271.0  // Park–Miller generator
float PM_M         = 2147483647.0
 
string TXT_MEDIAN  = "𝙈𝙀𝘿𝙄𝘼𝙉"
string TXT_P95     = "𝙋95"
string TXT_P5      = "𝙋5"
string TXT_ANCHOR  = "◆ 𝙎𝙄𝙈 𝘼𝙉𝘾𝙃𝙊𝙍"
string TXT_DIST    = "𝙏𝙀𝙍𝙈𝙄𝙉𝘼𝙇 𝘿𝙄𝙎𝙏𝙍𝙄𝘽𝙐𝙏𝙄𝙊𝙉"
string TXT_SIMNOTE = "SIMULATED · NOT A FORECAST"
 
bool  isBootLike = engineMode == "Bootstrap" or engineMode == "Block Bootstrap"
bool  isJump     = engineMode == "Jump Diffusion"
bool  isStudent  = engineMode == "Student-t (Fat Tails)"
bool  garchOn    = volMode == "GARCH Path"
int   blkSpanG   = math.max(1, lookback - blockLen)
float tScale     = math.sqrt(float(tDof) / (float(tDof) - 2.0))
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 02. THEME
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 
color cBull = visualTheme == "Obsidian Pro" ? color.rgb(34, 197, 94) : visualTheme == "Midnight Blue" ? color.rgb(56, 189, 248) : visualTheme == "Emerald Matrix" ? color.rgb(16, 185, 129) : color.rgb(250, 204, 21)
color cBear = visualTheme == "Obsidian Pro" ? color.rgb(239, 68, 68) : visualTheme == "Midnight Blue" ? color.rgb(244, 114, 182) : visualTheme == "Emerald Matrix" ? color.rgb(248, 113, 113) : color.rgb(220, 38, 38)
color cCone = visualTheme == "Obsidian Pro" ? color.rgb(88, 166, 255) : visualTheme == "Midnight Blue" ? color.rgb(99, 102, 241) : visualTheme == "Emerald Matrix" ? color.rgb(52, 211, 153) : color.rgb(251, 146, 60)
color cMid  = visualTheme == "Obsidian Pro" ? color.rgb(250, 250, 250) : visualTheme == "Midnight Blue" ? color.rgb(224, 231, 255) : visualTheme == "Emerald Matrix" ? color.rgb(209, 250, 229) : color.rgb(255, 237, 213)
color cBg   = visualTheme == "Obsidian Pro" ? color.rgb(13, 17, 23) : visualTheme == "Midnight Blue" ? color.rgb(15, 23, 42) : visualTheme == "Emerald Matrix" ? color.rgb(6, 20, 16) : color.rgb(24, 12, 12)
color cHead = visualTheme == "Obsidian Pro" ? color.rgb(22, 27, 34) : visualTheme == "Midnight Blue" ? color.rgb(30, 41, 59) : visualTheme == "Emerald Matrix" ? color.rgb(10, 36, 28) : color.rgb(48, 18, 18)
color cText = color.rgb(230, 237, 243)
color cMute = color.rgb(139, 148, 158)
color cWarn = color.rgb(255, 167, 38)
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 03. HELPERS
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 
// Park–Miller minimal standard generator (state in a 1-element array; exact in float). Returns (0, 1).
f_next(array<float> st) =>
    float s = (array.get(st, 0) * PM_A) % PM_M
    array.set(st, 0, s)
    s / PM_M
 
// Standard normal via Box–Muller.
f_normal(array<float> st) =>
    float u1 = math.max(f_next(st), 1e-12)
    float u2 = f_next(st)
    math.sqrt(-2.0 * math.log(u1)) * math.cos(2.0 * math.pi * u2)
 
// Student-t via Bailey's polar method, scaled to unit variance.
f_student(array<float> st) =>
    float u = 0.0
    float w = 2.0
    int guard = 0
    while (w >= 1.0 or w <= 0.0) and guard < 60
        u := 2.0 * f_next(st) - 1.0
        float v = 2.0 * f_next(st) - 1.0
        w := u * u + v * v
        guard += 1
    float wc = math.min(math.max(w, 1e-12), 0.999999)
    float t = u * math.sqrt(math.max(0.0, float(tDof) * (math.pow(wc, -2.0 / float(tDof)) - 1.0) / wc))
    t / tScale
 
// Random draws for one step: a = primary (uniform for bootstrap engines, symmetric otherwise),
// b = jump occurrence (uniform), c = jump size (normal).
f_draw3(array<float> st) =>
    float a = 0.0
    float b = 0.0
    float c = 0.0
    if isBootLike
        a := f_next(st)
    else if isStudent
        a := f_student(st)
    else
        a := f_normal(st)
        if isJump
            b := f_next(st)
            c := f_normal(st)
    [a, b, c]
 
// Return model ending `off` bars ago:
// [standardized pool, drift used, raw regime scale, base σ, jump frequency, jump σ]
f_pool(int off) =>
    array<float> rets = array.new<float>(lookback, 0.0)
    for i = 0 to lookback - 1
        array.set(rets, i, math.log(close[off + i] / close[off + i + 1]))
    float muH  = array.avg(rets)
    float sigH = math.max(array.stdev(rets), 1e-10)
    float ewVar = sigH * sigH
    for i = lookback - 1 to 0
        float r = array.get(rets, i)
        ewVar := EWMA_LAMBDA * ewVar + (1.0 - EWMA_LAMBDA) * r * r
    float rawScale = math.sqrt(ewVar) / sigH
    array<float> stdPool = array.new<float>(lookback, 0.0)
    array<float> jumps   = array.new<float>()
    array<float> calm    = array.new<float>()
    for i = 0 to lookback - 1
        float dv = array.get(rets, i) - muH
        array.set(stdPool, i, dv / sigH)
        if math.abs(dv) > JUMP_SIGMAS * sigH
            array.push(jumps, dv)
        else
            array.push(calm, dv)
    float sigD = array.size(calm) > 2 ? math.max(array.stdev(calm), 1e-10) : sigH
    float lamJ = math.max(LAM_LO, math.min(LAM_HI, float(array.size(jumps)) / float(lookback)))
    float sigJ = array.size(jumps) > 1 ? math.max(array.stdev(jumps), sigH) : JUMP_SIGMAS * sigH
    float muUse = driftMode == "Historical Drift" ? muH : 0.0
    [stdPool, muUse, rawScale, isJump ? sigD : sigH, lamJ, sigJ]
 
// One simulated log-return step. eps = diffusion shock (feeds GARCH); jumps are added on top.
f_step(float a, float b, float c, array<float> stdPool, float muUse, float sdNow, float lamJ, float sigJ, int blkIdx, int blkLeft) =>
    float step = 0.0
    float eps  = 0.0
    int   bI   = blkIdx
    int   bL   = blkLeft
    if engineMode == "Bootstrap"
        eps  := array.get(stdPool, math.min(lookback - 1, int(math.floor(a * lookback)))) * sdNow
        step := muUse + eps
    else if engineMode == "Block Bootstrap"
        if bL <= 0
            bI := math.min(blkSpanG - 1, int(math.floor(a * blkSpanG)))
            bL := blockLen
        eps  := array.get(stdPool, math.min(lookback - 1, bI)) * sdNow
        step := muUse + eps
        bI += 1
        bL -= 1
    else
        eps  := a * sdNow
        step := muUse + eps
        if isJump and b < lamJ
            step += sigJ * c
    [step, eps, bI, bL]
 
f_rowBg(int row) =>
    row % 2 == 0 ? color.new(cBg, 0) : color.new(cHead, 0)
 
f_pct(float v) =>
    (v >= 0 ? "+" : "") + str.tostring(v, "#.##") + "%"
 
f_prob(float v) =>
    str.tostring(v, "#.#") + "%"
 
f_bars(float v) =>
    na(v) ? "—" : "~" + str.tostring(math.round(v)) + " bars"
 
f_tablePos() =>
    switch tablePos
        "Top Left"     => position.top_left
        "Bottom Right" => position.bottom_right
        "Bottom Left"  => position.bottom_left
        "Middle Right" => position.middle_right
        => position.top_right
 
f_textSize() =>
    switch tableSize
        "Tiny"   => size.tiny
        "Normal" => size.normal
        => size.small
 
f_cell(table t, int col, int row, string txt, color fg, color bg) =>
    table.cell(t, col, row, txt, text_color=fg, bgcolor=bg, text_size=f_textSize(), text_halign=col == 0 ? text.align_left : text.align_right)
 
// Filled band polygon between two percentile arrays.
f_band(array<int> ck, array<float> upper, array<float> lower, float anchor, color line_c, color fill_c) =>
    int n = array.size(ck)
    array<chart.point> pts = array.from(chart.point.from_index(bar_index, anchor))
    for c = 0 to n - 1
        array.push(pts, chart.point.from_index(bar_index + array.get(ck, c), array.get(upper, c)))
    for c = n - 1 to 0
        array.push(pts, chart.point.from_index(bar_index + array.get(ck, c), array.get(lower, c)))
    polyline.new(pts, true, true, xloc.bar_index, line_c, fill_c, line.style_solid, 1)
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 04. STATE
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 
var array<polyline> polys   = array.new<polyline>()
var array<line>     lines_  = array.new<line>()
var array<label>    labels_ = array.new<label>()
var array<box>      boxes_  = array.new<box>()
var table           stats   = table.new(f_tablePos(), 2, 26, bgcolor=cBg, frame_color=color.new(cCone, 40), frame_width=1, border_color=color.new(cMute, 85), border_width=1)
 
var int prevBias   = 0
bool    biasBullEv = false
bool    biasBearEv = false
bool    biasFlatEv = false
 
float atrNow = ta.atr(atrLen)
 
// Only on a confirmed bar: the last historical bar on load, then each realtime bar at its close.
bool computeNow = barstate.isconfirmed and (barstate.islastconfirmedhistory or barstate.islast)
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 05. SIMULATION
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 
if computeNow and bar_index > lookback + 2
 
    // ── clear previous drawings ─────────────────────────────────────────────
    for p in polys
        polyline.delete(p)
    array.clear(polys)
    for l in lines_
        line.delete(l)
    array.clear(lines_)
    for lb in labels_
        label.delete(lb)
    array.clear(labels_)
    for bx in boxes_
        box.delete(bx)
    array.clear(boxes_)
 
    float anchor = close
    int   nSim   = math.max(100, math.min(simulations, int(math.floor(float(MAX_WORK) / float(horizon)))))
    nSim := nSim % 2 == 0 ? nSim : nSim - 1
    int   nChk   = math.min(horizon, MAX_CHECK)
    float fN     = float(nSim)
 
    // ── 01–02. return model + volatility ────────────────────────────────────
    [stdPool, muUse, rawScale, sigBase, lamJ, sigJ] = f_pool(0)
    float volScale = math.max(VOL_LO, math.min(VOL_HI, rawScale))
    float sdConst  = volMode == "Raw Historical" ? sigBase : sigBase * volScale
    float hStart   = sdConst * sdConst
    float omega    = sigBase * sigBase * (1.0 - GARCH_A - GARCH_B)
 
    // ── 03. levels ───────────────────────────────────────────────────────────
    float d1  = levelMode == "Percent" ? anchor * level1 / 100.0 : atrNow * level1
    float d2  = levelMode == "Percent" ? anchor * level2 / 100.0 : atrNow * level2
    float up1 = anchor + d1
    float up2 = anchor + d2
    float dn1 = anchor - d1
    float dn2 = anchor - d2
    int hitU1 = 0
    int hitU2 = 0
    int hitD1 = 0
    int hitD2 = 0
    int raceUp1 = 0
    int raceDn1 = 0
    int raceUp2 = 0
    int raceDn2 = 0
    array<float> ttU1 = array.new<float>()
    array<float> ttU2 = array.new<float>()
    array<float> ttD1 = array.new<float>()
    array<float> ttD2 = array.new<float>()
 
    array<int> ckStep = array.new<int>(nChk, 0)
    for c = 0 to nChk - 1
        array.set(ckStep, c, int(math.round(float(c + 1) * float(horizon) / float(nChk))))
    matrix<float> grid     = matrix.new<float>(nChk, nSim, anchor)
    array<float>  terminal = array.new<float>(nSim, anchor)
    array<float>  runUp    = array.new<float>(nSim, 0.0)
    array<float>  drawDn   = array.new<float>(nSim, 0.0)
 
    int drawN = showPaths ? math.min(pathCount, nSim) : 0
    matrix<float> drawM = matrix.new<float>(math.max(1, drawN), horizon, anchor)
 
    // deterministic seed
    float seed0 = lockSeed ? float(seedInput) : float(seedInput) * 7919.0 + float(bar_index)
    array<float> st = array.from(math.max(1.0, (seed0 * 16807.0) % PM_M))
    for k = 0 to 9
        f_next(st)
 
    // draws of the current even path, reused mirrored by its antithetic twin
    array<float> dA = array.new<float>(horizon, 0.0)
    array<float> dB = array.new<float>(horizon, 0.0)
    array<float> dC = array.new<float>(horizon, 0.0)
 
    // ── 04. engine (antithetic pairs) ────────────────────────────────────────
    for s = 0 to nSim - 1
        bool twin = s % 2 == 1
        if not twin
            for t = 0 to horizon - 1
                [ga, gb, gc] = f_draw3(st)
                array.set(dA, t, ga)
                array.set(dB, t, gb)
                array.set(dC, t, gc)
 
        float logP = math.log(anchor)
        float hiP  = anchor
        float loP  = anchor
        float hVar = hStart
        int   ck   = 0
        int   blkLeft = 0
        int   blkIdx  = 0
        int   first1  = 0   // +1 = ▲L1 first, −1 = ▼L1 first
        int   first2  = 0
        int   tU1 = 0
        int   tU2 = 0
        int   tD1 = 0
        int   tD2 = 0
 
        for t = 1 to horizon
            float va = array.get(dA, t - 1)
            float vb = array.get(dB, t - 1)
            float vc = array.get(dC, t - 1)
            if twin
                va := isBootLike ? 1.0 - va : -va
                vb := 1.0 - vb
                vc := -vc
            float sdNow = garchOn ? math.sqrt(hVar) : sdConst
            [stp, eps, nbI, nbL] = f_step(va, vb, vc, stdPool, muUse, sdNow, lamJ, sigJ, blkIdx, blkLeft)
            blkIdx  := nbI
            blkLeft := nbL
            if garchOn
                hVar := math.max(1e-14, omega + GARCH_A * eps * eps + GARCH_B * hVar)
 
            logP += stp
            float p = math.exp(logP)
            hiP := math.max(hiP, p)
            loP := math.min(loP, p)
            if tU1 == 0 and p >= up1
                tU1 := t
            if tU2 == 0 and p >= up2
                tU2 := t
            if tD1 == 0 and p <= dn1
                tD1 := t
            if tD2 == 0 and p <= dn2
                tD2 := t
            if first1 == 0
                first1 := p >= up1 ? 1 : p <= dn1 ? -1 : 0
            if first2 == 0
                first2 := p >= up2 ? 1 : p <= dn2 ? -1 : 0
            if ck < nChk and t == array.get(ckStep, ck)
                matrix.set(grid, ck, s, p)
                ck += 1
            if s < drawN
                matrix.set(drawM, s, t - 1, p)
 
        array.set(terminal, s, math.exp(logP))
        array.set(runUp, s, (hiP / anchor - 1.0) * 100.0)
        array.set(drawDn, s, (loP / anchor - 1.0) * 100.0)
        hitU1 += tU1 > 0 ? 1 : 0
        hitU2 += tU2 > 0 ? 1 : 0
        hitD1 += tD1 > 0 ? 1 : 0
        hitD2 += tD2 > 0 ? 1 : 0
        if tU1 > 0
            array.push(ttU1, float(tU1))
        if tU2 > 0
            array.push(ttU2, float(tU2))
        if tD1 > 0
            array.push(ttD1, float(tD1))
        if tD2 > 0
            array.push(ttD2, float(tD2))
        raceUp1 += first1 == 1 ? 1 : 0
        raceDn1 += first1 == -1 ? 1 : 0
        raceUp2 += first2 == 1 ? 1 : 0
        raceDn2 += first2 == -1 ? 1 : 0
 
    // ── 05. aggregation ──────────────────────────────────────────────────────
    array<float> pcts = array.from(5.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 95.0)
    matrix<float> pm = matrix.new<float>(11, nChk, anchor)   // rows = percentiles, cols = checkpoints
    for c = 0 to nChk - 1
        array<float> rowC = matrix.row(grid, c)
        for q = 0 to 10
            matrix.set(pm, q, c, array.percentile_linear_interpolation(rowC, array.get(pcts, q)))
    float p95E   = matrix.get(pm, 10, nChk - 1)
    float p5E    = matrix.get(pm, 0, nChk - 1)
    float medEnd = matrix.get(pm, 5, nChk - 1)
 
    array<float> tret = array.new<float>(nSim, 0.0)
    int above = 0
    for s = 0 to nSim - 1
        float tp = array.get(terminal, s)
        array.set(tret, s, (tp / anchor - 1.0) * 100.0)
        above += tp > anchor ? 1 : 0
    float pAbove = float(above) * 100.0 / fN
    float rP5    = array.percentile_linear_interpolation(tret, 5)
    float rP50   = array.percentile_linear_interpolation(tret, 50)
    float rP95   = array.percentile_linear_interpolation(tret, 95)
    float rMean  = array.avg(tret)
    float rSd    = math.max(array.stdev(tret), 1e-10)
    float sumTail = 0.0
    int   nTail   = 0
    float m3      = 0.0
    for s = 0 to nSim - 1
        float x = array.get(tret, s)
        m3 += math.pow((x - rMean) / rSd, 3)
        if x <= rP5
            sumTail += x
            nTail   += 1
    float skew   = m3 / fN
    float var95  = math.max(0.0, -rP5)
    float cvar95 = nTail > 0 ? math.max(0.0, -(sumTail / float(nTail))) : var95
    float ruMed  = array.percentile_linear_interpolation(runUp, 50)
    float ruP95  = array.percentile_linear_interpolation(runUp, 95)
    float ddMed  = array.percentile_linear_interpolation(drawDn, 50)
    float ddP95  = array.percentile_linear_interpolation(drawDn, 5)
    float mU1 = array.size(ttU1) > 0 ? array.median(ttU1) : na
    float mU2 = array.size(ttU2) > 0 ? array.median(ttU2) : na
    float mD1 = array.size(ttD1) > 0 ? array.median(ttD1) : na
    float mD2 = array.size(ttD2) > 0 ? array.median(ttD2) : na
 
    // direction
    bool   dirUp    = pAbove >= 50.0
    float  dirP     = dirUp ? pAbove : 100.0 - pAbove
    float  edge     = dirP - 50.0
    string strength = edge >= biasThreshold - 50.0 ? "STRONG" : edge >= 4.0 ? "MODERATE" : "WEAK"
    color  dirC     = dirUp ? cBull : cBear
 
    // ── 06. probability fan ──────────────────────────────────────────────────
    if fanMode != "Off"
        // outer → inner so darker bands sit on top
        array<int> qLo = fanMode == "5 Bands" ? array.from(0, 1, 2, 3, 4) : fanMode == "3 Bands" ? array.from(0, 2, 4) : array.from(0)
        int nb = array.size(qLo)
        for b = 0 to nb - 1
            int lo = array.get(qLo, b)
            int hi = 10 - lo
            int transp = 93 - int(math.round(float(b) * (fanMode == "5 Bands" ? 4.5 : fanMode == "3 Bands" ? 8.0 : 0.0)))
            color lc = b == 0 ? color.new(cCone, 50) : color.new(cCone, 100)
            array.push(polys, f_band(ckStep, matrix.row(pm, hi), matrix.row(pm, lo), anchor, lc, color.new(cCone, transp)))
        array.push(lines_, line.new(bar_index + horizon, p5E, bar_index + horizon, p95E, xloc=xloc.bar_index, color=color.new(cCone, 40), style=line.style_dotted, width=1))
        array.push(labels_, label.new(bar_index + horizon, p95E, TXT_P95 + "  " + str.tostring(p95E, format.mintick), style=label.style_label_left, color=color.new(cCone, 35), textcolor=cText, size=size.tiny, tooltip="95th percentile of simulated prices at the end of the horizon (" + f_pct(rP95) + ")."))
        array.push(labels_, label.new(bar_index + horizon, p5E, TXT_P5 + "  " + str.tostring(p5E, format.mintick), style=label.style_label_left, color=color.new(cCone, 35), textcolor=cText, size=size.tiny, tooltip="5th percentile of simulated prices at the end of the horizon (" + f_pct(rP5) + ")."))
 
    // ── 07. outcome-graded sample paths ──────────────────────────────────────
    if drawN > 0
        float spread = math.max(math.abs(rP5), math.abs(rP95), 1e-6)
        for s = 0 to drawN - 1
            array<chart.point> pts = array.from(chart.point.from_index(bar_index, anchor))
            for t = 0 to horizon - 1
                array.push(pts, chart.point.from_index(bar_index + t + 1, matrix.get(drawM, s, t)))
            float ret = (matrix.get(drawM, s, horizon - 1) / anchor - 1.0) * 100.0
            color gc  = color.from_gradient(ret, -spread, spread, cBear, cBull)
            array.push(polys, polyline.new(pts, false, false, xloc.bar_index, color.new(gc, 55), na, line.style_solid, 1))
 
    // ── 08. glowing median + arrow head ──────────────────────────────────────
    if showMedian
        array<chart.point> mid = array.from(chart.point.from_index(bar_index, anchor))
        for c = 0 to nChk - 1
            array.push(mid, chart.point.from_index(bar_index + array.get(ckStep, c), matrix.get(pm, 5, c)))
        array.push(polys, polyline.new(mid, true, false, xloc.bar_index, color.new(dirC, 78), na, line.style_solid, 7))
        array.push(polys, polyline.new(mid, true, false, xloc.bar_index, color.new(cMid, 0), na, line.style_solid, 2))
        if nChk >= 2
            array.push(lines_, line.new(bar_index + array.get(ckStep, nChk - 2), matrix.get(pm, 5, nChk - 2), bar_index + horizon, medEnd, xloc=xloc.bar_index, color=dirC, style=line.style_arrow_right, width=2))
        array.push(labels_, label.new(bar_index + horizon, medEnd, TXT_MEDIAN + "  " + str.tostring(medEnd, format.mintick) + "  (" + f_pct(rP50) + ")", style=label.style_label_left, color=color.new(cMid, 0), textcolor=cBg, size=size.small, tooltip="50th percentile of simulated prices at the end of the horizon.\n" + TXT_SIMNOTE))
 
    // ── 09. direction arrow ──────────────────────────────────────────────────
    if showDirection
        float pad = math.max((p95E - p5E) * 0.06, syminfo.mintick)
        int   xA  = bar_index + int(math.round(float(horizon) * 0.8))
        array.push(labels_, label.new(xA, dirUp ? p95E + pad : p5E - pad, (dirUp ? "UP " : "DOWN ") + f_prob(dirP) + "\n" + strength, style=dirUp ? label.style_arrowup : label.style_arrowdown, color=color.new(dirC, strength == "WEAK" ? 50 : 0), textcolor=dirC, size=strength == "STRONG" ? size.huge : strength == "MODERATE" ? size.large : size.normal, tooltip=f_prob(dirP) + " of " + str.tostring(nSim) + " simulated paths finished " + (dirUp ? "above" : "below") + " the anchor after " + str.tostring(horizon) + " bars.\nStrength: " + strength + " (STRONG ≥ " + str.tostring(biasThreshold, "#") + "%).\n" + TXT_SIMNOTE))
 
    // ── 10. probability levels ───────────────────────────────────────────────
    if showLevels
        array<float>  lvP = array.from(up2, up1, dn1, dn2)
        array<float>  lvQ = array.from(float(hitU2) * 100.0 / fN, float(hitU1) * 100.0 / fN, float(hitD1) * 100.0 / fN, float(hitD2) * 100.0 / fN)
        array<float>  lvT = array.from(mU2, mU1, mD1, mD2)
        array<string> lvN = array.from("▲ L2", "▲ L1", "▼ L1", "▼ L2")
        for i = 0 to 3
            float  lp   = array.get(lvP, i)
            bool   isUp = i < 2
            color  lc   = isUp ? cBull : cBear
            float  dist = i == 0 or i == 3 ? level2 : level1
            string unit = levelMode == "Percent" ? "%" : " ATR"
            float  tt   = array.get(lvT, i)
            array.push(lines_, line.new(bar_index, lp, bar_index + horizon, lp, xloc=xloc.bar_index, color=color.new(lc, 45), style=line.style_dashed, width=1))
            array.push(labels_, label.new(bar_index + int(horizon / 2), lp, array.get(lvN, i) + " " + (isUp ? "+" : "−") + str.tostring(dist, "#.##") + unit + " · touch " + f_prob(array.get(lvQ, i)) + (na(tt) ? "" : " · " + f_bars(tt)), style=isUp ? label.style_label_down : label.style_label_up, color=color.new(lc, 25), textcolor=color.white, size=size.tiny, tooltip="Share of simulated paths that touched " + str.tostring(lp, format.mintick) + " at least once within " + str.tostring(horizon) + " bars, and the median number of bars those paths needed.\n" + TXT_SIMNOTE))
 
    // ── 11. terminal distribution ────────────────────────────────────────────
    if showDist
        float lo = array.percentile_linear_interpolation(terminal, 1)
        float hi = array.percentile_linear_interpolation(terminal, 99)
        if hi > lo
            float bw = (hi - lo) / float(DIST_BINS)
            array<int> bins = array.new<int>(DIST_BINS, 0)
            for s = 0 to nSim - 1
                float v = array.get(terminal, s)
                if v >= lo and v <= hi
                    int bi = math.min(DIST_BINS - 1, int(math.floor((v - lo) / bw)))
                    array.set(bins, bi, array.get(bins, bi) + 1)
            int mx = math.max(1, array.max(bins))
            int x0 = bar_index + horizon + DIST_GAP
            for k = 0 to DIST_BINS - 1
                int cnt = array.get(bins, k)
                if cnt > 0
                    float bTop = lo + bw * float(k + 1)
                    float bBot = lo + bw * float(k)
                    int   wBars = math.max(1, int(math.round(float(cnt) / float(mx) * float(DIST_WIDTH))))
                    color bc = (bTop + bBot) / 2.0 >= anchor ? cBull : cBear
                    array.push(boxes_, box.new(x0, bTop, x0 + wBars, bBot, border_color=color.new(bc, 40), bgcolor=color.new(bc, 70), xloc=xloc.bar_index))
            array.push(labels_, label.new(x0, hi, TXT_DIST, style=label.style_label_lower_left, color=color.new(cHead, 0), textcolor=cMute, size=size.tiny, tooltip="Histogram of simulated prices at the end of the horizon (P1–P99). Wider rows = more simulated paths finished there."))
 
    // ── 12. model calibration (walk-back, no look-ahead) ─────────────────────
    int calN = 0
    int in90 = 0
    int in50 = 0
    if calibOn
        // anchors limited by history and by a fixed calculation budget (long horizons → fewer anchors)
        int maxK = math.min(calibSamples, int(math.floor(float(bar_index - lookback - 3) / float(horizon))) - 1, int(math.floor(float(CALIB_WORK) / float(CALIB_PATHS * horizon))))
        if maxK >= 1
            array<float> stC = array.from(math.max(1.0, (float(seedInput) * 48271.0 + 12345.0) % PM_M))
            for j = 1 to maxK
                int off = horizon * j                       // anchor = `off` bars ago
                [poolC, muC, rsC, sbC, lamC, sjC] = f_pool(off)
                float vsC = math.max(VOL_LO, math.min(VOL_HI, rsC))
                float sdC = volMode == "Raw Historical" ? sbC : sbC * vsC
                float omC = sbC * sbC * (1.0 - GARCH_A - GARCH_B)
                float a0  = close[off]
                array<float> termC = array.new<float>(CALIB_PATHS, a0)
                for s = 0 to CALIB_PATHS - 1
                    float lp2 = 0.0
                    float hC  = sdC * sdC
                    int   bL  = 0
                    int   bI  = 0
                    for t = 1 to horizon
                        [ca, cb, cc] = f_draw3(stC)
                        float sdN = garchOn ? math.sqrt(hC) : sdC
                        [stp, eps, nbI, nbL] = f_step(ca, cb, cc, poolC, muC, sdN, lamC, sjC, bI, bL)
                        bI := nbI
                        bL := nbL
                        if garchOn
                            hC := math.max(1e-14, omC + GARCH_A * eps * eps + GARCH_B * hC)
                        lp2 += stp
                    array.set(termC, s, a0 * math.exp(lp2))
                float q5  = array.percentile_linear_interpolation(termC, 5)
                float q25 = array.percentile_linear_interpolation(termC, 25)
                float q75 = array.percentile_linear_interpolation(termC, 75)
                float q95 = array.percentile_linear_interpolation(termC, 95)
                float realized = close[off - horizon]
                bool hit90 = realized >= q5 and realized <= q95
                bool hit50 = realized >= q25 and realized <= q75
                calN += 1
                in90 += hit90 ? 1 : 0
                in50 += hit50 ? 1 : 0
                if showCalibMarks
                    int   xb = bar_index - off + horizon
                    color hc = hit90 ? cBull : cBear
                    array.push(lines_, line.new(xb, q5, xb, q95, xloc=xloc.bar_index, color=color.new(cCone, 45), width=3))
                    array.push(lines_, line.new(xb, q25, xb, q75, xloc=xloc.bar_index, color=color.new(cCone, 15), width=5))
                    array.push(labels_, label.new(xb, realized, "●", style=label.style_label_center, color=color.new(hc, 100), textcolor=hc, size=size.small, tooltip="Calibration test · anchor " + str.tostring(off) + " bars ago\nModel P5–P95: " + str.tostring(q5, format.mintick) + " – " + str.tostring(q95, format.mintick) + "\nRealized: " + str.tostring(realized, format.mintick) + (hit90 ? "  ✓ inside" : "  ✕ outside")))
    float  cov90      = calN > 0 ? float(in90) * 100.0 / float(calN) : na
    float  cov50      = calN > 0 ? float(in50) * 100.0 / float(calN) : na
    string calVerdict = calN == 0 ? "Not enough history" : cov90 < 75.0 ? "Too narrow" : cov90 > 97.0 and cov50 > 70.0 ? "Too wide" : "Well calibrated"
    color  calColor   = calN == 0 ? cMute : calVerdict == "Well calibrated" ? cBull : cWarn
 
    // ── 13. anchor marker ────────────────────────────────────────────────────
    if showAnchor
        array.push(labels_, label.new(bar_index, anchor, TXT_ANCHOR, style=label.style_label_right, color=color.new(cCone, 20), textcolor=color.white, size=size.tiny, tooltip="Projection anchor: close of the last confirmed bar.\nMethod: " + engineMode + " · " + str.tostring(nSim) + " paths (antithetic) · " + str.tostring(horizon) + " bars.\n" + TXT_SIMNOTE))
 
    // ── 14. skew state + alerts ──────────────────────────────────────────────
    int bias = pAbove >= biasThreshold ? 1 : pAbove <= 100.0 - biasThreshold ? -1 : 0
    if barstate.islast and bias != prevBias
        biasBullEv := bias == 1
        biasBearEv := bias == -1
        biasFlatEv := bias == 0
        alert("Monte Carlo skew changed on " + syminfo.ticker + ": " + (dirUp ? "UP " : "DOWN ") + f_prob(dirP) + " (" + strength + "), P5–P95 " + f_pct(rP5) + " / " + f_pct(rP95) + ".", alert.freq_once_per_bar_close)
    prevBias := bias
 
    // ── 15. statistics panel ─────────────────────────────────────────────────
    table.clear(stats, 0, 0, 1, 25)
    if showTable
        string regime  = rawScale > 1.25 ? "Expanding" : rawScale < 0.8 ? "Contracting" : "Normal"
        color  regimeC = rawScale > 1.25 ? cWarn : rawScale < 0.8 ? cCone : cText
        float  none1   = math.max(0.0, 100.0 - float(raceUp1 + raceDn1) * 100.0 / fN)
        string method  = engineMode + (isStudent ? " · ν " + str.tostring(tDof) : isJump ? " · λ " + str.tostring(lamJ * 100.0, "#.##") + "%/bar" : "")
        string volTxt  = (garchOn ? "GARCH · " : volMode == "Raw Historical" ? "Raw · " : "Regime · ") + regime + " (" + str.tostring(rawScale, "#.##") + "×)"
        int r = 0
        f_cell(stats, 0, r, "MONTE CARLO", cText, cHead)
        f_cell(stats, 1, r, "SIMULATION ENGINE", cCone, cHead)
        r += 1
        f_cell(stats, 0, r, "Direction", cText, color.new(dirC, 75))
        f_cell(stats, 1, r, (dirUp ? "▲ UP · " : "▼ DOWN · ") + f_prob(dirP) + " · " + strength, dirC, color.new(dirC, 75))
        r += 1
        f_cell(stats, 0, r, "Method", cMute, f_rowBg(r))
        f_cell(stats, 1, r, method, cText, f_rowBg(r))
        r += 1
        f_cell(stats, 0, r, "Paths · Horizon", cMute, f_rowBg(r))
        f_cell(stats, 1, r, str.tostring(nSim) + " antithetic · " + str.tostring(horizon) + " bars", cText, f_rowBg(r))
        r += 1
        f_cell(stats, 0, r, "Volatility", cMute, f_rowBg(r))
        f_cell(stats, 1, r, volTxt, regimeC, f_rowBg(r))
        r += 1
        f_cell(stats, 0, r, "Median Outcome", cMute, f_rowBg(r))
        f_cell(stats, 1, r, f_pct(rP50), rP50 >= 0 ? cBull : cBear, f_rowBg(r))
        r += 1
        f_cell(stats, 0, r, "P5 – P95 Range", cMute, f_rowBg(r))
        f_cell(stats, 1, r, f_pct(rP5) + "  /  " + f_pct(rP95), cText, f_rowBg(r))
        r += 1
        f_cell(stats, 0, r, "Touch ▲ L1 · ▲ L2", cMute, f_rowBg(r))
        f_cell(stats, 1, r, f_prob(float(hitU1) * 100.0 / fN) + " · " + f_prob(float(hitU2) * 100.0 / fN), cBull, f_rowBg(r))
        r += 1
        f_cell(stats, 0, r, "Touch ▼ L1 · ▼ L2", cMute, f_rowBg(r))
        f_cell(stats, 1, r, f_prob(float(hitD1) * 100.0 / fN) + " · " + f_prob(float(hitD2) * 100.0 / fN), cBear, f_rowBg(r))
        r += 1
        f_cell(stats, 0, r, "Bars to Touch L1 (median)", cMute, f_rowBg(r))
        f_cell(stats, 1, r, "▲ " + f_bars(mU1) + "  ▼ " + f_bars(mD1), cText, f_rowBg(r))
        r += 1
        f_cell(stats, 0, r, "Race L1 (first touch)", cMute, f_rowBg(r))
        f_cell(stats, 1, r, "▲ " + f_prob(float(raceUp1) * 100.0 / fN) + "  ▼ " + f_prob(float(raceDn1) * 100.0 / fN) + "  · none " + f_prob(none1), raceUp1 >= raceDn1 ? cBull : cBear, f_rowBg(r))
        r += 1
        f_cell(stats, 0, r, "Race L2 (first touch)", cMute, f_rowBg(r))
        f_cell(stats, 1, r, "▲ " + f_prob(float(raceUp2) * 100.0 / fN) + "  ▼ " + f_prob(float(raceDn2) * 100.0 / fN), raceUp2 >= raceDn2 ? cBull : cBear, f_rowBg(r))
        r += 1
        f_cell(stats, 0, r, "Max Run-Up (median · P95)", cMute, f_rowBg(r))
        f_cell(stats, 1, r, f_pct(ruMed) + " · " + f_pct(ruP95), cBull, f_rowBg(r))
        r += 1
        f_cell(stats, 0, r, "Max Drawdown (median · P95)", cMute, f_rowBg(r))
        f_cell(stats, 1, r, f_pct(ddMed) + " · " + f_pct(ddP95), cBear, f_rowBg(r))
        r += 1
        f_cell(stats, 0, r, "Value at Risk (95%)", cMute, f_rowBg(r))
        f_cell(stats, 1, r, "−" + str.tostring(var95, "#.##") + "%", cBear, f_rowBg(r))
        r += 1
        f_cell(stats, 0, r, "Expected Shortfall (95%)", cMute, f_rowBg(r))
        f_cell(stats, 1, r, "−" + str.tostring(cvar95, "#.##") + "%", cBear, f_rowBg(r))
        r += 1
        f_cell(stats, 0, r, "Distribution Skew", cMute, f_rowBg(r))
        f_cell(stats, 1, r, str.tostring(skew, "#.##"), skew >= 0 ? cBull : cBear, f_rowBg(r))
        r += 1
        f_cell(stats, 0, r, "Calibration P5–P95", cMute, f_rowBg(r))
        f_cell(stats, 1, r, calN > 0 ? f_prob(cov90) + "  (target 90%)" : "—", calColor, f_rowBg(r))
        r += 1
        f_cell(stats, 0, r, "Calibration P25–P75", cMute, f_rowBg(r))
        f_cell(stats, 1, r, calN > 0 ? f_prob(cov50) + "  (target 50%)" : "—", calColor, f_rowBg(r))
        r += 1
        f_cell(stats, 0, r, "Model Verdict", cMute, f_rowBg(r))
        f_cell(stats, 1, r, calVerdict + (calN > 0 ? " · " + str.tostring(calN) + " tests" : ""), calColor, f_rowBg(r))
        r += 1
        f_cell(stats, 0, r, TXT_SIMNOTE, cMute, cHead)
        f_cell(stats, 1, r, "bar close · seed " + str.tostring(seedInput), cMute, cHead)
 
else if computeNow and showTable
    table.clear(stats, 0, 0, 1, 25)
    f_cell(stats, 0, 0, "MONTE CARLO", cText, cHead)
    f_cell(stats, 1, 0, "Waiting for history…", cWarn, cHead)
 
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// 06. ALERT CONDITIONS
//━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 
alertcondition(biasBullEv, "Monte Carlo · Bullish Skew", "Monte Carlo simulation turned to a strong bullish skew on {{ticker}} {{interval}}.")
alertcondition(biasBearEv, "Monte Carlo · Bearish Skew", "Monte Carlo simulation turned to a strong bearish skew on {{ticker}} {{interval}}.")
alertcondition(biasFlatEv, "Monte Carlo · Balanced", "Monte Carlo simulation returned to a balanced distribution on {{ticker}} {{interval}}.")

← 返回列表