TradingView中计算入场价与出场价间盈利百分比的方法
Pine Script 实现开平仓盈利百分比计算
你可以通过状态变量记录开仓价格,再结合平仓价格按比例换算,直接得到和平台内置工具效果一致的两位小数盈利百分比数值,不需要依赖内置持仓统计功能。
核心计算逻辑
- 多头持仓盈利百分比公式:
(平仓价 / 入场价 - 1) * 100,计算结果保留2位小数即可得到类似6.99格式的数值 - 用
var关键字定义持久化变量存储入场价、持仓状态,避免每根K线刷新重置数值
完整实现代码
把你已经定义好的开平仓条件代入即可直接使用:
// 已定义的开平仓条件 entryCond = k > 0 and d > 0 and k < d and bbr > 0 and macd > 0 and signal > 0 and macd > signal and mf < 30 and cci < 0 exitCond = k > d and k > 80 and d > 80 and bbr > 1 and mf > 80 and cci > 100 // 持久化存储状态,仅初始化时赋值一次 var entryPrice = na var isHolding = false // 开仓触发:空仓且满足开仓条件 if not isHolding and entryCond // 若按下根K线开盘价成交,可替换为对应周期的开盘价 entryPrice := close isHolding := true profitPercent = na // 平仓触发:持仓且满足平仓条件 if isHolding and exitCond exitPrice = close // 计算盈利百分比 profitPercent := (exitPrice / entryPrice - 1) * 100 // 平仓后重置状态 isHolding := false entryPrice := na // 输出两位小数格式的结果,可直接在数据窗口查看 plot(profitPercent, title="单笔盈利百分比", display=display.data_window) // 可选:在平仓K线上直接标注盈利数值 if not na(profitPercent) label.new(bar_index, high, str.tostring(profitPercent, "#.##") + "%", color = profitPercent > 0 ? color.green : color.red, style=label.style_label_down)
补充说明
- 如果你写的是
strategy类型脚本,无需自行维护持仓状态和入场价,直接调用内置属性strategy.opentrades[0].profit_percent即可获取当前持仓的实时盈利百分比,平仓时直接取值即可。 - 若后续需要支持空头持仓计算,将空头盈利公式替换为
(入场价 / 平仓价 - 1) * 100即可适配。 - 若要计算扣除手续费、滑点的净盈利,直接在最终结果中扣减对应成本比例即可。
内容的提问来源于stack exchange,提问作者David Buik
相关产品推荐
相关产品推荐

