本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Adaptive MA-Kalman", shorttitle = "Adaptive MA-Kalman", overlay = true, format = format.price, max_bars_back = 1000)
// SETTINGS
// Data Source
force_ha = input.bool(false, "Force Heikin Ashi", group="Data Source",
tooltip = "Forces the use of native Heikin-Ashi candles for calculating the price source")
// Global Smoothing (ALMA)
smooth_len = input.int(2, "Global Smoothing Length", minval=1, group="Global Smoothing",
tooltip = "Base smoothing length for internal calculations.")
smooth_off = input.float(0.85, "Global Smoothing Offset", minval=0.05, maxval=1.0, step=0.05, group="Global Smoothing",
tooltip = "Offset parameter for internal ALMA smoothing.")
smooth_sig = input.float(1.5, "Global Smoothing Sigma", minval=0.0, step=0.25, group="Global Smoothing",
tooltip = "Sigma parameter determining the width of internal ALMA smoothing.")
// Kalman Window Settings (Auto-Calibration)
use_grid_em = input.bool(true, "Dynamic Matrix EM Grid", group="Kalman Window Settings",
tooltip = "Enables dynamically scaled selection of Q, R variants and Student-t degrees of freedom in the Evasion window.")
qrSensitivity = input.float(1.0, "Auto Q/R Sensitivity Multiplier", minval=0.1, maxval=5.0, step=0.05, group="Kalman Window Settings",
tooltip = "Automatically scales the calculated Q/R ratio. >1.0 = faster reaction (larger Q, smaller R), <1.0 = stronger smoothing.")
kalmanWindow = input.int(9, "Kalman Window", minval = 2, maxval = 50, group="Kalman Window Settings",
tooltip = "Base micro-window for the Kalman filter and GKYZ estimation.")
// Evasion Buffer and Volume Filter Settings
evasion_mult = input.float(0.24, "Noise Channel Width", minval = 0.0, maxval = 3.0, step = 0.005, group="Evasion Settings",
tooltip = "Base Evasion width smoothing out minor price fluctuations.")
volume_boost = input.float(0.25, "Volume Filter Sensitivity", minval = 0.0, maxval = 3.0, step = 0.025, group="Evasion Settings",
tooltip = "Volume buffer sensitivity multiplier")
// ALMA Medium
showMedium = input.bool(true, "Show Medium ALMA", group="ALMA Medium",
tooltip = "Enables or disables Medium ALMA on the chart.")
medLen = input.int(30, "Medium Length", minval=1, group="ALMA Medium",
tooltip = "Length for Medium ALMA.")
medOff = input.float(0.8, "Medium Offset", minval=0.05, maxval=1.0, step=0.05, group="ALMA Medium",
tooltip = "Offset for Medium ALMA.")
medSig = input.float(5.0, "Medium Sigma", minval=0.25, step=0.25, group="ALMA Medium",
tooltip = "Sigma for Medium ALMA.")
// ALMA Long
showLong = input.bool(true, "Show Long ALMA", group="ALMA Long",
tooltip = "Enables or disables Long ALMA on the chart.")
longLen = input.int(120, "Long Length", minval=1, group="ALMA Long",
tooltip = "Length for Long ALMA.")
longOff = input.float(0.8, "Long Offset", minval=0.05, maxval=1.0, step=0.05, group="ALMA Long",
tooltip = "Offset for Long ALMA.")
longSig = input.float(5.0, "Long Sigma", minval=0.25, step=0.25, group="ALMA Long",
tooltip = "Sigma for Long ALMA.")
// Evasion Window Automation
int parkinsonWindow = kalmanWindow
int evasionWindow = parkinsonWindow * 18
// Styles
bullColor = color.rgb(36, 218, 187)
bearColor = color.rgb(212, 30, 45)
neutralColor = color.rgb(114, 116, 122)
col_fill_bull = input.color(color.new(color.green, 80), "Channel Fill (Bullish)", group="Style")
col_fill_bear = input.color(color.new(color.red, 80), "Channel Fill (Bearish)", group="Style")
// HEIKIN ASHI BLOCK
ha_ticker = ticker.heikinashi(syminfo.tickerid)
[ha_s_open, ha_s_high, ha_s_low, ha_s_close] = request.security(ha_ticker, timeframe.period, [open, high, low, close], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
float current_open = force_ha ? ha_s_open : open
float current_high = force_ha ? ha_s_high : high
float current_low = force_ha ? ha_s_low : low
float current_close = force_ha ? ha_s_close : close
// SOURCE & VOLATILITY CALCULATIONS
float candleSpread = math.abs(current_close - current_open)
float candleRange = current_high - current_low
float closePosition = candleRange > 0.0 ? (current_close - current_low) / candleRange : 0.5
float volumeFlowDirection = (closePosition - 0.5) * 2.0
float upperWick = current_high - math.max(current_open, current_close)
float lowerWick = math.min(current_open, current_close) - current_low
float totalWicks = upperWick + lowerWick
float knotAsymmetry = totalWicks > 0.0 ? (lowerWick - upperWick) / totalWicks : 0.0
float p_momentum = (current_close - current_open) / math.max(candleSpread, 0.00000001)
float gravityShift = (volumeFlowDirection * 0.3) + (knotAsymmetry * 0.15) + (p_momentum * 0.05)
float parabolicPOCFactor = 0.5 + math.max(-0.45, math.min(0.45, gravityShift))
float parabolicCentroid = current_low + (candleRange * parabolicPOCFactor)
float prev_current_close = nz(current_close[1], current_open)
float midPoint = (current_open + prev_current_close) / 2.0
float raw_srcInput = candleRange > 0.0 ? parabolicCentroid : midPoint
srcInput = ta.alma(raw_srcInput, smooth_len, smooth_off, smooth_sig)
// GKYZ Hybrid Core
float effHigh = math.max(current_high, prev_current_close)
float effLow = math.max(math.min(current_low, prev_current_close), 0.00000001)
float GK_COEF = 2.0 * math.log(2.0) - 1.0
float overnightReturn = current_open > 0.0 and prev_current_close > 0.0 ? math.log(current_open / prev_current_close) : 0.0
float overnightVariance = math.pow(overnightReturn, 2.0)
float pct_h_l = effHigh > 0.0 and effLow > 0.0 ? math.log(effHigh / effLow) : 0.0
float pct_c_o = current_open > 0.0 and current_close > 0.0 ? math.log(current_close / current_open) : 0.0
float gk_core = 0.5 * math.pow(pct_h_l, 2.0) - GK_COEF * math.pow(pct_c_o, 2.0)
float pct_h_c = effHigh > 0.0 and current_close > 0.0 ? math.log(effHigh / current_close) : 0.0
float pct_h_o = effHigh > 0.0 and current_open > 0.0 ? math.log(effHigh / current_open) : 0.0
float pct_l_c = effLow > 0.0 and current_close > 0.0 ? math.log(effLow / current_close) : 0.0
float pct_l_o = effLow > 0.0 and current_open > 0.0 ? math.log(effLow / current_open) : 0.0
float rs_core = pct_h_c * pct_h_o + pct_l_c * pct_l_o
float intradayVariance = (math.max(gk_core, 0.0) + math.max(rs_core, 0.0)) / 2.0
float hybrid_element = (0.5 * overnightVariance) + (0.5 * intradayVariance)
float gkyzMeanVariance = ta.alma(hybrid_element, parkinsonWindow, smooth_off, smooth_sig)
float finalVolatilityPct = na(gkyzMeanVariance) or gkyzMeanVariance < 0.0 ? 0.001 : math.max(math.sqrt(gkyzMeanVariance), 0.001)
float statistical_gkyz = ta.alma(finalVolatilityPct * current_close, evasionWindow, smooth_off, smooth_sig)
// OPTIMIZED WINDOW STATISTICS
logSrc = math.log(math.max(srcInput, 0.00001))
logReturn = nz(ta.change(logSrc))
smoothLogReturn = ta.alma(logReturn, smooth_len, smooth_off, smooth_sig)
int num_steps = evasionWindow - kalmanWindow + 1
float series_stdev = nz(ta.stdev(smoothLogReturn, kalmanWindow), 0.0001)
float series_gkyz = nz(ta.alma(finalVolatilityPct, kalmanWindow, 0.85, 1), 0.001)
// KALMAN ENGINE WITH DEGREES OF FREEDOM AUTOMATION
array<float> q_mults = array.new<float>(num_steps, 0.0)
array<float> r_mults = array.new<float>(num_steps, 0.0)
array<float> df_grid = array.new<float>(num_steps, 5.0)
array<float> window_stdevs = array.new<float>(num_steps, 0.0)
array<float> window_gkyz = array.new<float>(num_steps, 0.0)
float sum_stdevs = 0.0
float sum_gkyz = 0.0
for i = 0 to num_steps - 1
float stdev_i = nz(series_stdev[i], 0.0001)
float gkyz_i = nz(series_gkyz[i], 0.001)
array.set(window_stdevs, i, stdev_i)
array.set(window_gkyz, i, gkyz_i)
sum_stdevs += stdev_i
sum_gkyz += gkyz_i
rollingShortStDev = array.get(window_stdevs, 0)
rollingShortGkyz = array.get(window_gkyz, 0)
rollingMacroStDev = sum_stdevs / float(num_steps)
rollingMacroGkyz = sum_gkyz / float(num_steps)
rawVolRatio = rollingMacroStDev > 0 ? rollingShortStDev / rollingMacroStDev : 1.0
volRatio = ta.alma(rawVolRatio, smooth_len + 1, smooth_off, smooth_sig)
rawGkyzRatio = rollingMacroGkyz > 0 ? rollingShortGkyz / rollingMacroGkyz : 1.0
gkyzRatio = ta.alma(rawGkyzRatio, smooth_len + 1, smooth_off, smooth_sig)
float baselineMacro = ta.alma(rollingMacroStDev, evasionWindow, smooth_off, smooth_sig)
baselineMacro := na(baselineMacro) or baselineMacro <= 0 ? rollingMacroStDev : baselineMacro
float spreadFactor = math.max(0.3, math.min(3.0, rollingMacroStDev / baselineMacro))
float base_df_anchor = 5.0 / math.max(gkyzRatio, 0.2)
for i = 0 to num_steps - 1
float stepPos = num_steps > 1 ? (i - (num_steps - 1) / 2.0) / ((num_steps - 1) / 2.0) : 0.0
float window_dev = rollingMacroStDev > 0 ? (array.get(window_stdevs, i) / rollingMacroStDev) : 1.0
float window_gkyz_dev = rollingMacroGkyz > 0 ? (array.get(window_gkyz, i) / rollingMacroGkyz) : 1.0
float qm = math.exp(stepPos * 0.7 * spreadFactor * window_dev)
float rm = math.exp(-stepPos * 0.7 * spreadFactor / window_dev)
float candidate_df = base_df_anchor / math.max(window_gkyz_dev, 0.25)
candidate_df := math.max(2.5, math.min(30.0, candidate_df))
array.set(q_mults, i, qm)
array.set(r_mults, i, rm)
array.set(df_grid, i, candidate_df)
var float best_q_mult = 1.0
var float best_r_mult = 1.0
var float best_df = 5.0
if use_grid_em and bar_index > evasionWindow
float min_err = 1e10
for i = 0 to array.size(q_mults) - 1
float qm = array.get(q_mults, i)
float candidate_err = math.abs(math.log(qm) - math.log(math.max(volRatio, 0.0001)))
if candidate_err < min_err
min_err := candidate_err
best_q_mult := qm
best_r_mult := array.get(r_mults, i)
best_df := array.get(df_grid, i)
else
best_q_mult := 1.0
best_r_mult := 1.0
best_df := math.max(2.5, math.min(30.0, base_df_anchor))
// AUTOMATIC CALIBRATION OF BASE Q/R
float macroVarClose = math.pow(rollingMacroStDev, 2.0)
float macroVarGkyz = math.pow(rollingMacroGkyz, 2.0)
float autoBaseR = math.max(macroVarGkyz, 1e-7)
float noiseToSignal = macroVarGkyz > 0 ? (macroVarClose / macroVarGkyz) : 0.2
float autoBaseQ = autoBaseR * math.max(0.05, math.min(2.0, noiseToSignal))
targetR = (autoBaseR / qrSensitivity) * (volRatio + 0.1) * best_r_mult
targetQ = (autoBaseQ * qrSensitivity) * (volRatio + 0.1) * best_q_mult
dynamicR = ta.alma(targetR, smooth_len, smooth_off, smooth_sig)
dynamicQ = ta.alma(targetQ, smooth_len, smooth_off, smooth_sig)
dynamicDf = ta.alma(best_df, smooth_len, smooth_off, smooth_sig)
// KALMAN FILTER STEP (T-STUDENT ROBUST)
var float x_est = na
var float p_cov = 1.0
if bar_index == 0 or na(x_est)
x_est := logSrc
p_cov := 1.0
x_pred = x_est
p_pred = p_cov + dynamicQ
float innovation = logSrc - x_pred
float scaledInnov = math.abs(innovation) / math.sqrt(math.max(p_pred + dynamicR, 1e-8))
float t_weight = (dynamicDf + 1.0) / (dynamicDf + math.pow(scaledInnov, 2.0))
t_weight := math.max(0.05, math.min(1.0, t_weight))
float effectiveR = dynamicR / t_weight
kalmanGain = p_pred / (p_pred + effectiveR)
x_est := x_pred + kalmanGain * innovation
p_cov := (1.0 - kalmanGain) * p_pred
est = math.exp(x_est)
// BASE EVASION CHANNEL AND VOLUME FILTER
float base_evasion_width = statistical_gkyz * evasion_mult
float evasion_upper = est + base_evasion_width
float evasion_lower = est - base_evasion_width
float pctPocDist = math.abs(math.log(math.max(parabolicCentroid, 0.00001)) - math.log(math.max(est, 0.00001)))
float normalizedPocDist = finalVolatilityPct > 0 ? pctPocDist / finalVolatilityPct : pctPocDist
float safe_volume = nz(volume) > 0 ? volume : 1.0
float baseVolMA = ta.alma(safe_volume, kalmanWindow, 0.85, 1.0)
float relVol = baseVolMA > 0 ? safe_volume / baseVolMA : 1.0
float logVolumeImpact = normalizedPocDist * relVol
float avgLogImpact = ta.alma(logVolumeImpact, kalmanWindow, 0.85, 1.0)
float volumeAnomaly = avgLogImpact > 0 ? logVolumeImpact / avgLogImpact : 1.0
float rubberBuffer = math.max(0.0, volumeAnomaly - 1.0) * volume_boost * base_evasion_width
// DECISION AND VISUAL THRESHOLDS
float trigger_upper = evasion_upper + rubberBuffer
float trigger_lower = evasion_lower - rubberBuffer
var int trend_state = 0
if trend_state <= 0 and srcInput > trigger_upper
trend_state := 1
else if trend_state >= 0 and srcInput < trigger_lower
trend_state := -1
if trend_state == 0
trend_state := srcInput >= est ? 1 : -1
color estColor = trend_state == 1 ? bullColor : bearColor
est_medium = ta.alma(raw_srcInput, medLen, medOff, medSig)
slope_m = nz(ta.change(est_medium))
estColor_m = slope_m > 0 ? bullColor : slope_m < 0 ? bearColor : neutralColor
est_long = ta.alma(raw_srcInput, longLen, longOff, longSig)
slope_l = nz(ta.change(est_long))
estColor_l = slope_l > 0 ? bullColor : slope_l < 0 ? bearColor : neutralColor
// PLOTS & CHART
plot_est = plot(est, "Short Kalman", color = estColor, linewidth = 2)
plot_med = plot(showMedium ? est_medium : na, "Medium ALMA", color = estColor_m, linewidth = 2)
plot_lng = plot(showLong ? est_long : na, "Long ALMA", color = estColor_l, linewidth = 3)
p_upper = plot(trigger_upper, color = color.new(color.green, 60), title = "Evasion Upper Bound")
p_lower = plot(trigger_lower, color = color.new(color.red, 60), title = "Evasion Lower Bound")
color channel_fill_color = trend_state == 1 ? col_fill_bull : col_fill_bear
fill(p_upper, p_lower, color = channel_fill_color, editable = false, title = "Evasion Channel Fill")