Kalman-Referenced Hurst Regime + AKF Bands + FLD

garygfe1y · study · 505 行 · 点赞 7 · TradingView 原页

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

Pine Script

//@version=6
indicator('Kalman-Referenced Hurst Regime + AKF Bands + FLD ', shorttitle = 'KF-Hurst Regime',
     overlay = false, precision = 3, max_bars_back = 600)
 
// =================================================================================================
// 1. Inputs — Kalman Filter
// =================================================================================================
S = input.source(close, 'Source for filter')
 
g1 = 'Kalman Adaptation Settings'
int    adapt_len = input.int(20, 'Adaptivity Lookback Length', minval = 1, group = g1)
string vol_type  = input.string('ATR', 'Volatility Measure', options = ['ATR', 'StdDev'], group = g1)
 
float k_R = input.float(1.0, 'R Multiplier (Smoothing Sensitivity)', step = 0.1, group = g1,
     tooltip = 'Scales Measurement Noise (R). Higher → more smoothing in high vol. Applies in Custom mode only.')
float k_Q = input.float(0.1, 'Q Multiplier (Adaptation Speed)', step = 0.01, group = g1,
     tooltip = 'Scales Process Noise (Q). Higher → faster adaptation to price changes. Applies in Custom mode only.')
 
bool show_colored_trend = input.bool(true, 'Color Kalman line by trend direction', group = g1)
 
g_bands = 'Standard Deviation Bands'
bool show_bands = input.bool(true, 'Show StdDev Bands', group = g_bands)
 
float mult1 = input.float(1.0, 'Band 1 Multiplier', minval = 0.1, step = 0.1, group = g_bands, inline = 'b1')
bool  show1 = input.bool(true,  '', group = g_bands, inline = 'b1')
color col1  = input.color(color.new(color.orange, 40), 'Band 1', group = g_bands, inline = 'b1c')
string sty1 = input.string('Solid', 'Style', options = ['Solid','Dashed','Dotted'], group = g_bands, inline = 'b1s')
int   wid1  = input.int(1, '', minval = 1, maxval = 4, group = g_bands, inline = 'b1s')
 
float mult2 = input.float(2.0, 'Band 2 Multiplier', minval = 0.1, step = 0.1, group = g_bands, inline = 'b2')
bool  show2 = input.bool(true,  '', group = g_bands, inline = 'b2')
color col2  = input.color(color.new(color.purple, 50), 'Band 2', group = g_bands, inline = 'b2c')
string sty2 = input.string('Dashed', 'Style', options = ['Solid','Dashed','Dotted'], group = g_bands, inline = 'b2s')
int   wid2  = input.int(1, '', minval = 1, maxval = 4, group = g_bands, inline = 'b2s')
 
float mult3 = input.float(3.0, 'Band 3 Multiplier', minval = 0.1, step = 0.1, group = g_bands, inline = 'b3')
bool  show3 = input.bool(true,  '', group = g_bands, inline = 'b3')
color col3  = input.color(color.new(color.red, 60), 'Band 3', group = g_bands, inline = 'b3c')
string sty3 = input.string('Dotted', 'Style', options = ['Solid','Dashed','Dotted'], group = g_bands, inline = 'b3s')
int   wid3  = input.int(1, '', minval = 1, maxval = 4, group = g_bands, inline = 'b3s')
 
bool use_fixed_stdev = input.bool(false, 'Use Fixed-Length Innovation StdDev (instead of expanding)', group = g_bands)
int  stdev_len       = input.int(50, 'Fixed StdDev Lookback Length', minval = 5, group = g_bands)
 
g_session = 'Session Anchor (Globex)'
bool   anchor_globex  = input.bool(false, 'Anchor / Reset Kalman at Each New Globex Day', group = g_session)
string globex_session = input.session('1800-1700', 'Globex Session (ET: 6PM-5PM next day)', group = g_session)
 
bool in_globex      = not na(time(timeframe.period, globex_session))
bool new_globex_day = in_globex and not in_globex[1]
 
