TradingView SMA交叉策略Pine Script v5回测无结果求助
Pine Script v5均线交叉多头策略无回测结果排查
问题原因
- 平仓订单ID不匹配:你调用
strategy.entry()创建的多头订单ID为buy,但平仓时strategy.close()指定关闭ID为sell的订单,系统无法找到对应持仓,无法完成平仓逻辑。 - 限价单无法成交:入场逻辑设置
limit=close[1],以上一根K线收盘价作为挂单价,若当前K线价格高于该值,限价单不会成交,绝大多数行情下都无法成功开仓。 - 止盈计算空值异常:空仓时
strategy.position_avg_price返回空值na,计算出的longTakeProfit也为空,导致平仓判断逻辑失效。 - 若回测标的在所选时间区间内不满足
ma2>ma3 and ma3>ma4的多头排列条件,也不会触发入场信号。
修正后代码
//@version=5 strategy(shorttitle='Long on MA Crossover',title='Long Strategy with MA Crossover', overlay=true, initial_capital = 20000, currency = currency.USD, process_orders_on_close=true, default_qty_type = strategy.cash, default_qty_value = 20000, commission_type=strategy.commission.percent, commission_value=0.075) //Backtest dates fromMonth = input.int(defval = 1, title = "From Month", minval = 1, maxval = 12) fromDay = input.int(defval = 1, title = "From Day", minval = 1, maxval = 31) fromYear = input.int(defval = 2019, title = "From Year", minval = 1970) thruMonth = input.int(defval = 1, title = "Thru Month", minval = 1, maxval = 12) thruDay = input.int(defval = 1, title = "Thru Day", minval = 1, maxval = 31) thruYear = input.int(defval = 2112, title = "Thru Year", minval = 1970) showDate = input.bool(defval = true, title = "Show Date Range") start = timestamp(fromYear, fromMonth, fromDay, 00, 00) // backtest start window finish = timestamp(thruYear, thruMonth, thruDay, 23, 59) // backtest finish window window() => time >= start and time <= finish ? true : false // create function "within window of time" len1 = input.int(9, minval=1, title="MA1") len2 = input.int(50, minval=1, title="MA2") len3 = input.int(100, minval=1, title="MA3") len4 = input.int(200, minval=1, title="MA4") ma1 = ta.sma(close, len1) ma2 = ta.sma(close, len2) ma3 = ta.sma(close, len3) ma4 = ta.sma(close, len4) Take_profit= ((input (3))/100) // 持仓时才计算止盈价 longTakeProfit = strategy.position_size > 0 ? strategy.position_avg_price * (1 + Take_profit) : na closeLong = (strategy.position_size > 0 and close > longTakeProfit) or ta.crossover(ma2,ma1) //Entry 移除limit参数改为市价成交,或根据需求调整限价逻辑 strategy.entry("buy", strategy.long, when = ta.crossover(ma1,ma2) and ma2 > ma3 and ma3 > ma4 and window()) //Exit 修正平仓订单ID为buy strategy.close("buy", when = closeLong and window())
内容的提问来源于stack exchange,提问作者Sunil Doddapaneni
相关产品推荐
相关产品推荐

