添加Strategy Entry时PineScript编译报错,求策略回测解决方案
解决[LAVA] Heiken Ashi Oscillator指标转策略的编译错误及策略实现
问题核心原因
原代码使用study()声明指标,但加入策略订单函数(strategy.order())会触发编译错误——TradingView PineScript中,指标(study)和策略(strategy)是两种不同的脚本类型,不能混用策略订单API。必须将study()替换为strategy()才能使用策略功能。此外原代码的信号条件逻辑不符合需求,需要调整为“信号从无到有”的切换触发入场,以及信号变色时平仓。
修正后的完整策略代码
// Tradingview.com Pinescript @author Ni6HTH4wK [LAVA] strategy(title="[LAVA] Heiken Ashi Oscillator Strategy", overlay=false, default_qty_type=strategy.cash, default_qty_value=10000, initial_capital=10000, commission_type=strategy.commission.percent, commission_value=0.1) // Inputs n1 = input(10, title="Multiplier", minval=1) n2 = input(42, title="RSI Length", minval=2) q1 = input(false, title="Show as RSI") // Sources hk_open = security(heikenashi(tickerid), tostring((interval*n1)), open) hk_stop = security(heikenashi(tickerid), tostring((interval*n1)), close) hk_local_open = na(hk_open[1])?open:(hk_open[1]+ohlc4[1])/2 hk_local_stop = ohlc4 // Source logic oc_hi = max(hk_local_open,hk_local_stop) oc_lo = min(hk_local_open,hk_local_stop) oc_dif = avg(oc_hi-oc_lo, high-low) dif_ema = ema(oc_dif, 14) std_dev = stdev(dif_ema, 20) // Heiken Ashi Logic hk_bull = hk_stop>hk_open?low>=hk_open?3*std_dev+hk_bull[1]:1*std_dev+hk_bull[1]:0 hk_bear = hk_open>hk_stop?high<=hk_open?3*std_dev+hk_bear[1]:1*std_dev+hk_bear[1]:0 // 信号切换条件(核心逻辑修正) bullSignal = hk_bull > 0 and hk_bull[1] <= 0 // 从无到有出现绿色信号(做多) bearSignal = hk_bear > 0 and hk_bear[1] <= 0 // 从无到有出现红色信号(做空) closeLongSignal = hk_bear > 0 // 红色信号出现,平多单 closeShortSignal = hk_bull > 0 // 绿色信号出现,平空单 // Heiken Ashi RSI hk_rsi = rsi(cum(hk_bull)-cum(hk_bear), 14) // Coloring hk_cci = cci(ohlc4, n2)>0 // Plotting plot(q1?na:hk_bull>0?hk_bull:na, title="Bullish Heiken Ashi", style=areabr, color=#339933, transp=50) plot(q1?na:hk_bear>0?hk_bear:na, title="Bearish Heiken Ashi", style=areabr, color=#ff0f0f, transp=50) plot(q1?hk_rsi:na, title="Heiken Ashi RSI", linewidth=2, color=hk_cci?#459915:#cf0023, transp=50) plot(q1?70:na, color=#222222) plot(q1?30:na, color=#222222) // 警报条件修正 alertcondition(bullSignal, title = "切换为绿色做多信号", message = "[LAVA] Heiken Ashi Oscillator 切换为绿色做多信号") alertcondition(bearSignal, title = "切换为红色做空信号", message = "[LAVA] Heiken Ashi Oscillator 切换为红色做空信号") // 策略订单逻辑 // 平多单 if (closeLongSignal) strategy.close(id="Enter Long") // 平空单 if (closeShortSignal) strategy.close(id="Enter Short") // 做多入场 if (bullSignal) strategy.entry(id="Enter Long", long=strategy.long) // 做空入场 if (bearSignal) strategy.entry(id="Enter Short", short=strategy.short)
关键修改说明
- 脚本类型切换:将
study()替换为strategy(),并配置了策略的资金、佣金等基础参数,确保能在策略测试器中运行。 - 信号逻辑修正:
- 入场信号改为信号从无到有的切换(
hk_bull>0且hk_bull[1]<=0),避免重复触发入场。 - 平仓信号设置为反向信号出现时触发(红色信号出现平多单,绿色信号出现平空单),符合“信号变色时平仓”的需求。
- 入场信号改为信号从无到有的切换(
- 订单函数优化:使用
strategy.entry()统一处理入场,strategy.close()处理平仓,逻辑更清晰,避免重复订单。 - 警报条件修正:同步调整警报触发条件为信号切换时刻,确保警报与策略入场时机一致。
内容的提问来源于stack exchange,提问作者Andry Hamida
相关产品推荐
相关产品推荐