// =================================================================================================
// 1b. Setup Mode (Kalman preset)
// =================================================================================================
g_mode = 'Setup Mode'
string setup_mode = input.string('Mean Reversion', 'Kalman Preset',
     options = ['Mean Reversion', 'Trend Following', 'Custom'], group = g_mode,
     tooltip = 'Mean Reversion: faster filter (Q 0.08 / R 1.0) — estimate tracks price closely, excursions from it revert. Trend Following: slow filter (Q 0.02 / R 1.4) — estimate lags, one-sided innovations push Hurst above 0.60. Custom: use the R/Q multipliers above.')
 
float k_R_eff = setup_mode == 'Trend Following' ? 1.4  : setup_mode == 'Mean Reversion' ? 1.0  : k_R
float k_Q_eff = setup_mode == 'Trend Following' ? 0.02 : setup_mode == 'Mean Reversion' ? 0.08 : k_Q
 
// =================================================================================================
// 1c. Inputs — FLD (Future Line of Demarcation)
// =================================================================================================
g_fld = 'FLD (Future Line of Demarcation)'
bool   show_fld    = input.bool(true, 'Show FLD on price chart', group = g_fld)
string fld_src_sel = input.string('Kalman Estimate', 'FLD Source', options = ['Kalman Estimate', 'Close'], group = g_fld)
string fld_mode    = input.string('Auto (innovation cycle)', 'Cycle Detection', options = ['Auto (innovation cycle)', 'Manual'], group = g_fld)
int    fld_manual  = input.int(20, 'Manual Cycle Period (bars)', minval = 4, group = g_fld)
int    fld_win     = input.int(120, 'Cycle Detection Window', minval = 40, maxval = 400, group = g_fld)
int    fld_maxlag  = input.int(60, 'Max Cycle Period', minval = 10, maxval = 200, group = g_fld)
float  fld_minCorr = input.float(0.30, 'Min Autocorrelation to Accept Cycle', minval = 0.05, maxval = 0.9, step = 0.05, group = g_fld)
color  fld_col     = input.color(color.new(color.blue, 0), 'FLD Colour', group = g_fld)
 
// =================================================================================================
// 1d. Signal-Quality Gates
// =================================================================================================
g_gate = 'Signal-Quality Gates'
bool  gates_on       = input.bool(true, 'Enable gates (veto only — never generate signals)', group = g_gate)
int   gain_len       = input.int(50, 'Gain Median Lookback', minval = 10, maxval = 200, group = g_gate,
     tooltip = 'Setups gated unless the Kalman gain sits below its median over this window — i.e. the filter is settled and bands/innovations are trustworthy.')
float gain_mult      = input.float(1.0, 'Gain Threshold × Median', minval = 0.5, maxval = 2.0, step = 0.05, group = g_gate)
int   min_regime_age = input.int(2, 'Min Regime Age (bars)', minval = 0, maxval = 50, group = g_gate,
     tooltip = 'Bars the regime must persist before setups are permitted — filters one-bar threshold flickers.')
int   max_regime_age = input.int(30, 'Max Regime Age (bars)', minval = 5, maxval = 200, group = g_gate,
     tooltip = 'Setups vetoed beyond this age — late trend entries buy exhaustion; stale MR excursions have decayed.')
float h_tol          = input.float(0.02, 'H-Momentum Tolerance', minval = 0.0, maxval = 0.1, step = 0.01, group = g_gate,
     tooltip = 'MR mode requires H still falling (within tolerance); Trend mode requires H still rising. Measured as 5-bar change in bounded Hurst.')
 
// =================================================================================================
// 2. Inputs — Hurst (Kalman-Referenced)
// =================================================================================================
g_h = 'Hurst (Kalman-Referenced)'
bool autoMode = input.bool(true, 'Auto-optimise to timeframe + Kalman settings', group = g_h,
     tooltip = 'Lookback scales with chart timeframe, Kalman Adaptivity Lookback and effective Q. Scales derive as fractions of the effective lookback.')
 
int manualLength = input.int(128, 'Manual lookback', minval = 32, maxval = 512, group = 'Hurst Manual Settings')
int manualS1 = input.int(8,  'Scale 1', minval = 4, group = 'Hurst Manual Settings')
int manualS2 = input.int(16, 'Scale 2', minval = 4, group = 'Hurst Manual Settings')
int manualS3 = input.int(32, 'Scale 3', minval = 4, group = 'Hurst Manual Settings')
int manualS4 = input.int(64, 'Scale 4', minval = 4, group = 'Hurst Manual Settings')
 
