State-Dependent EMA [BackQuant]

BackQuant · study · 156 行 · 点赞 190 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © BackQuant
 
//@version=6
indicator("State-Dependent EMA [BackQuant]", shorttitle="State EMA [BackQuant]", overlay=true)
 
// Constants
const string calc = "Core Calculation Settings"
const string state = "State Estimation"
const string ui = "Plotting and Coloring"
const color GREEN = #00ff00
const color RED = #ff0000
 
// Inputs
float src = input.source(close, "Source", group=calc)
int fastLen = input.int(4, "Fast EMA Length", minval=1, group=calc, inline="LEN")
int slowLen = input.int(40, "Slow EMA Length", minval=2, group=calc, inline="LEN")
string stateMode = input.string("Combined", "State Model", options=["Combined", "Efficiency", "Sustained Residual"], group=calc)
 
int erLen = input.int(20, "Efficiency Length", minval=2, group=state)
int residualLen = input.int(4, "Residual Persistence", minval=1, group=state)
int atrLen = input.int(14, "ATR Length", minval=2, group=state)
float residualScale = input.float(1.5, "Residual Scale", minval=0.1, step=0.1, group=state)
float efficiencyWeight = input.float(0.5, "Efficiency Weight", minval=0.0, maxval=1.0, step=0.05, group=state, inline="WT")
float residualWeight = input.float(0.5, "Residual", minval=0.0, maxval=1.0, step=0.05, group=state, inline="WT")
int shortVarLen = input.int(10, "Short Variance Length", minval=2, group=state, inline="VAR")
int longVarLen = input.int(40, "Long", minval=3, group=state, inline="VAR")
float variancePenalty = input.float(1.0, "Variance Penalty", minval=0.0, maxval=5.0, step=0.1, group=state, tooltip="Reduces alpha when short-term return volatility exceeds its longer-term baseline. Set to 0 to disable.")
 
color longCol = input.color(GREEN, "Long Color", group=ui, inline="COL")
color shortCol = input.color(RED, "Short Color", group=ui, inline="COL")
int lineW = input.int(3, "Line Width", minval=1, maxval=6, group=ui)
int ribbonLen = input.int(9, "Ribbon Length", minval=2, group=ui)
string trendMode = input.string("Ribbon", "Trend Direction", options=["Ribbon", "Filter Slope"], group=ui)
int trendLookback = input.int(2, "Slope Lookback", minval=1, group=ui)
bool showRibbon = input.bool(true, "Gradient Ribbon", group=ui)
bool showFill = input.bool(true, "Price Gradient Fill", group=ui)
bool showGlow = input.bool(true, "Filter Glow", group=ui)
bool showBaseline = input.bool(false, "Show Fixed EMA Comparison", group=ui)
int baselineLen = input.int(20, "Comparison Length", minval=1, group=ui)
bool paintCandles = input.bool(false, "Paint Candles", group=ui)
bool bgCol = input.bool(false, "Background Color", group=ui)
 
// Efficiency
float change = src - src[1]
float travel = ta.sma(math.abs(change), erLen) * erLen
float displacement = math.abs(src - src[erLen])
float efficiency = not na(travel) and travel > 0.0 ? math.min(displacement / travel, 1.0) : 0.0
 
// Variance
float shortVol = ta.stdev(change, shortVarLen)
float longVol = ta.stdev(change, longVarLen)
float varianceRatio = not na(shortVol) and not na(longVol) and longVol > 0.0 ? shortVol / longVol : 1.0
float varianceGate = 1.0 / (1.0 + variancePenalty * math.max(varianceRatio - 1.0, 0.0))
 
// Sustained Residual
var float filt = na
float innovation = src - nz(filt[1], src)
float persistentResidual = ta.ema(innovation, residualLen)
float atr = ta.atr(atrLen)
float normalizedResidual = math.abs(persistentResidual) / math.max(nz(atr, syminfo.mintick), syminfo.mintick)
float residualState = math.min(normalizedResidual / residualScale, 1.0)
 
// State Model
float totalWeight = efficiencyWeight + residualWeight
float combinedState = totalWeight > 0.0 ? (efficiency * efficiencyWeight + residualState * residualWeight) / totalWeight : 0.0
 
float rawState = switch stateMode
    "Efficiency" => efficiency
    "Sustained Residual" => residualState
    => combinedState
 
float marketState = math.max(0.0, math.min(1.0, rawState * varianceGate))
 
