#!/usr/bin/env python3
"""
火币K线监控分析脚本
过滤型连续上涨策略
"""
import json
import time
from datetime import datetime

# 评级系统
def get_grade(consecutive_count):
    """根据连续上涨数量返回评级"""
    if consecutive_count >= 13:
        return "SS级"
    elif consecutive_count >= 11:
        return "S级"
    elif consecutive_count >= 9:
        return "A级"
    elif consecutive_count >= 7:
        return "B级"
    elif consecutive_count >= 5:
        return "C级"
    elif consecutive_count >= 3:
        return "D级"
    else:
        return None  # 不够评级

# 过滤型连续上涨分析
def analyze_filtered_consecutive_up(klines, max_reverse=2, small_reverse_threshold=0.3):
    """
    过滤型连续上涨分析
    
    参数:
    - klines: K线数据列表（按时间倒序，最新在前）
    - max_reverse: 允许的最大连续反向K线数量（默认2）
    - small_reverse_threshold: 小幅回调阈值（默认0.3，即30%）
    
    返回:
    - (连续上涨数量, 净涨幅, K线序列符号列表)
    """
    if len(klines) < 3:
        return 0, 0.0, []
    
    # 计算每根K线的涨跌幅和方向
    candle_changes = []
    for i, k in enumerate(klines):
        open_price = k['open']
        close_price = k['close']
        change_pct = (close_price - open_price) / open_price * 100
        direction = 'up' if close_price > open_price else ('down' if close_price < open_price else 'neutral')
        candle_changes.append({
            'index': i,
            'open': open_price,
            'close': close_price,
            'change_pct': change_pct,
            'direction': direction
        })
    
    # 寻找连续上涨序列
    max_consecutive = 0
    best_sequence = None
    best_up_gains = 0
    best_down_losses = 0
    
    # 从最新K线开始往前找
    for start_idx in range(len(candle_changes)):
        if candle_changes[start_idx]['direction'] != 'up':
            continue
            
        consecutive_up = 0
        reverse_count = 0
        total_up_gains = 0
        total_down_losses = 0
        sequence = []
        sequence_indices = []
        
        for i in range(start_idx, len(candle_changes)):
            candle = candle_changes[i]
            if candle['direction'] == 'up':
                consecutive_up += 1
                reverse_count = 0  # 重置反向计数
                total_up_gains += candle['change_pct']
                sequence.append('🔺')
                sequence_indices.append(i)
            elif candle['direction'] == 'down':
                # 检查是否是小幅回调
                if total_up_gains > 0:
                    # 计算这根下跌相对于已获得涨幅的比例
                    if total_up_gains > 0:
                        ratio = abs(candle['change_pct']) / total_up_gains
                        if ratio < small_reverse_threshold:
                            # 忽略小幅回调
                            continue
                
                reverse_count += 1
                if reverse_count > max_reverse:
                    break  # 连续反向K线太多，终止
                total_down_losses += abs(candle['change_pct'])
                sequence.append('⬇️')
                sequence_indices.append(i)
            # neutral 忽略
        
        # 更新最佳序列
        if consecutive_up > max_consecutive:
            max_consecutive = consecutive_up
            best_sequence = sequence.copy()
            best_up_gains = total_up_gains
            best_down_losses = total_down_losses
        
        # 如果已经找到足够长的序列，可以提前终止
        if max_consecutive >= 10:
            break
    
    # 计算净涨幅
    net_gain = best_up_gains - best_down_losses
    
    return max_consecutive, net_gain, best_sequence if best_sequence else []

# 主分析函数
def analyze_symbol(symbol, period, klines_data):
    """分析单个币种和周期"""
    result = {
        'symbol': symbol,
        'period': period,
        'current_price': klines_data[0]['close'] if klines_data else 0,
        'analysis': None
    }
    
    consecutive_count, net_gain, sequence = analyze_filtered_consecutive_up(klines_data)
    
    if consecutive_count >= 3:
        grade = get_grade(consecutive_count)
        if grade:
            result['analysis'] = {
                'consecutive_count': consecutive_count,
                'net_gain': net_gain,
                'grade': grade,
                'sequence': sequence
            }
    
    return result

# 解析API响应
def parse_kline_response(json_str):
    """解析火币API响应"""
    data = json.loads(json_str)
    return data.get('data', [])

# 示例调用
if __name__ == '__main__':
    # 这里可以添加测试代码
    pass
