将Pine Script v2.0版本的trendFilter指标转换为v4.0版本并解决前置引用变量问题
Converting trendFilter from Pine Script v2 to v4 (Removing Forward References)
Got it, let's walk through converting your v2 indicator to v4 while fixing the forward reference issue. First, I'll note the key changes needed, then share the fully converted code.
Key Changes from v2 to v4:
- Replaced
studywithindicator(v4's standard declaration for indicators) - Restored the commented-out
Pdinput andPcalculation—these are critical for theavariable to work, so they can't stay commented - Removed forward references by using previous bar values (e.g.,
Tsl[1]instead ofTsl[0]) since v4 prohibits referencing a variable before it's defined - Used the
varkeyword to initialize persistent variables that retain values across bars (required for tracking trend state over time) - Switched to
:=for updatingvarvariables (v4's assignment syntax for mutable persistent values) - Updated color handling to use v4's color functions (you can keep hex codes too, but this is more idiomatic)
Fully Converted Pine Script v4 Code
//@version=4 indicator("trendFilter", overlay=true) // Restore required inputs and calculations (commented in original v2 code) Pd = input(200, title="Period") Factor = input(0.9, title="Factor") P = pow(Pd, 2) a = 2 / (P + 1) // Initialize persistent variables to track state across bars var float t = na var float TrendUp = na var float TrendDown = na var int Trend = 1 var float Tsl = na // Use previous bar's Tsl value (or hl2 for the first bar) to avoid forward references prevTsl = nz(Tsl[1], hl2) // Calculate core values using previous state d = abs(close - prevTsl) t := a * d + (1 - a) * nz(t[1], d) src = Factor * prevTsl + (1 - Factor) * close Up = prevTsl - t Dn = prevTsl + t // Update trend tracking variables TrendUp := src[1] > TrendUp[1] ? max(Up, TrendUp[1]) : Up TrendDown := src[1] < TrendDown[1] ? min(Dn, TrendDown[1]) : Dn // Determine current trend direction Trend := src > TrendDown[1] ? 1 : src < TrendUp[1] ? -1 : nz(Trend[1], 1) // Calculate current TSL value Tsl := Trend == 1 ? TrendDown : TrendUp // Set plot color based on TSL direction css = Tsl > Tsl[1] ? color.new(color.blue, 0) : Tsl < Tsl[1] ? color.new(color.red, 0) : na // Plot the TSL line plot(Tsl, color=fixnan(css), transp=0)
This code maintains the original indicator's logic while complying with v4's rules. The main fix for forward references is using prevTsl (the prior bar's TSL value) instead of trying to reference the current bar's uncalculated TSL value.
内容的提问来源于stack exchange,提问作者iHRSd
相关产品推荐
相关产品推荐

