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

Python使用def函数和条件语句判断连续红绿蜡烛输出交易信号

修改思路

要实现连续多根蜡烛的组合判定,需要调整原有的单根校验逻辑,核心修改点如下:

  • 调整颜色判断函数,简化返回值避免冗余操作
  • 一次性获取最近4根已闭合蜡烛的颜色做序列匹配
  • 新增数据量校验逻辑,避免索引越界报错

完整修改后代码

# 简化颜色判断函数,直接返回单根蜡烛的颜色字符串
def get_candle_color(open_price, close_price):
    if open_price > close_price:
        return "RED"
    elif open_price < close_price:
        return "GREEN"
    else:
        return "DOJI"

while True:
    time_iq = API.get_server_timestamp()
    # 保留原代码的时间判断逻辑不改动
    if int(dt.fromtimestamp(time_iq).second) == 59 or 1 > 0:
        data_candle = API.get_candles(pair, timeframe, 10, time_iq)
        # 先校验历史蜡烛数量足够,避免索引报错
        if len(data_candle) < 5:
            continue
        # 按从旧到新的顺序,取4根已闭合的蜡烛颜色(跳过当前未闭合的最后一根)
        c1 = get_candle_color(data_candle[-5]["open"], data_candle[-5]["close"])
        c2 = get_candle_color(data_candle[-4]["open"], data_candle[-4]["close"])
        c3 = get_candle_color(data_candle[-3]["open"], data_candle[-3]["close"])
        c4 = get_candle_color(data_candle[-2]["open"], data_candle[-2]["close"])
        
        # 匹配连续2红接2绿的卖出信号
        if c1 == "RED" and c2 == "RED" and c3 == "GREEN" and c4 == "GREEN":
            print("PLEASE SELL")
        # 匹配连续2绿接2红的买入信号,对应你要求的elif分支
        elif c1 == "GREEN" and c2 == "GREEN" and c3 == "RED" and c4 == "RED":
            print("PLEASE BUY")

补充说明

如果需要把十字星(DOJI)纳入某类蜡烛的判定范围,可以调整条件写法,比如允许十字星算红色的话,把c1 == "RED"改成c1 in ("RED", "DOJI")即可,其他位置同理修改。

内容的提问来源于stack exchange,提问作者Tevis L

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 22:24:02