g_d = 'Hurst Display'
float lowerLevel = input.float(0.40, 'Lower reference', minval = 0, maxval = 1, group = g_d)
float upperLevel = input.float(0.60, 'Upper reference', minval = 0, maxval = 1, group = g_d)
bool  showTable  = input.bool(true, 'Show information table', group = g_d)
bool  highlight_regime = input.bool(true, 'Tint pane background by regime state', group = g_d)
bool  alert_regime = input.bool(true, 'Alert on regime state changes', group = g_d)
 
// =================================================================================================
// 3. Auto-Optimised Hurst Settings (timeframe + Kalman coupling)
// =================================================================================================
int tfSeconds = timeframe.in_seconds()
 
int tfBase = switch tfSeconds
    60   => 256
    120  => 192
    300  => 128
    600  => 96
    1800 => 64
    => 128
 
float kalmanLookbackScale = adapt_len / 20.0
float kalmanSpeedScale    = math.pow(0.1 / math.max(k_Q_eff, 0.01), 0.25)
 
int autoLength = int(math.round(tfBase * kalmanLookbackScale * kalmanSpeedScale))
autoLength := math.max(32, math.min(512, autoLength))
 
int a1 = math.max(4,  autoLength / 16)
int a2 = math.max(8,  autoLength / 8)
int a3 = math.max(16, autoLength / 4)
int a4 = math.max(32, autoLength / 2)
 
int length = autoMode ? autoLength   : manualLength
int s1     = autoMode ? a1           : manualS1
int s2     = autoMode ? a2           : manualS2
int s3     = autoMode ? a3           : manualS3
int s4     = autoMode ? a4           : manualS4
 
if not (s1 < s2 and s2 < s3 and s3 < s4 and s4 <= length)
    runtime.error('Scales must be ascending and no larger than the lookback.')
 
// =================================================================================================
// 4. Kalman Filter Core Logic
// =================================================================================================
var float kalman_est = na
var float P          = 1.0
var float k_gain     = na
 
max_bars_back(kalman_est, 600)
max_bars_back(close, 600)
 
epsilon = syminfo.mintick * 10
 
float volatility = switch vol_type
    'ATR'    => ta.atr(adapt_len)
    'StdDev' => ta.stdev(S, adapt_len)
 
if not na(volatility)
 
    if na(kalman_est) or (anchor_globex and new_globex_day)
        kalman_est := S
        P := 1.0
 
    volatility := math.max(volatility, epsilon)
 
    R = math.pow(k_R_eff * volatility, 2)
    Q = math.pow(k_Q_eff * volatility, 2)
 
    float pred   = kalman_est
    float P_pred = P + Q
 
    float K = P_pred / (P_pred + R)
    kalman_est := pred + K * (S - pred)
    P := (1 - K) * P_pred
    k_gain := K
 
// Filter-implied drift: the dynamic mean, expressed as a log return of the state estimate.
// This replaces the static block mean in the R/S estimator below.
float kalRet = math.log(kalman_est / kalman_est[1])
 
// =================================================================================================
// 5. Standard Deviation Bands (innovation-based)
// =================================================================================================
float innovation = S - kalman_est
float fixed_stdev = ta.stdev(innovation, stdev_len)
float stdev_res = na
 
if not na(kalman_est) and not na(innovation)
    if use_fixed_stdev
        stdev_res := fixed_stdev
    else
        var float sum_sq_err = 0.0
        var int   count      = 0
        sum_sq_err += math.pow(innovation, 2)
        count      += 1
        float variance = sum_sq_err / math.max(count, 1)
        stdev_res := math.sqrt(variance)
 
stdev_res := na(stdev_res) ? volatility : stdev_res
 
