如何仅使用策略入场后的K线数据计算指标并触发交易信号
实现方案
可以实现该需求,核心是自定义可重置的均值计算逻辑,不要使用Pine Script内置的全局sma函数。
原有代码问题说明
- 变量
y的赋值逻辑错误,仅在持仓满x根的单根K线赋值为x,其余时间都是0,内置sma接收到长度为0时输出异常,无法得到正确结果 - Pine Script内置的
sma()函数基于全量历史K线计算,不会在每次开仓时自动重置计算起点,无法满足仅用开仓后K线计算的要求
完整修复代码
//@version=5 strategy("持仓后计算MA测试", overlay=true) open_long = strategy.position_size > 0 open_short = strategy.position_size < 0 //Entry MA's fast_ma = ta.sma(close,10) slow_ma = ta.sma(close,20) ma_long = ta.crossover(fast_ma ,slow_ma) ma_short = ta.crossover(slow_ma ,fast_ma) //EntryRSI rsi = ta.rsi(close,14) rsi_long = rsi[1] > 50 rsi_short = rsi[1] < 50 //Exit RSI exit_long = ta.crossunder(rsi,50) exit_short = ta.crossover(rsi,50) //strategy if ma_long and rsi_long strategy.entry("Long", strategy.long) if ma_short and rsi_short strategy.entry("Short", strategy.short) if open_long and exit_long strategy.close("Long") if open_short and exit_short strategy.close("Short") // 修复后的自定义MA计算逻辑 x = input.int(10, "Variable Length", minval=1) // 声明持久化变量存储累计收盘价和持仓K线计数 var float sum_close = na var int bar_count = na // 开仓触发时重置变量 if ta.change(strategy.position_size) != 0 and strategy.position_size != 0 sum_close := 0 bar_count := 0 // 持仓状态下累计数据 if strategy.position_size != 0 sum_close := sum_close + close bar_count := bar_count + 1 // 仅持仓且满x根K线时输出MA值,否则输出na不显示 var_ma = na if strategy.position_size != 0 and bar_count >= x var_ma := sum_close / bar_count plot(var_ma, color=color.new(color.blue, 0), linewidth=2)
逻辑说明
- 每次新开仓时都会重置累计值和计数,保证只统计本次开仓后的K线数据
- 持仓不足x根K线时返回
na,图表上不会显示,平仓后也会自动返回na不再显示 - 计算得到的
var_ma可以直接用于后续的仓位调整判断逻辑,和普通指标用法完全一致
内容的提问来源于stack exchange,提问作者J Smith
相关产品推荐
相关产品推荐

