如何在Pine策略中绘制每笔交易入场与离场的点数距离
实现方案
可以实现,直接使用Pine Script内置的策略交易相关函数即可完成数据获取、计算和绘制操作。
具体实现逻辑
- 核心是通过
strategy.closedtrades系列函数,获取每笔已平仓交易的入场价、离场价、入场K线索引、离场K线索引四个核心参数 - 距离计算逻辑:
- ticks距离公式:
abs(离场价 - 入场价) / syminfo.mintick,其中syminfo.mintick是标的的最小跳动单位,Pine Script会自动适配当前交易品种 - points距离可以直接用ticks结果乘以
syminfo.pointvalue换算得到
- ticks距离公式:
- 绘制可以用
line.new()连接入场和离场点位,用label.new()在离场位置展示计算好的距离数值
可直接运行的参考代码
//@version=5 strategy("交易点位距离标注示例", overlay=true, initial_capital=10000, default_qty_type=strategy.cash, default_qty_value=1000) // 示例策略逻辑:5周期和20周期均线交叉 fast_ma = ta.sma(close, 5) slow_ma = ta.sma(close, 20) if ta.crossover(fast_ma, slow_ma) strategy.entry("多单", strategy.long) if ta.crossunder(fast_ma, slow_ma) strategy.entry("空单", strategy.short) // 绘制每笔平仓交易的点位距离 if strategy.closedtrades > 0 last_trade_index = strategy.closedtrades - 1 entry_price = strategy.closedtrades.entry_price(last_trade_index) exit_price = strategy.closedtrades.exit_price(last_trade_index) entry_bar = strategy.closedtrades.entry_bar_index(last_trade_index) exit_bar = strategy.closedtrades.exit_bar_index(last_trade_index) // 计算距离 ticks_diff = math.abs(exit_price - entry_price) / syminfo.mintick points_diff = ticks_diff * syminfo.pointvalue // 绘制入场离场连接线 line.new(x1=entry_bar, y1=entry_price, x2=exit_bar, y2=exit_price, color=color.blue, width=2, style=line.style_dashed) // 绘制距离标签,盈利标绿亏损标红 label.new(x=exit_bar, y=exit_price, text=str.tostring(ticks_diff) + " ticks\n" + str.tostring(points_diff) + " points", color=exit_price > entry_price ? color.new(color.green, 90) : color.new(color.red, 90), textcolor=exit_price > entry_price ? color.green : color.red, style=label.style_label_down, size=size.small)
效果说明
- 虚线会直接连接对应交易的入场和离场点位,一一对应不会混淆
- 标签自动适配标的属性,股票、期货、外汇、加密货币等品种都可以正确计算距离
- 盈利和亏损交易用不同颜色区分,辨识度更高
内容的提问来源于stack exchange,提问作者Parabolic1
相关产品推荐
相关产品推荐

