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

如何识别K线颜色?求3根红K后做多的Pine Script编写指导

Pine Script 策略逻辑修正指导

原代码的核心问题

  1. 红绿K线判断错误:你用open > open[1]识别绿K是不准确的,标准红绿K的判断基于当前K线的开盘价与收盘价:
    • 红K:close < open(收盘价低于开盘价)
    • 绿K:close > open(收盘价高于开盘价)
  2. 连续红K检测逻辑错误:open[3] > open[2] and open[2] > open[1]仅判断开盘价递减,和K线是否为红色无关,无法正确识别连续红K。
  3. 未覆盖红K延续场景:原代码只检查固定3根红K,没考虑4根、5根连续红K后出现绿K的情况,不符合“至少3根红K后等绿K开多”的需求。

正确逻辑构建步骤

  1. 定义标准的红绿K线判断条件
  2. 检测是否出现过至少3根连续红K的状态(包括红K持续延续的情况)
  3. 当连续红K状态成立后,在第一根绿K出现时执行开多

修正后的完整代码

//@version=5
strategy("连续红K后绿K开多", overlay=true, default_qty_type=strategy.cash, default_qty_value=10000, commission_type=strategy.commission.percent, commission_value=0.1)

// 定义红绿K线
isRedCandle = close < open
isGreenCandle = close > open

// 检测是否出现至少3根连续红K(包含红K延续的情况)
hasAtLeast3Red = ta.barssince(not isRedCandle) >= 3 or (ta.barssince(not isRedCandle) == -1 and ta.barssince(isRedCandle) >= 2)

// 开多条件:满足至少3根红K,且当前是绿K
longCondition = hasAtLeast3Red and isGreenCandle

// 执行开多(可添加持仓判断避免重复开仓)
if (longCondition and strategy.position_size == 0)
    strategy.entry("Long", strategy.long, 100)

代码逻辑解释

  • isRedCandle/isGreenCandle:用当前K线的收盘价与开盘价对比,确保红绿K判断的准确性。
  • hasAtLeast3Red:
    • ta.barssince(not isRedCandle) >=3:距离上一根非红K已过3根及以上K线,说明当前已连续3根或更多红K。
    • ta.barssince(not isRedCandle) == -1:表示回溯至今所有K线都是红K,且数量≥3(ta.barssince(isRedCandle)>=2)。
  • 开多条件中加入strategy.position_size == 0,避免在已有持仓时重复开仓,符合交易逻辑。

额外优化建议

  • 可添加止损止盈规则,比如固定点数止损或移动止损,降低单一开多逻辑的风险。
  • 若需更严格的连续红K判断(比如必须是连续的,中间不能有非红K),可调整hasAtLeast3Red的逻辑为isRedCandle[2] and isRedCandle[1] and isRedCandle,但这仅针对连续3根红K的场景,不包含红K延续的情况。

内容的提问来源于stack exchange,提问作者black panther

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 09:10:37