// =================================================================================================
// 6. Hurst R/S Estimator — referenced to the Kalman dynamic mean
// =================================================================================================
hurstRS(int windowLength, int scale1, int scale2, int scale3, int scale4) =>
    array<int> scales = array.from(scale1, scale2, scale3, scale4)
 
    float sumX = 0.0
    float sumY = 0.0
    float sumXX = 0.0
    float sumXY = 0.0
    int validScales = 0
 
    for scaleIndex = 0 to 3
        int blockSize = array.get(scales, scaleIndex)
        int blockCount = int(math.floor(windowLength / blockSize))
 
        float totalRS = 0.0
        int validBlocks = 0
 
        for block = 0 to blockCount - 1
            int startOffset = block * blockSize
 
            // Deviations measured against the Kalman filter's state estimate
            // (time-varying prediction), NOT a static block mean.
            float cumulative = 0.0
            float maxCum = 0.0
            float minCum = 0.0
            float variance = 0.0
 
            for j = 0 to blockSize - 1
                int offset = startOffset + j
                float r  = math.log(close[offset] / close[offset + 1])
                float dm = kalRet[offset]
                dm := na(dm) ? 0.0 : dm
                float deviation = r - dm
 
                cumulative += deviation
                maxCum := math.max(maxCum, cumulative)
                minCum := math.min(minCum, cumulative)
                variance += deviation * deviation
 
            float sd = math.sqrt(variance / blockSize)
            float rangeValue = maxCum - minCum
 
            if sd > 0 and rangeValue > 0
                totalRS += rangeValue / sd
                validBlocks += 1
 
        if validBlocks > 0
            float avgRS = totalRS / validBlocks
            float x = math.log(blockSize)
            float y = math.log(avgRS)
 
            sumX += x
            sumY += y
            sumXX += x * x
            sumXY += x * y
            validScales += 1
 
    float result = na
 
    if validScales >= 3
        float denominator = validScales * sumXX - sumX * sumX
        if math.abs(denominator) > 1e-10
            result := (validScales * sumXY - sumX * sumY) / denominator
 
    result
 
// ─── Confirmed-bar calculation ──────────────────────────────────────────────────────────────────
// Called every bar for series consistency; stored only on confirmed bars.
float currentRaw = hurstRS(length, s1, s2, s3, s4)
 
var float rawHurst = na
var float boundedHurst = na
 
if barstate.isconfirmed and bar_index >= length
    rawHurst := currentRaw
    boundedHurst := na(rawHurst) ? na : math.max(0.0, math.min(1.0, rawHurst))
 
// =================================================================================================
// 6b. FLD — cycle detection from Kalman innovations + forward projection
// =================================================================================================
float fld_src = fld_src_sel == 'Kalman Estimate' ? kalman_est : close
 
var array<float> innov_hist = array.new_float()
if not na(innovation)
    array.push(innov_hist, innovation)
    if array.size(innov_hist) > fld_win
        array.shift(innov_hist)
 
// Dominant cycle = lag with the highest innovation autocorrelation above threshold.
// Period persists when no lag qualifies — avoids jumping between noise peaks.
var int cycle_period = 20
if array.size(innov_hist) >= fld_win and barstate.isconfirmed
    int n = fld_win
    int maxLag = math.min(fld_maxlag, n / 2)
    float best_corr = fld_minCorr
    for lag = 8 to maxLag
        int m = n - lag
        float mx = 0.0
        float my = 0.0
        for i = 0 to m - 1
            mx += array.get(innov_hist, i)
            my += array.get(innov_hist, i + lag)
        mx /= m
        my /= m
        float cov = 0.0
        float vx = 0.0
        float vy = 0.0
        for i = 0 to m - 1
            float dx = array.get(innov_hist, i) - mx
            float dy = array.get(innov_hist, i + lag) - my
            cov += dx * dy
            vx += dx * dx
            vy += dy * dy
        float corr = vx > 0 and vy > 0 ? cov / math.sqrt(vx * vy) : 0.0
        if corr > best_corr
            best_corr := corr
            cycle_period := lag
 
int fld_period = fld_mode == 'Manual' ? fld_manual : cycle_period
int fld_shift  = math.max(2, int(fld_period / 2))
 
// FLD value visible above the current bar (the line is plotted fld_shift bars forward).
float fld_line = fld_src[fld_shift]
 
