如何为strategy.exit()添加含部分平仓的盈亏金额注释?
解决strategy.exit()平仓后添加盈亏注释的方案
直接利用Pine Script的strategy.closedtrades系列内置变量就能实现,无需手动判断平仓条件或仓位,不管是全仓还是部分平仓都能准确捕捉盈亏并添加注释。
实现思路
每次strategy.exit()触发平仓(包括部分平仓),都会在strategy.closedtrades中新增一条记录。我们可以通过追踪已平仓交易数量的变化,捕捉到每一次新的平仓事件,然后提取对应交易的盈亏数据,在图表上生成注释。
完整代码示例
//@version=5 strategy("Exit Profit Annotation Demo", overlay=true, default_qty_type=strategy.cash, default_qty_value=10000, commission_type=strategy.commission.percent, commission_value=0.1) // 定义变量记录上一次的已平仓交易数量 var int prev_closed_trades = 0 // 示例开仓条件(可替换为你的策略逻辑) long_condition = ta.crossover(ta.sma(close, 50), ta.sma(close, 200)) if (long_condition) strategy.entry("Long", strategy.long) // 设置止损止盈的exit strategy.exit("Exit Long", "Long", stop=close*0.95, limit=close*1.05) // 捕捉新的平仓事件并添加注释 if strategy.closedtrades > prev_closed_trades // 获取最新平仓交易的索引(从0开始,最新的是最后一条) latest_trade_idx = strategy.closedtrades - 1 // 提取该平仓的盈亏、发生K线、平仓价格 exit_profit = strategy.closedtrades.profit(latest_trade_idx) exit_bar = strategy.closedtrades.bar_index(latest_trade_idx) exit_price = strategy.closedtrades.exit_price(latest_trade_idx) // 在平仓价格下方创建注释,盈亏为正显示绿色,负则红色 label.new( bar_index=exit_bar, y=exit_price - ta.atr(14)*0.5, // 注释位置在平仓价下方半个ATR处,避免遮挡价格 text=str.tostring(exit_profit, "Exit Profit: $%.2f"), color=exit_profit > 0 ? color.new(color.green, 0) : color.new(color.red, 0), textcolor=color.white, style=label.style_label_up, size=size.small ) // 更新已平仓交易数量记录 prev_closed_trades := strategy.closedtrades
关键说明
strategy.closedtrades:返回当前已平仓的交易总数量,每完成一次平仓(包括部分平仓)就会+1,部分平仓会被拆分为多条独立的平仓记录,和策略测试器的交易列表对应。strategy.closedtrades.profit(idx):获取索引为idx的平仓交易的盈亏金额,包含手续费和滑点的计算结果。- 注释位置用
ta.atr(14)*0.5偏移,是为了让注释不会和价格K线或标记重叠,你可以根据需要调整偏移量。
内容的提问来源于stack exchange,提问作者Blu
相关产品推荐
相关产品推荐

