PineScript代码第21行else if语句报错,请求排查原因
PineScript v4 中else if语法错误原因分析
错误核心原因
PineScript的if/else if结构有严格的语法规则,你的代码违反了以下要求:
- 代码块必须统一缩进:
if条件下的strategy.entry("Long", strategy.long, tradeSize)没有缩进,编译器会判定if块在tradeSize = ...行就已经结束 - else if必须紧跟对应if块:因为前面的
if块被提前终止,后续的else if找不到匹配的父级if,直接触发语法错误 - 额外问题:
else if块内的tradeSize和strategy.entry同样未缩进,也不符合语法规范
修正后的完整代码
//@version=4 tradeDirection = input(direction.up, "Trade Direction") // direction of the breakout (up or down) breakoutPeriod = input(14, "Breakout Period") // number of bars to look back for the breakout stopLoss = input(0.002, "Stop Loss") // stop loss in percentage of the trade value takeProfit = input(0.004, "Take Profit") // take profit in percentage of the trade value maxTrades = input(2, "Maximum Number of Trades") // maximum number of open trades at the same time maxRisk = input(0.01, "Maximum Risk per Trade") // maximum risk per trade in percentage of account value // Next, we create a variable to track the highest or lowest price in the breakout period breakoutPrice = tradeDirection == direction.up ? highest(high, breakoutPeriod) : lowest(low, breakoutPeriod) // Then, we check if the current price has broken out of the breakout period and if we have not reached the maximum number of open trades if (tradeDirection == direction.up and close > breakoutPrice and strategy.opentrades < maxTrades) // If it has, we calculate the trade size based on the maximum risk per trade tradeSize = maxRisk / (stopLoss * close) // And enter a long position with the calculated trade size strategy.entry("Long", strategy.long, tradeSize) else if (tradeDirection == direction.down and close < breakoutPrice and strategy.opentrades < maxTrades) // If it has, we calculate the trade size based on the maximum risk per trade tradeSize = maxRisk / (stopLoss * close) // And enter a short position with the calculated trade size strategy.entry("Short", strategy.short, tradeSize) // Finally, we set our stop loss and take profit levels strategy.exit("Stop Loss", "Long", stopLossType.percent, stopLoss) strategy.exit("Take Profit", "Long", profitType.percent, takeProfit) // We repeat the same process for the short position strategy.exit("Stop Loss", "Short", stopLossType.percent, stopLoss) strategy.exit("Take Profit", "Short", profitType.percent, takeProfit)
内容的提问来源于stack exchange,提问作者Ricta
相关产品推荐
相关产品推荐

