Pine Script编译报错:第19行存在‘未使用行延续符的行尾’语法错误
Pine Script v4 语法错误排查求助
我写了一段基于Pine Script v4的交易策略代码,逻辑是价格突破昨日最高价时开多单,跌破昨日最低价时开空单,同时设置了止损(stopLoss)和止盈(takeProfit)参数。但编译时提示第19行存在「未使用行延续符的行尾」语法错误,试过Stack Overflow和Pine Script官方指南的解决方案,问题仍未解决,恳请协助排查。
报错代码如下:
// @version=4 // This is a trading bot that opens long positions if the price goes over the last day's maximum price, // and opens short positions if the price goes below the last day's minimum price. // The number of pips to use for the stop loss. var stopLoss = 20 // The number of pips to use for the take profit. var takeProfit = 40 // Get the last day's high and low prices. var lastDayHigh = security(tickerid, 'D', high, lookahead=barmerge.lookahead_on) var lastDayLow = security(tickerid, 'D', low, lookahead=barmerge.lookahead_on) // Check if the current price is above the last day's high. if close[0]>lastDayHigh[1] // Open a long position with a stop loss and take profit. strategy.entry("Long", strategy.long, stop=strategy.position_avg_price * (1 + stopLoss / 100), limit=strategy.position_avg_price * (1 + takeProfit / 100)) // Check if the current price is below the last day's low. else if close[0] < lastDayLow[1] // Open a short position with a stop loss and take profit. strategy.entry("Short", strategy.short, stop=strategy.position_avg_price * (1 - stopLoss / 100), limit=strategy.position_avg_price * (1 - takeProfit / 100))
问题排查与修正方案
1. 语法错误根源:缺少行延续符
Pine Script v4中,函数参数跨多行书写时,必须在每行末尾添加行延续符\,否则会触发「未使用行延续符的行尾」错误。你的第19行(strategy.entry的第一行参数)末尾没有加\,导致编译失败。
2. 其他逻辑错误修正
除了语法问题,代码还有几个逻辑缺陷需要调整:
var关键字误用:lastDayHigh和lastDayLow使用var会只初始化一次,无法每日更新昨日高低价,需去掉var。- 过时变量
tickerid:v4中推荐使用syminfo.tickerid替代tickerid,避免兼容性问题。 - 止损止盈计算错误:开仓时
strategy.position_avg_price还未生成(开仓前无仓位),应该用当前突破价格(close)来计算止损止盈。 - 索引错误:
security函数取的是昨日的高低价,无需加[1]索引;close[0]可简化为close。
修正后的完整代码
// @version=4 strategy("突破昨日高低价策略", overlay=true) // 止损止盈点数(百分比/点数可自行调整) stopLoss = 20 takeProfit = 40 // 获取昨日高低价(每日更新) lastDayHigh = security(syminfo.tickerid, 'D', high[1], lookahead=barmerge.lookahead_on) lastDayLow = security(syminfo.tickerid, 'D', low[1], lookahead=barmerge.lookahead_on) // 突破昨日最高价开多 if close > lastDayHigh longStop = close * (1 - stopLoss / 10000) // 按点数计算(1点=0.0001),百分比则改为/100 longLimit = close * (1 + takeProfit / 10000) strategy.entry("Long", strategy.long, stop=longStop, limit=longLimit) // 跌破昨日最低价开空 else if close < lastDayLow shortStop = close * (1 + stopLoss / 10000) shortLimit = close * (1 - takeProfit / 10000) strategy.entry("Short", strategy.short, stop=shortStop, limit=shortLimit)
补充说明
- 若你的止损止盈是按百分比计算,将代码中的
/10000改为/100即可;按点数计算则保持/10000(适用于多数货币对)。 - 添加
overlay=true让策略信号叠加在主图上,方便观察价格与信号的对应关系。
内容的提问来源于stack exchange,提问作者esx
相关产品推荐
相关产品推荐

