如何修改Pine Script代码消除operator ?:的bool参数警告
Pine Script 三元运算符警告修复方案
问题根源
原代码中barsInDelay := request.security(syminfo.tickerid, "1", close[1]) ? barsInDelay + 1 : 0触发警告,核心原因是三元运算符?:的第一个参数必须传入布尔值,但request.security返回的是价格数值(浮点型),Pine Script会隐式将数值转换为布尔值(非零为true、零为false),这种隐式转换不符合参数规范,因此抛出警告。
修复方案
根据你的逻辑(计数延迟周期内的1分钟K线数量),需要将三元运算符的第一个参数改为显式布尔判断,以下两种方案可选:
方案1:判断1分钟周期是否生成新K线(推荐)
如果你的目的是每出现一根新的1分钟K线就计数+1,用barstate.isnew在1分钟周期内的状态判断是更准确的K线计数方式:
barsInDelay := request.security(syminfo.tickerid, "1", barstate.isnew) ? barsInDelay + 1 : 0
方案2:判断1分钟周期的close[1]是否有效
如果是要确保获取到有效的1分钟历史收盘价才计数,显式判断数值非空即可(你之前尝试的!= na写法错误,正确的非空判断是not na(表达式)):
barsInDelay := not na(request.security(syminfo.tickerid, "1", close[1])) ? barsInDelay + 1 : 0
完整修改后代码
//@version=5 contractsPerOrder = 5 strategy("Delayed Alerts", overlay=true, initial_capital = 20000, use_bar_magnifier = true, default_qty_value = contractsPerOrder) i_delayBars = input(1, "Delay in Bars") // How many lower timeframe bars must pass before sending alert var int barsInDelay = 0 // Initialize the barsInDelay variable // 替换为方案1的修复代码 barsInDelay := request.security(syminfo.tickerid, "1", barstate.isnew) ? barsInDelay + 1 : 0 // Count the number of bars in the delay timeframe delayElapsed = barsInDelay >= i_delayBars // Check if the i_delayBars have elapsed since the last alert buyCondition = close > ta.sma(close, 20) and close[1] > close[2] and close[2] > close[3] if buyCondition and delayElapsed buyAlertMessage = '{"ticker": "' + syminfo.ticker + '", "action": "buy", "price": ' + str.tostring(close) + ', "quantity": ' + str.tostring(contractsPerOrder) + '}' strategy.entry("Buy", strategy.long, alert_message = buyAlertMessage) if delayElapsed sellAlertMessage = '{"ticker": "' + syminfo.ticker + '", "action": "sell", "price": "{{close}}", "quantity": ' + str.tostring(contractsPerOrder) + '}' strategy.exit("Sell", profit = 5*5, loss = 10*4)
内容的提问来源于stack exchange,提问作者Margaux
相关产品推荐
相关产品推荐

