TradingView Pine Script策略修复:实现条件持仓,避免逐K线开平仓
TradingView Pine Script 策略优化:实现单次开仓+持仓至平仓条件触发
原策略存在的问题:每根满足条件的K线都会重复执行开平仓操作,不符合「首次满足开仓条件时开仓,持仓直到平仓条件触发再平仓」的需求。
原代码
//@version=5 strategy("test", overlay = false, process_orders_on_close=true) // Input Period1 = input(7, title = "Period1") Period1 = input(14, title = "Period2") // 注:此处变量重复赋值,建议改为 Period2 = input(14, title = "Period2") // Calculate Stochastics stoch1 = ta.stoch(close, Period1) stoch2 = ta.stoch(close, Period2) // Variables var bool entered = false // Count positive/negative CCIs positiveStoch = (stoch1 > 0 ? 1 : 0) + (stoch2 > 0 ? 1 : 0) negativeStoch = (stoch1 < 0 ? 1 : 0) + (stoch2 < 0 ? 1 : 0) // Entry conditions entryLong = positiveStoch >= 2 entryShort = negativeStoch >= 2 // Exit condition exitLong = positiveStoch <= 1 exitShort = negativeStoch <= 1 // Variables var bool entered = false // Entry and exit logic if entryLong and not entered strategy.entry("Long", strategy.long) entered := true else if entryShort and not entered strategy.entry("Short", strategy.short) entered := true if (exitLong or exitShort) strategy.close("Long") strategy.close("Short") entered := false
优化核心思路
拆分多空持仓状态,分别用enteredLong和enteredShort跟踪多头、空头持仓情况:
- 开仓时,若当前持有反向仓位,先平仓再开新仓
- 平仓仅在对应持仓状态激活且满足平仓条件时执行,避免无持仓时误操作
- 确保仅在首次满足开仓条件时触发开仓,不会重复执行
修正后的代码
//@version=5 strategy("test", overlay = false, process_orders_on_close=true) // Input Period1 = input(7, title = "Period1") Period2 = input(14, title = "Period2") // 修正原代码变量重复赋值问题 // Calculate Stochastics stoch1 = ta.stoch(close, Period1) stoch2 = ta.stoch(close, Period2) // Count positive/negative CCIs positiveStoch = (stoch1 > 0 ? 1 : 0) + (stoch2 > 0 ? 1 : 0) negativeStoch = (stoch1 < 0 ? 1 : 0) + (stoch2 < 0 ? 1 : 0) // Entry conditions entryLong = positiveStoch >= 2 entryShort = negativeStoch >= 2 // Exit condition exitLong = positiveStoch <= 1 exitShort = negativeStoch <= 1 // Variables:分别跟踪多空持仓状态 var bool enteredLong = false var bool enteredShort = false // Entry and exit logic if entryLong and not enteredLong if enteredShort strategy.close("Short") enteredShort := false strategy.entry("Long", strategy.long) enteredLong := true if entryShort and not enteredShort if enteredLong strategy.close("Long") enteredLong := false strategy.entry("Short", strategy.short) enteredShort := true if enteredLong and exitLong strategy.close("Long") enteredLong := false if enteredShort and exitShort strategy.close("Short") enteredShort := false
内容的提问来源于stack exchange,提问作者Larry Cai
相关产品推荐
相关产品推荐

