如何获取特定未平仓交易的浮动盈利(而非全部未平仓交易总和)
获取特定未平仓交易的浮动盈利
在Pine Script中,strategy.openprofit确实会返回所有未平仓订单的浮动盈利总和,无法直接获取单笔订单的盈利。但你可以通过手动追踪每笔开仓的关键信息来实现这个需求,具体步骤如下:
实现思路
- 用数组存储每笔开仓的价格、方向和持仓量
- 开仓时将对应数据写入数组
- 实时根据当前价格计算单笔订单的浮动盈利
- 平仓时按FIFO规则移除数组中对应元素
完整代码示例
//@version=5 strategy("单笔浮动盈利追踪", overlay=true, pyramiding=2, default_qty_type=strategy.cash, close_entries_rule=strategy.close_entries_rule.fifo) // 定义存储开仓信息的数组:每个元素是[开仓价格, 持仓方向(1=多, -1=空), 持仓量] var float[] entryPrices = array.new_float() var int[] entryDirs = array.new_int() var float[] entrySizes = array.new_float() // 示例开仓条件(可替换为你的实际开仓逻辑) longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28)) if (longCondition) strategy.entry("Long", strategy.long) // 记录开仓信息 array.push(entryPrices, strategy.entry_price) array.push(entryDirs, 1) array.push(entrySizes, strategy.position_size) shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28)) if (shortCondition) strategy.entry("Short", strategy.short) // 记录开仓信息 array.push(entryPrices, strategy.entry_price) array.push(entryDirs, -1) array.push(entrySizes, strategy.position_size) // 计算单笔浮动盈利的函数 getSingleOpenProfit(index) => if array.size(entryPrices) > index entryPrice = array.get(entryPrices, index) dir = array.get(entryDirs, index) size = array.get(entrySizes, index) // 根据方向计算盈利:多单=当前价-开仓价,空单=开仓价-当前价 profitPerShare = dir == 1 ? (close - entryPrice) : (entryPrice - close) totalProfit = profitPerShare * size totalProfit else na // 获取第一笔未平仓单的盈利(FIFO下最早开的单) firstProfit = getSingleOpenProfit(0) // 获取第二笔未平仓单的盈利 secondProfit = getSingleOpenProfit(1) // 你的原有逻辑修改:使用单笔盈利判断 var bool profit45 = false if firstProfit > 45 or secondProfit > 45 profit45 := true if profit45 and (firstProfit < 20 or secondProfit < 20) strategy.close("Short", comment="Close Long") profit45 := false // 平仓时移除对应开仓记录(FIFO规则,平最早开的单) if strategy.closedtrades > 0 // 每次平仓移除数组第一个元素 array.shift(entryPrices) array.shift(entryDirs) array.shift(entrySizes) // 可选:在图表上显示单笔盈利 plot(firstProfit, color=color.green, title="第一笔浮动盈利") plot(secondProfit, color=color.red, title="第二笔浮动盈利")
关键说明
- 数组
entryPrices、entryDirs、entrySizes分别存储每笔开仓的价格、方向和持仓量 - 函数
getSingleOpenProfit(index)通过索引获取对应笔数的浮动盈利,索引0对应最早开的单(FIFO规则下优先平仓的单) - 平仓时通过
array.shift()移除数组第一个元素,保证数组始终对应当前未平仓订单
内容的提问来源于stack exchange,提问作者ManouSeven
相关产品推荐
相关产品推荐