bool fld_cross_up = ta.crossover(close, fld_line)
bool fld_cross_dn = ta.crossunder(close, fld_line)
 
// =================================================================================================
// 7. Regime State + Signal-Quality Gates (mode-aware)
// =================================================================================================
bool mr_active = not na(boundedHurst) and boundedHurst < lowerLevel
bool tf_active = not na(boundedHurst) and boundedHurst > upperLevel
 
bool mode_matched = (setup_mode == 'Mean Reversion'  and mr_active) or
     (setup_mode == 'Trend Following' and tf_active) or
     (setup_mode == 'Custom' and (mr_active or tf_active))
 
bool wrong_regime = (mr_active or tf_active) and not mode_matched and setup_mode != 'Custom'
 
// ─── Gate 1: Kalman gain confidence (applies in all modes, including Custom) ───────────────────
float k_med  = ta.median(k_gain, gain_len)
bool gain_ok = not gates_on or (not na(k_gain) and not na(k_med) and k_gain <= k_med * gain_mult)
 
// ─── Gate 2: regime age + H-momentum (not applied in Custom mode) ──────────────────────────────
int regime_now = mr_active ? 1 : tf_active ? 2 : 0
var int regime_age = 0
if barstate.isconfirmed
    if regime_now != 0 and regime_now == regime_now[1]
        regime_age += 1
    else
        regime_age := regime_now != 0 ? 1 : 0
 
float h_delta = nz(boundedHurst - boundedHurst[5])
 
bool age_ok = not gates_on or setup_mode == 'Custom' or
     (regime_age >= min_regime_age and regime_age <= max_regime_age)
bool momentum_ok = not gates_on or setup_mode == 'Custom' or
     (setup_mode == 'Mean Reversion' ? h_delta <= h_tol : h_delta >= -h_tol)
 
bool setup_ok = mode_matched and gain_ok and age_ok and momentum_ok
 
// Tint: full colour when tradeable, washed-out when gated, red when wrong mode.
color bg_col = not highlight_regime ? na :
     mode_matched and mr_active ? (setup_ok ? color.new(color.teal,   86) : color.new(color.teal,   93)) :
     mode_matched and tf_active ? (setup_ok ? color.new(color.orange, 86) : color.new(color.orange, 93)) :
     wrong_regime               ? color.new(color.red, 90) : na
 
bgcolor(bg_col)
 
// =================================================================================================
// 8. Plotting
// =================================================================================================
// ─── Price chart (forced overlay from this pane) ────────────────────────────────────────────────
color line_color = show_colored_trend ?
     (kalman_est > kalman_est[1] ? color.green : color.red) : color.blue
 
plot(kalman_est, 'Kalman Estimate', color = line_color, linewidth = 2, force_overlay = true)
 
float upper1 = kalman_est + mult1 * stdev_res
float lower1 = kalman_est - mult1 * stdev_res
float upper2 = kalman_est + mult2 * stdev_res
float lower2 = kalman_est - mult2 * stdev_res
float upper3 = kalman_est + mult3 * stdev_res
float lower3 = kalman_est - mult3 * stdev_res
 
bool plot_band1 = show_bands and show1
bool plot_band2 = show_bands and show2
bool plot_band3 = show_bands and show3
 
plot(plot_band1 ? upper1 : na, 'Upper 1', color = plot_band1 ? col1 : na, linewidth = wid1, force_overlay = true,
     linestyle = sty1 == 'Dashed' ? plot.linestyle_dashed : sty1 == 'Dotted' ? plot.linestyle_dotted : plot.linestyle_solid)
plot(plot_band1 ? lower1 : na, 'Lower 1', color = plot_band1 ? col1 : na, linewidth = wid1, force_overlay = true,
     linestyle = sty1 == 'Dashed' ? plot.linestyle_dashed : sty1 == 'Dotted' ? plot.linestyle_dotted : plot.linestyle_solid)
 
plot(plot_band2 ? upper2 : na, 'Upper 2', color = plot_band2 ? col2 : na, linewidth = wid2, force_overlay = true,
     linestyle = sty2 == 'Dashed' ? plot.linestyle_dashed : sty2 == 'Dotted' ? plot.linestyle_dotted : plot.linestyle_solid)
