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

Pine Script:如何获取自定义条件对应价格设置止损与止盈?

Pine Script 解决止损/入场价格获取问题

核心解决思路

问题本质是你只判断了入场/止损触发的布尔条件,但没在条件触发时捕获对应K线的价格。ta.valuewhen()是正确的方向,只要确保触发条件和价格捕获的时机匹配,就能拿到符合要求的float类型价格。

修改后的完整策略示例

//@version=5
strategy("Bull FVG 3:1 RR Strategy", overlay=true, default_qty_type=strategy.cash, default_qty_value=1000, commission_type=strategy.commission.percent, commission_value=0.1)

// 替换成你自己的BullFVG和入场交叉逻辑
bullFVG = ta.crossover(ta.sma(close, 5), ta.sma(close, 20)) 
bullEntryCross = bullFVG

// 替换成你依赖dist变量的止损计算逻辑
dist = ta.atr(14) * 0.5
bullStopLoss = ta.low - dist

// 捕获触发条件时的对应价格:0表示取最近一次触发的价格
bullEntryPrice = ta.valuewhen(bullEntryCross, close, 0)
bullStopLossPrice = ta.valuewhen(bullEntryCross, bullStopLoss, 0)

// 计算3:1风险回报比的止盈价
risk = bullEntryPrice - bullStopLossPrice
bullTakeProfitPrice = bullEntryPrice + risk * 3

// 发送限价多单并设置止损止盈
if (bullEntryCross)
    strategy.entry("Long", strategy.long, limit=bullEntryPrice)
    strategy.exit("Exit Long", "Long", stop=bullStopLossPrice, limit=bullTakeProfitPrice)

// 绘制辅助线
plot(bullStopLoss, color=color.red, title="Bull Stop Loss")
plot(bullTakeProfitPrice, color=color.green, title="Bull Take Profit")

关键要点说明

  • 价格捕获逻辑:ta.valuewhen(cond, source, occurrence)中occurrence=0会取最近一次条件触发时的source价格,确保拿到的是触发入场信号那根K线的对应价格,是标准float类型,满足订单函数的参数要求。
  • 止盈计算:先算出单笔交易的风险值(入场价-止损价),再乘以3加到入场价上,严格符合3:1的风险回报比要求。
  • 订单关联:用strategy.exit可以直接给入场单绑定止损和止盈,不用分开下单,Pine Script会自动关联对应订单,避免逻辑混乱。

如果你的bullStopLoss是随K线变动的动态值,ta.valuewhen会帮你固定住触发入场信号时的止损价,避免后续K线变动导致止损价漂移。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 03:07:15