Pine Script跨品种策略编写求助:实现VTV与VUG切换交易
Pine Script跨品种切换交易策略实现方案
一、修正原有指标代码
你代码里的longCondition引用了未定义的shorterSMA,需改为之前定义的shorterMA,同时为变量添加清晰后缀避免混淆,修正后指标代码如下:
// Create Indicators VTV_260SMA = request.security(symbol = "BATS:VTV", timeframe = "D", expression = ta.sma(close, 260)) VUG_10SMA = request.security(symbol = "BATS:VUG", timeframe = "D", expression = ta.sma(close, 10)) spy_10SMA = ta.sma(close, 10) // SPY的10日均线 spy_50SMA = ta.sma(close, 50) // SPY的50日均线 // Specify crossover conditions longVTVCondition = ta.crossover(spy_10SMA, spy_50SMA) // 定义做多VTV的触发条件 switchToVUGCondition = not longVTVCondition // 不满足VTV条件时切换到VUG
二、完整策略代码实现
Pine Script通过strategy.entry()指定交易标的,配合平仓指令实现跨品种切换,以下是可直接运行的完整策略:
//@version=5 strategy("VTV/VUG切换策略", overlay=false, initial_capital=10000, commission_type=strategy.commission.percent, commission_value=0.1, default_qty_type=strategy.cash, default_qty_value=10000) // 1. 获取各品种均线数据 VTV_260SMA = request.security(symbol = "BATS:VTV", timeframe = "D", expression = ta.sma(close, 260)) VUG_10SMA = request.security(symbol = "BATS:VUG", timeframe = "D", expression = ta.sma(close, 10)) spy_10SMA = ta.sma(close, 10) spy_50SMA = ta.sma(close, 50) // 2. 定义交易触发条件 longVTVCondition = ta.crossover(spy_10SMA, spy_50SMA) // 可替换为你实际需要的VTV做多条件 switchToVUGCondition = not longVTVCondition // 3. 平仓逻辑:切换品种前平掉当前持仓 if (longVTVCondition) strategy.close("VUG多单", comment="平VUG仓") else if (switchToVUGCondition) strategy.close("VTV多单", comment="平VTV仓") // 4. 开仓逻辑 if (longVTVCondition) strategy.entry("VTV多单", strategy.long, symbol="BATS:VTV", comment="开VTV多单") if (switchToVUGCondition) strategy.entry("VUG多单", strategy.long, symbol="BATS:VUG", comment="开VUG多单")
三、关键细节说明
- 标的指定:
strategy.entry()的symbol参数直接填入目标品种代码,即可对当前图表外的品种下单。 - 仓位标识:给每个仓位设置唯一ID(如"VTV多单"),确保精准平仓,避免误操作其他持仓。
- 条件互斥:通过
not逻辑保证切换条件互斥,避免同时持有两个品种的仓位。 - 参数配置:初始化时设置了初始资金、佣金比例、全额下单模式,可根据需求调整
default_qty_value改用固定手数下单。
四、注意事项
- 确保TradingView能获取到VTV、VUG的历史数据,否则策略测试会报错。
- 时间帧匹配:
request.security()使用日线数据,建议主图时间帧与之一致,或根据需求修改timeframe参数。 - 滑点模拟:可在
strategy()中添加slippage=strategy.slippage.fixed, slippage_value=0.1模拟实际交易滑点。
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

