You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TradingView策略脚本报错:IF函数'StochIN'语法错误求助

问题排查:TradingView策略脚本语法错误(Syntax error at input 'StochIN')

问题场景

编写用于测试指标优劣的TradingView策略,通过输入参数选择是否启用指标作为交易入场条件(比如启用Stochastic时,仅K线上穿D线才可入场),但脚本执行时在IF函数处触发「Syntax error at input 'StochIN'」错误,原代码如下:

StochIN = input(title="Stoch IN", type=input.bool, defval=true, group="Indicators", inline="5")

/// Stochastic
periodK = input(14, title="%K Length", minval=1, group="Stochastic")
smoothKSto = input(7, title="%K Smoothing", minval=1, group="Stochastic")
periodD = input(3, title="%D Smoothing", minval=1, group="Stochastic")
stok = sma(stoch(close, high, low, periodK), smoothKSto)
stod = sma(stok, periodD)

/////If Stochastic is selected, then StochIn variable becomes true only at crossover, otherwise it is always true
if StochIN
     StochIN := crossover(stok, stod) or crossover(stok[1], stod[1])
else
     StochIN := true

///second condition
rsiIN = input(title="RSI IN", type=input.bool, defval=true, group="Indicators", inline="8")

rsi = rsi(close, 14)

if rsiIN
     rsiIN := crossover(rsi, 30) or crossover(rsi[1], 30)
else
     rsiIN := true

////Enter the trade when all conditions are true. 
if StochIn and rsiIn
    strategy.entry("Long", strategy.long)

错误原因

Pine Script中,通过input()创建的输入变量是只读的,不允许重新赋值。原代码里将StochIN、rsiIN定义为输入参数后,又在if语句中用:=修改它们的值,这违反了语法规则,直接导致了报错。

修正后的代码

单独创建新变量存储条件判断结果,避免修改输入参数:

// 输入参数保留只读属性
StochIN = input(title="Stoch IN", type=input.bool, defval=true, group="Indicators", inline="5")

/// Stochastic指标计算
periodK = input(14, title="%K Length", minval=1, group="Stochastic")
smoothKSto = input(7, title="%K Smoothing", minval=1, group="Stochastic")
periodD = input(3, title="%D Smoothing", minval=1, group="Stochastic")
stok = sma(stoch(close, high, low, periodK), smoothKSto)
stod = sma(stok, periodD)

// 用新变量存储Stochastic条件结果
stochCondition = if StochIN
     crossover(stok, stod) or crossover(stok[1], stod[1])
else
     true

/// RSI输入参数
rsiIN = input(title="RSI IN", type=input.bool, defval=true, group="Indicators", inline="8")

rsi = rsi(close, 14)

// 用新变量存储RSI条件结果
rsiCondition = if rsiIN
     crossover(rsi, 30) or crossover(rsi[1], 30)
else
     true

//// 入场条件:所有条件满足时开多
if stochCondition and rsiCondition
    strategy.entry("Long", strategy.long)

内容的提问来源于stack exchange,提问作者Giovanni Dominoni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 04:08:21