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

Pine Script代码第22行输入不匹配错误排查求助

Pine Script策略代码输入不匹配错误排查

错误原因分析

  • 三元运算符不完整:Pine Script的三元表达式要求必须遵循condition ? 真值 : 假值的完整结构,你的代码中stopDistance和stopPrice仅定义了条件为真时的返回值,缺少假值分支,直接导致类型不匹配错误。
  • 变量拼写错误:退出条件中的stopComdition是拼写错误,正确应为stopCondition,拼写错误会让止损判断逻辑失效。

修正后的完整代码

strategy("My strategy", 
     overlay=true, 
     initial_capital = 500, 
     default_qty_type = strategy.percent_of_equity, 
     default_qty_value = 100, 
     commission_type = strategy.commission.cash_per_contract, 
     commission_value = .005)

i_ma1         = input.int(title = "MA 1 Length", defval = 200, step = 10, group = "Strategy Parameters", tooltip = "长期均线")
i_ma2         = input.int(title = "MA 2 Length", defval = 10, step = 10, group = "Strategy Parameters", tooltip = "短期均线")
i_stopPercent = input.float(title = "止损百分比", defval = 0.10, step = 0.10, group = "Strategy Parameters", tooltip = "止损下跌百分比阈值")
i_startTime   = input.time(title = "起始过滤时间", defval = timestamp("01 Jan 1995 13:30 +0000"), group = "时间过滤", tooltip = "开始日期和时间")
i_endTime     = input.time(title = "结束过滤时间", defval = timestamp("1 Jan 2099 19:30 +0000"), group = "时间过滤", tooltip = "结束日期和时间")

ma1 = ta.sma(close, i_ma1)
ma2 = ta.sma(close, i_ma2)

f_dateFilter = time >= i_startTime and time <= i_endTime

var float buyPrice = 0
buyCondition    = close > ma1 and close < ma2 and strategy.position_size == 0 and f_dateFilter
sellCondition   = close > ma2 and strategy.position_size > 0
// 补全三元运算符的假值分支,无持仓时返回na
stopDistance    = strategy.position_size > 0 ? ((buyPrice - close) / close) : na
stopPrice       = strategy.position_size > 0 ? buyPrice - (buyPrice * i_stopPercent) : na
stopCondition   = strategy.position_size > 0 and stopDistance > i_stopPercent

if buyCondition
    strategy.entry(id="Long", direction = strategy.long)

if buyCondition[1]
    buyPrice := open

if sellCondition or stopCondition
    // 修正拼写错误:stopComdition → stopCondition
    strategy.close(id = "Long", comment = "Exit" + (stopCondition ? "SL=True" : ""))
    buyPrice := na

关键修正点说明

  1. 三元运算符补全:为stopDistance和stopPrice添加: na分支,当无持仓时返回na,避免因类型不匹配触发报错。
  2. 拼写错误修复:将stopComdition改为正确的stopCondition,确保止损条件的判断逻辑能正常执行。

内容的提问来源于stack exchange,提问作者phillip barnes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 00:40:42