plot(plot_band2 ? lower2 : na, 'Lower 2', color = plot_band2 ? col2 : na, linewidth = wid2, force_overlay = true,
     linestyle = sty2 == 'Dashed' ? plot.linestyle_dashed : sty2 == 'Dotted' ? plot.linestyle_dotted : plot.linestyle_solid)
 
plot(plot_band3 ? upper3 : na, 'Upper 3', color = plot_band3 ? col3 : na, linewidth = wid3, force_overlay = true,
     linestyle = sty3 == 'Dashed' ? plot.linestyle_dashed : sty3 == 'Dotted' ? plot.linestyle_dotted : plot.linestyle_solid)
plot(plot_band3 ? lower3 : na, 'Lower 3', color = plot_band3 ? col3 : na, linewidth = wid3, force_overlay = true,
     linestyle = sty3 == 'Dashed' ? plot.linestyle_dashed : sty3 == 'Dotted' ? plot.linestyle_dotted : plot.linestyle_solid)
 
// ─── FLD: line shows the source from fld_shift bars ago (equivalent to a forward shift) ─────────
// Note: plot offset requires a compile-time constant, so the FLD is anchored to the current bar
// rather than drawn into the future. Crosses and levels are unaffected.
plot(show_fld ? fld_line : na, 'FLD', color = fld_col, linewidth = 1, force_overlay = true)
plot(fld_line, 'FLD (current-bar value)', display = display.data_window)
plot(show_fld and fld_cross_up ? low  : na, 'FLD Cross Up', color = color.new(color.teal, 0),
     style = plot.style_circles, linewidth = 2, force_overlay = true)
plot(show_fld and fld_cross_dn ? high : na, 'FLD Cross Down', color = color.new(color.red, 0),
     style = plot.style_circles, linewidth = 2, force_overlay = true)
 
// ─── Separate pane: Hurst line and reference levels ─────────────────────────────────────────────
hline(0.0, 'Zero', color = color.new(color.gray, 100))
hline(1.0, 'One', color = color.new(color.gray, 100))
hline(0.5, 'Random walk reference', color = color.gray, linestyle = hline.style_dashed)
hline(lowerLevel, 'Lower regime threshold', color = color.new(color.teal, 65))
hline(upperLevel, 'Upper regime threshold', color = color.new(color.orange, 65))
 
color hurstColour = na(boundedHurst) ? color.gray :
     boundedHurst > upperLevel ? color.orange :
     boundedHurst < lowerLevel ? color.teal :
     color.silver
 
plot(boundedHurst, title = 'Hurst (Kalman-referenced)', color = hurstColour, linewidth = 2)
plot(rawHurst, title = 'Raw Hurst (unbounded)', display = display.data_window)
 
