You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TradingView策略编译通过入场条件触发但回测无交易问题求助

TradingView策略无入场交易记录的问题原因及修复方案

核心问题排查

  • 平仓指令ID不匹配:strategy.close()的第一个参数必须和开仓时strategy.entry()设置的订单ID完全一致,你开仓ID是long,但止损、止盈指令里写的是stop loss、take profit,系统找不到对应持仓,指令执行异常会干扰策略正常运行。
  • 保证金参数设置错误:margin_long参数代表开仓所需保证金占订单价值的百分比,你设置为500相当于开仓需要5倍于订单价值的保证金,初始资金仅100、默认开100%仓位的情况下完全不符合开仓资金要求,自然无法下单。如果是要加杠杆,比如2倍杠杆对应margin_long=50,10倍杠杆对应margin_long=10。
  • 止损逻辑错误且无持仓判断:strategy.opentrades.profit(0)返回的是持仓利润的金额,你直接和-0.02*strategy.opentrades.size(0)对比,单位不匹配逻辑完全无效;同时空仓状态下调用strategy.opentrades系列属性会抛出运行时错误,导致策略逻辑中断,无法触发开仓指令。
  • 止盈逻辑无持仓判断:和止损问题一样,空仓时调用strategy.opentrades.max_runup会触发错误,中断策略运行。

修正后的完整代码

strategy("Good news", overlay=true, margin_long=10, margin_short=10, initial_capital=100, calc_on_order_fills=true, calc_on_every_tick=true, default_qty_type = strategy.percent_of_equity, default_qty_value = 100)

periods = 144
multip = 5
volthreshMA = multip*ta.sma(volume[1], periods)

longCondition = (volume > volthreshMA and close > open)
if (longCondition)
    strategy.entry("long", strategy.long)
    
// 有持仓时才执行平仓逻辑
if strategy.opentrades > 0
    //2% stop loss 修正为按持仓成本计算亏损比例
    stopCondition = strategy.opentrades.profit(0) < (-0.02 * strategy.opentrades.entry_price(0) * strategy.opentrades.size(0))
    if (stopCondition)
        strategy.close("long", comment="stop loss")

    //take profit when profit is 80% of max profit during trade 新增max_runup为0的判断避免除0错误
    if strategy.opentrades.max_runup(0) > 0
        takeprofitCondition = ((strategy.opentrades.max_runup(0) - strategy.opentrades.profit (0))/strategy.opentrades.max_runup(0)) > 0.2
        if (takeprofitCondition)
            strategy.close("long", comment="take profit")

额外验证建议

如果修正后还是没有触发开仓,可以在代码末尾叠加以下逻辑,直观确认longCondition是否真的触发:

plotshape(longCondition, title="多单信号", location=location.belowbar, color=color.green, style=shape.labelup, text="多")

内容的提问来源于stack exchange,提问作者Kaspar Hidayat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 03:36:03