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

Pine Script编写策略时math.round传参与变量作用域报错求助

Pine Script三均线策略报错修复

问题相关信息

原策略代码如下:

//@version=5
strategy("Mi semaforo", overlay=true, margin_long=100, margin_short=100)

mm_g = ta.sma(close, 5)
mm_y= ta.sma(close, 10)
mm_r = ta.sma(close, 20)

alcista = (mm_g > mm_y) and (mm_y > mm_r)
// bajista = (mm_g < mm_y) and (mm_y < mm_r)

comprado = strategy.position_size > 0

if (not comprado and alcista) 
    cantidad = math.round(strategy.equity, close)
    strategy.entry("Compra", strategy.long, cantidad)

if (comprado and not alcista) 
    strategy.close("Compra", comment="Venta")
  • 错误定位行:cantidad = math.round(strategy.equity, close)
  • 报错信息:
    1. 第17行:无法调用math.round,传入的precision参数值为close,该参数为series float类型,但函数要求传入simple int类型
    2. 第17行:变量cantidad未在#global_#0作用域中找到,无法注册副作用

错误原因

  1. 参数使用逻辑错误:math.round(数值, 精度)的第二个参数是指定保留小数位数的整数参数,误把close(序列浮点型的收盘价)传入作为精度值,不符合参数类型要求。从代码逻辑看,原本的意图是用总资金除以收盘价计算可开仓数量,不是把收盘价当取整精度。
  2. 变量作用域错误:Pine Script中如果变量仅在if条件的局部代码块内首次声明,全局作用域无法识别该变量,会导致交易指令调用时找不到对应变量的报错。

修复方法

  1. 修正开仓数量计算逻辑:使用strategy.equity / close计算当前权益可买入的标的数量,再调用math.round取整,取整精度传0(即保留0位小数,得到整数数量),符合下单数量必须为正整数的要求。
  2. 提前在全局作用域声明cantidad变量,if块内对变量赋值时使用:=操作符(Pine Script中给已声明的全局变量重新赋值的专用操作符)。

修复后完整可运行代码

//@version=5
strategy("Mi semaforo", overlay=true, margin_long=100, margin_short=100)

mm_g = ta.sma(close, 5)
mm_y= ta.sma(close, 10)
mm_r = ta.sma(close, 20)

alcista = (mm_g > mm_y) and (mm_y > mm_r)
// bajista = (mm_g < mm_y) and (mm_y < mm_r)

comprado = strategy.position_size > 0
// 全局声明开仓数量变量
cantidad = 0

if (not comprado and alcista) 
    // 计算全仓可买数量并取整
    cantidad := math.round(strategy.equity / close, 0)
    strategy.entry("Compra", strategy.long, cantidad)

if (comprado and not alcista) 
    strategy.close("Compra", comment="Venta")

内容的提问来源于stack exchange,提问作者Alexis Graff

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 21:21:25