如何在Pine Script策略中绘制trail_price与trail_offset?
绘制追踪止损的trail_price与trail_offset对应价格
在Pine Script中,strategy.exit的内部追踪变量不会直接对外暴露,需要自己复刻止损逻辑来计算并绘制追踪价格。针对你设置的trail_price = close, trail_offset = 50(多单场景),具体实现如下:
核心逻辑说明
当持有多单时,追踪止损的规则是:
- 初始止损价为开仓时的
close - 50 - 后续价格上涨时,止损价会随价格同步上移(保持与最新收盘价50点的偏移);价格下跌时,止损价保持之前的最高值不变
完整代码示例
//@version=5 strategy("追踪止损绘制演示", overlay=true) // 示例开仓条件:5日均线上穿20日均线 if ta.crossover(ta.sma(close, 5), ta.sma(close, 20)) strategy.entry("Long", strategy.long) // 你的出场条件 strategy.exit("Long", trail_price = close, trail_offset = 50) // 计算并维护追踪止损价(对应trail_price - trail_offset) var float trailStopPrice = na if strategy.position_size > 0 // 开仓当日初始化止损价 if strategy.opentrades.entry_bar_index == bar_index trailStopPrice := close - 50 // 持仓期间更新止损价:取当前偏移价和历史最高止损价的最大值 else trailStopPrice := math.max(trailStopPrice, close - 50) else // 无持仓时重置变量 trailStopPrice := na // 绘制追踪止损价 plot(trailStopPrice, color=color.red, title="追踪止损价", linewidth=2) // 如果需要绘制trail_price本身(即追踪的基准收盘价) var float trailBasePrice = na if strategy.position_size > 0 if strategy.opentrades.entry_bar_index == bar_index trailBasePrice := close else trailBasePrice := math.max(trailBasePrice, close) else trailBasePrice := na plot(trailBasePrice, color=color.blue, title="追踪基准价(trail_price)", linewidth=2, style=plot.style_circles)
代码解释
var关键字确保变量仅在首次运行时初始化,避免每根K线重置- 持仓时通过
math.max保证止损价只上移、不下移,完全匹配strategy.exit的追踪逻辑 - 无持仓时将变量设为
na,避免绘制无效的线条
内容的提问来源于stack exchange,提问作者Mel
相关产品推荐
相关产品推荐

