如何在Pine Script策略警报中添加止损与止盈价格
解决Pine Script警报无法获取止损止盈值的问题
问题出在strategy.order.stop和strategy.order.limit字段仅对纯粹的止损单/止盈单生效,而你用strategy.entry同时设置stop和limit的挂单模式下,这两个字段不会被自动填充。正确做法是手动把止损止盈值存为全局变量,再在警报模板中引用:
1. 修改Pine Script代码,添加全局变量存储止损止盈
在脚本开头定义全局变量,开仓时赋值:
// 定义全局变量存储止损止盈值 var float stopLossValue = na var float takeProfitValue = na // 计算当期止损止盈值 currentStop = close - riskLong currentTP = takeProfitLong // 赋值给全局变量 stopLossValue := currentStop takeProfitValue := currentTP // 执行开仓 strategy.entry("Long", strategy.long, stop = currentStop, limit = currentTP, qty = math.round(probLossLong / (riskLong / close)))
2. 修改警报体模板
直接引用全局变量替换原来的占位符:
{ "symbol": "{{ticker}}", "position": "{{strategy.order.action}}", "entry_price": "{{strategy.order.price}}", "leverage": "{{strategy.order.contracts}}", "stop_loss": "{{stopLossValue}}", "take_profit": "{{takeProfitValue}}", "timestamp": "{{timenow}}" }
这样触发警报时,stop_loss和take_profit字段就能正确获取到对应的数值了。
内容的提问来源于stack exchange,提问作者Umut Emre Önder
相关产品推荐
相关产品推荐

