如何实现单根K线平仓后等待下一根K线开仓?代码问题求助
问题分析与修复方案
核心问题
你的脚本持续跳过K线的主要原因是入场条件过于严苛:你要求必须在退出后的下一根精确K线(bar_index == last_exit_bar_idx + 1)执行入场,一旦该K线不满足inDateRange或者其他隐性条件,后续K线就永远无法触发入场——因为bar_index会持续递增,再也不会等于last_exit_bar_idx + 1,而enter_next_long/short的标记还一直处于激活状态,却没有机会被触发。
另外还有一个语法错误:在enter_next_long的入场代码块里,strategy.entry语句没有对齐,会导致逻辑异常。
修复后的代码
// Variables to track trade logic var int last_exit_bar_idx = na var bool enter_next_long = false var bool enter_next_short = false // Exit logic and prepare for next-bar entry if inDateRange if strategy.position_size > 0 // Currently in a long position if bearish strategy.close("long", comment="exit long") last_exit_bar_idx := bar_index enter_next_short := true enter_next_long := false if strategy.position_size < 0 // Currently in a short position if bullish strategy.close("short", comment="exit short") last_exit_bar_idx := bar_index enter_next_long := true enter_next_short := false // Enter positions after exit (relaxed condition) if inDateRange and strategy.position_size == 0 if enter_next_short and bar_index >= last_exit_bar_idx + 1 strategy.entry("short", strategy.short, comment="enter short") enter_next_short := false last_exit_bar_idx := na // 修复语法缩进问题 if enter_next_long and bar_index >= last_exit_bar_idx + 1 strategy.entry("long", strategy.long, comment="enter long") enter_next_long := false last_exit_bar_idx := na // Handle initial trades when no exits exist if inDateRange and na(last_exit_bar_idx) and strategy.position_size == 0 if bullish strategy.entry("long", strategy.long, comment="first long") last_exit_bar_idx := bar_index if bearish strategy.entry("short", strategy.short, comment="first short") last_exit_bar_idx := bar_index
关键修改点
- 将入场条件的
bar_index == last_exit_bar_idx + 1改为bar_index >= last_exit_bar_idx + 1:允许在退出后的任意后续符合条件的K线入场,不再限制必须是下一根K线。 - 修复了
enter_next_long代码块的缩进错误:确保strategy.entry和后续变量重置语句都在条件判断的范围内。
额外优化建议
如果bullish和bearish信号可能同时触发(比如震荡行情中),初始入场部分可以用else if替代第二个if,避免同时开多空仓的风险:
// Handle initial trades when no exits exist if inDateRange and na(last_exit_bar_idx) and strategy.position_size == 0 if bullish strategy.entry("long", strategy.long, comment="first long") last_exit_bar_idx := bar_index else if bearish strategy.entry("short", strategy.short, comment="first short") last_exit_bar_idx := bar_index
内容的提问来源于stack exchange,提问作者Maghal
相关产品推荐
相关产品推荐