// Adaptive Alpha
float fastAlpha = 2.0 / (fastLen + 1.0)
float slowAlpha = 2.0 / (math.max(slowLen, fastLen + 1) + 1.0)
float alpha = slowAlpha + (fastAlpha - slowAlpha) * marketState
 
// State-Dependent EMA
filt := na(filt[1]) ? src : filt[1] + alpha * (src - filt[1])
 
// Ribbon
float ribbonRef = ta.ema(filt, ribbonLen)
float baseline = ta.ema(src, baselineLen)
 
// Trend
bool bullish = trendMode == "Ribbon" ? filt > ribbonRef : filt > filt[trendLookback]
bool bearish = trendMode == "Ribbon" ? filt < ribbonRef : filt < filt[trendLookback]
 
var int trend = 0
 
if bullish
    trend := 1
else if bearish
    trend := -1
 
color col = trend == 1 ? longCol : trend == -1 ? shortCol : chart.fg_color
 
// Hidden Fill References
pFilter = plot(filt, "Filter Reference", display=display.none, editable=false)
pPrice = plot(close, "Price Reference", display=display.none, editable=false)
pRibbon = plot(showRibbon ? ribbonRef : na, "Ribbon Reference", color.new(col, 65), 2)
 
// Price Gradient
float priceTop = math.max(close, filt)
float priceBottom = math.min(close, filt)
 
color priceTopCol = close > filt ? color.new(col, 92) : color.new(col, 20)
color priceBottomCol = close > filt ? color.new(col, 20) : color.new(col, 92)
 
fill(pPrice, pFilter, priceTop, priceBottom, showFill ? priceTopCol : na, showFill ? priceBottomCol : na, title="Price Gradient")
 
// Ribbon Gradient
float ribbonTop = math.max(filt, ribbonRef)
float ribbonBottom = math.min(filt, ribbonRef)
 
color ribbonTopCol = filt > ribbonRef ? color.new(col, 25) : color.new(col, 90)
color ribbonBottomCol = filt > ribbonRef ? color.new(col, 90) : color.new(col, 25)
 
fill(pFilter, pRibbon, ribbonTop, ribbonBottom, showRibbon ? ribbonTopCol : na, showRibbon ? ribbonBottomCol : na, title="Trend Ribbon")
 
// Filter Glow
float glow = atr * 0.06
float outerGlow = glow * 2.0
 
pGlowUpper = plot(showGlow ? filt + glow : na, "Glow Upper", display=display.none, editable=false)
pGlowLower = plot(showGlow ? filt - glow : na, "Glow Lower", display=display.none, editable=false)
pOuterUpper = plot(showGlow ? filt + outerGlow : na, "Outer Glow Upper", display=display.none, editable=false)
pOuterLower = plot(showGlow ? filt - outerGlow : na, "Outer Glow Lower", display=display.none, editable=false)
 
fill(pOuterUpper, pOuterLower, showGlow ? color.new(col, 94) : na, title="Outer Glow")
fill(pGlowUpper, pGlowLower, showGlow ? color.new(col, 76) : na, title="Inner Glow")
 
// Main Filter
plot(filt, "State-Dependent EMA", col, lineW)
plot(showBaseline ? baseline : na, "Fixed EMA Comparison", color.new(chart.fg_color, 55), 1)
 
// Candles
plotcandle(open, high, low, close, "Trend Candles", col, col, true, bordercolor=col, display=paintCandles ? display.all : display.none)
bgcolor(bgCol ? color.new(col, 90) : na)
 
// Data Window
plot(alpha, "Adaptive Alpha", display=display.data_window)
plot(2.0 / alpha - 1.0, "Effective EMA Length", display=display.data_window)
plot(efficiency, "Efficiency Ratio", display=display.data_window)
plot(residualState, "Sustained Residual State", display=display.data_window)
plot(varianceRatio, "Variance Ratio", display=display.data_window)
plot(marketState, "Market State", display=display.data_window)
 
// Alerts
bool bullFlip = trend == 1 and trend[1] == -1
bool bearFlip = trend == -1 and trend[1] == 1
 
alertcondition(bullFlip, "State EMA Bullish", "State-Dependent EMA turned bullish {{exchange}}:{{ticker}}")
alertcondition(bearFlip, "State EMA Bearish", "State-Dependent EMA turned bearish {{exchange}}:{{ticker}}")

← 返回列表