// =================================================================================================
// 9. Information Table
// =================================================================================================
if showTable and barstate.islast
    var table t = table.new(position.top_right, 2, 10,
         bgcolor = color.new(color.black, 80), border_width = 1)
 
    string regime = na(boundedHurst) ? '—' :
         boundedHurst > upperLevel ? 'Persistent (trending)' :
         boundedHurst < lowerLevel ? 'Anti-persistent (mean-reverting)' : 'Near random walk'
 
    string status = wrong_regime ? 'OPPOSITE REGIME — DO NOT TRADE' :
         mode_matched and setup_ok ? 'REGIME ACTIVE — setups permitted' :
         mode_matched ? 'GATED — regime live, quality filter blocking' :
         'No regime — stand aside'
    color status_col = wrong_regime ? color.red :
         mode_matched and setup_ok ? color.aqua :
         mode_matched ? color.yellow : color.gray
 
    table.cell(t, 0, 0, 'Mode',      text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 0, setup_mode + '  (Q ' + str.tostring(k_Q_eff) + ' / R ' + str.tostring(k_R_eff) + ')',
         text_color = setup_mode == 'Custom' ? color.gray : color.aqua, text_size = size.small)
    table.cell(t, 0, 1, 'Timeframe', text_color = color.gray,  text_size = size.small)
    table.cell(t, 1, 1, timeframe.period, text_color = color.white, text_size = size.small)
    table.cell(t, 0, 2, 'Lookback',  text_color = color.gray,  text_size = size.small)
    table.cell(t, 1, 2, str.tostring(length) + (autoMode ? ' (auto)' : ' (manual)'), text_color = color.white, text_size = size.small)
    table.cell(t, 0, 3, 'Scales',    text_color = color.gray,  text_size = size.small)
    table.cell(t, 1, 3, str.tostring(s1) + '/' + str.tostring(s2) + '/' + str.tostring(s3) + '/' + str.tostring(s4), text_color = color.white, text_size = size.small)
    table.cell(t, 0, 4, 'Hurst',     text_color = color.gray,  text_size = size.small)
    table.cell(t, 1, 4, na(boundedHurst) ? '—' : str.tostring(boundedHurst, '#.###'), text_color = hurstColour, text_size = size.small)
    table.cell(t, 0, 5, 'Regime',    text_color = color.gray,  text_size = size.small)
    table.cell(t, 1, 5, regime,      text_color = hurstColour, text_size = size.small)
    table.cell(t, 0, 6, 'Cycle (FLD)', text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 6, str.tostring(fld_period) + ' bars → +' + str.tostring(fld_shift) + (fld_mode == 'Manual' ? ' (manual)' : ' (auto)'),
         text_color = fld_col, text_size = size.small)
    table.cell(t, 0, 7, 'Gain K',    text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 7, na(k_gain) ? '—' : str.tostring(k_gain, '#.###') + ' vs med ' + str.tostring(k_med, '#.###'),
         text_color = gain_ok ? color.aqua : color.yellow, text_size = size.small)
    table.cell(t, 0, 8, 'Age / ΔH',  text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 8, str.tostring(regime_age) + ' bars / ' + (h_delta >= 0 ? '+' : '') + str.tostring(h_delta, '#.###'),
         text_color = age_ok and momentum_ok ? color.aqua : color.yellow, text_size = size.small)
    table.cell(t, 0, 9, 'Status',    text_color = color.gray, text_size = size.small)
    table.cell(t, 1, 9, status,      text_color = status_col, text_size = size.small)
 
// =================================================================================================
// 10. Alerts
// =================================================================================================
// Kalman trend changes
if kalman_est[1] < kalman_est[2] and kalman_est > kalman_est[1]
    alert('KF-Hurst: Kalman trend change — Falling → Rising', alert.freq_once_per_bar)
 
if kalman_est[1] > kalman_est[2] and kalman_est < kalman_est[1]
    alert('KF-Hurst: Kalman trend change — Rising → Falling', alert.freq_once_per_bar)
 
// FLD crosses (cycle turns)
if barstate.isconfirmed and fld_cross_up
    alert('KF-Hurst: FLD cross UP — close through FLD, cycle turning up (period ' + str.tostring(fld_period) + ')', alert.freq_once_per_bar)
 
if barstate.isconfirmed and fld_cross_dn
    alert('KF-Hurst: FLD cross DOWN — close through FLD, cycle turning down (period ' + str.tostring(fld_period) + ')', alert.freq_once_per_bar)
 
// Regime state changes (confirmed bars only)
if alert_regime and barstate.isconfirmed
    if setup_ok and not setup_ok[1]
        alert('KF-Hurst: ' + setup_mode + ' regime ACTIVE and gates passed (H = ' + str.tostring(boundedHurst, '#.###') + ', K = ' + str.tostring(k_gain, '#.###') + ') — setups permitted', alert.freq_once_per_bar)
 
    if mode_matched and not setup_ok and not (mode_matched[1] and not setup_ok[1])
        alert('KF-Hurst: ' + setup_mode + ' regime live but GATED — quality filter blocking setups (K, age, or H-momentum)', alert.freq_once_per_bar)
 
    if wrong_regime and not wrong_regime[1]
        string live = tf_active ? 'TREND' : 'MEAN-REVERSION'
        alert('KF-Hurst: OPPOSITE REGIME — market is ' + live + ' but mode is ' + setup_mode + '. DO NOT TRADE this mode. Swap preset or stand aside.', alert.freq_once_per_bar)

← 返回列表