如何追踪并绘制空头开仓以来的最低价?代码异常排查求助
解决空头头寸开仓后最低价追踪问题
问题根源
你当前的空头追踪代码存在两个核心问题:
- 每次调用
math.min时都将short_entry_price纳入比较,导致价格回升至开仓价以上时,追踪值会被拉回开仓价,出现「从低点回升」的异常曲线 - 初始状态下
low_price_since_entry[1]为na,经nz()转换后变为0,直接让math.min返回0,出现平线
修正后的代码逻辑
正确的追踪逻辑应该是:
- 开仓瞬间,将追踪变量初始化至开仓价
- 开仓后,仅对比上一根K线的追踪最低价和当前K线的最低价,保留更小值
以下是修正后的完整代码:
// 假设已定义开仓条件与开仓价 var bool in_long = false var bool in_short = false var float long_entry_price = na var float short_entry_price = na // 示例开仓条件(可根据策略替换) long_condition = crossover(sma(close, 5), sma(close, 20)) short_condition = crossunder(sma(close, 5), sma(close, 20)) // 更新持仓状态与开仓价 if (long_condition) in_long := true long_entry_price := close if (short_condition) in_short := true short_entry_price := close if (strategy.exit("Exit Long")) // 替换为你的平仓条件 in_long := false if (strategy.exit("Exit Short")) // 替换为你的平仓条件 in_short := false // 多头:追踪开仓以来最高价 var float high_price_since_entry = na high_price_since_entry := in_long ? math.max(nz(high_price_since_entry[1], long_entry_price), high) : na // 空头:追踪开仓以来最低价 var float low_price_since_entry = na low_price_since_entry := in_short ? math.min(nz(low_price_since_entry[1], short_entry_price), low) : na // 绘图验证 plot(high_price_since_entry, color=color.green, title="Long High Since Entry") plot(low_price_since_entry, color=color.red, title="Short Low Since Entry") plot(long_entry_price, color=color.new(color.green, 50), title="Long Entry Price") plot(short_entry_price, color=color.new(color.red, 50), title="Short Entry Price")
关键修正点
- 用
in_short持仓状态判断是否更新追踪值,空仓时重置为na - 初始化时用
nz(low_price_since_entry[1], short_entry_price):第一次开仓时,low_price_since_entry[1]为na,直接取开仓价;后续则用上一根K线的追踪值 - 不再每次将
short_entry_price放入math.min参数,避免价格回升时拉回追踪值
追踪止损实现示例
如果要基于该最低价设置回撤止损(比如从最低价回升2%时平仓),可参考以下代码:
// 空头追踪止损:从最低价回升2%触发止损 stop_loss_pct = 2.0 short_stop_price = low_price_since_entry * (1 + stop_loss_pct / 100) // 触发止损条件 short_stop_condition = in_short and close >= short_stop_price if (short_stop_condition) strategy.close("Short", comment="Trailing Stop")
内容的提问来源于stack exchange,提问作者Olyboy
相关产品推荐
相关产品推荐

