You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pine Script如何在K线下方动态设置止损 基于入场K线高低点

Pine Script设置入场K线高低点为止损位的实现方法

核心单位转换逻辑

Pine Script中strategy.exit的loss参数确实要求传入以tick为单位的止损距离,和价格单位的差值不能直接混用,两者的换算依赖内置变量syminfo.mintick——即当前交易品种的最小价格变动单位,1个tick对应的价格波动幅度就是syminfo.mintick。
价格差值转ticks的通用公式为:
止损距离ticks = 价格差值 / syminfo.mintick

具体实现步骤

  • 固定记录入场K线的参考价格
    开仓条件触发时,立刻把当根K线的高点/低点存入持久化变量,避免后续K线变动时止损位跟着漂移:做多时记录当根K线的low作为止损参考价,做空时记录当根K线的high作为止损参考价,持仓平仓后将变量重置为空值即可。
  • 按持仓方向动态计算止损ticks值
    持有多单时,先计算入场均价和记录的入场K线低点的价格差,再除以最小变动价位得到对应ticks值;持有空单时,计算记录的入场K线高点和入场均价的价格差,同样换算为ticks值。计算时建议做取整、最小值兜底,避免传入非法数值导致策略报错。
  • 传入动态计算的止损参数
    将对应方向计算好的ticks值传入strategy.exit的loss参数,无对应方向持仓时传入na即可。

可运行代码示例

//@version=5
strategy("入场K线高低点止损策略", overlay=true, initial_capital=10000, default_qty_type=strategy.cash, default_qty_value=1000, commission_type=strategy.commission.percent, commission_value=0.1)

// 示例开仓条件:5周期均线上穿20周期均线做多,下穿做空
maFast = ta.sma(close, 5)
maSlow = ta.sma(close, 20)
longEntry = ta.crossover(maFast, maSlow)
shortEntry = ta.crossunder(maFast, maSlow)

// 持久化存储入场K线高低点
var float entryLow = na
var float entryHigh = na
if longEntry
    entryLow := low
    entryHigh := na
if shortEntry
    entryHigh := high
    entryLow := na
if strategy.position_size == 0
    entryLow := na
    entryHigh := na

// 动态计算各方向止损ticks
longLossTicks = na
shortLossTicks = na
if strategy.position_size > 0
    // 多单止损在入场K线低点,兜底最小1个tick防止报错
    priceGap = strategy.position_avg_price - entryLow
    longLossTicks := math.max(1, math.round(priceGap / syminfo.mintick))
if strategy.position_size < 0
    // 空单止损在入场K线高点
    priceGap = entryHigh - strategy.position_avg_price
    shortLossTicks := math.max(1, math.round(priceGap / syminfo.mintick))

// 开仓逻辑
if longEntry
    strategy.entry("开多", strategy.long)
if shortEntry
    strategy.entry("开空", strategy.short)

// 挂载动态止损
strategy.exit("平多", from_entry="开多", loss=longLossTicks)
strategy.exit("平空", from_entry="开空", loss=shortLossTicks)

// 绘图辅助查看
plot(maFast, color=color.blue, title="快均线")
plot(maSlow, color=color.orange, title="慢均线")
plot(strategy.position_size > 0 ? entryLow : na, color=color.red, style=plot.style_linebr, linewidth=2, title="多单止损线")
plot(strategy.position_size < 0 ? entryHigh : na, color=color.green, style=plot.style_linebr, linewidth=2, title="空单止损线")

注意事项

  • 不要用low[1]/high[1]这类偏移取值的方式获取入场K线价格,如果开仓信号和止损触发在同一根K线,偏移取值会拿到错误的K线价格,导致回测结果失真。
  • 如果需要给止损加缓冲空间(比如多单止损比入场K线低点再低2个tick,避免假突破扫损),直接在价格差计算时加上对应缓冲的价格值即可,比如多单价格差写为strategy.position_avg_price - entryLow + 2 * syminfo.mintick,换算后会自动包含缓冲距离。
  • 不要在持仓过程中更新记录的入场K线高低点,否则止损位会跟随新K线变动,达不到固定在入场K线位置止损的效果。

内容的提问来源于stack exchange,提问作者Bishnu Paudel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 14:27:18