#!/usr/bin/env python3
"""
格蕾丝 AI交易 — 数据采集器
================================
只负责拉数据给AI看，不做任何决策。
AI（格蕾丝）拿到这些数据后，自己判断做不做、做什么方向。
"""
import requests, json, sys
import pandas as pd
import numpy as np
from datetime import datetime, timezone, timedelta

BASE = "https://www.okx.com"
INST = "BTC-USDT-SWAP"

def get_candles(bar, limit=200):
    r = requests.get(f"{BASE}/api/v5/market/candles?instId={INST}&bar={bar}&limit={limit}", timeout=15)
    data = r.json()["data"]
    df = pd.DataFrame(data, columns=["ts","o","h","l","c","vol","_","_","_"])
    for col in ["o","h","l","c","vol"]:
        df[col] = df[col].astype(float)
    df["ts"] = pd.to_datetime(df["ts"].astype(int), unit="ms")
    return df.set_index("ts").iloc[::-1].sort_index()

def atr(df, n=14):
    h, l, c = df["h"], df["l"], df["c"]
    tr = pd.concat([h-l, (h-c.shift()).abs(), (l-c.shift()).abs()], axis=1).max(axis=1)
    return tr.rolling(n).mean().iloc[-1]

def swing_points(df, n=3):
    highs, lows = [], []
    for i in range(n, len(df)-n):
        if df["h"].iloc[i] == df["h"].iloc[i-n:i+n+1].max():
            highs.append((df.index[i], df["h"].iloc[i]))
        if df["l"].iloc[i] == df["l"].iloc[i-n:i+n+1].min():
            lows.append((df.index[i], df["l"].iloc[i]))
    return highs, lows

def fmt_time(ts):
    return ts.strftime("%m-%d %H:%M")

def main():
    now = datetime.now(timezone(timedelta(hours=8)))
    print(f"🕐 北京时间: {now.strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"📊 分析标的: {INST}\n")

    d1 = get_candles("1H", 100)
    d4 = get_candles("4H", 60)
    d15 = get_candles("15m", 100)
    dd = get_candles("1D", 60)

    # ===== 日线 =====
    dd["ma20"] = dd["c"].rolling(20).mean()
    dd["ma50"] = dd["c"].rolling(50).mean()
    last = dd.iloc[-1]
    print("═══ 日线级别 ═══")
    print(f"收盘: {last['c']:.0f} | MA20: {dd['ma20'].iloc[-1]:.0f} | MA50: {dd['ma50'].iloc[-1]:.0f}")
    print(f"趋势: {'多头' if last['c'] > dd['ma20'].iloc[-1] else '空头'} (c vs MA20)")
    print(f"近20日最高: {dd['h'].tail(20).max():.0f} | 最低: {dd['l'].tail(20).min():.0f}")
    print(f"今日: 开{last['o']:.0f} 高{last['h']:.0f} 低{last['l']:.0f} 收{last['c']:.0f}")

    # ===== 4H =====
    d4["ma20"] = d4["c"].rolling(20).mean()
    print("\n═══ 4小时级别 ═══")
    print(f"收盘: {d4['c'].iloc[-1]:.0f} | MA20: {d4['ma20'].iloc[-1]:.0f}")
    print(f"趋势: {'多头' if d4['c'].iloc[-1] > d4['ma20'].iloc[-1] else '空头'}")
    h4_highs, h4_lows = swing_points(d4, 2)
    if h4_highs: print(f"最近摆动高点: {fmt_time(h4_highs[-1][0])} @ {h4_highs[-1][1]:.0f}")
    if h4_lows: print(f"最近摆动低点: {fmt_time(h4_lows[-1][0])} @ {h4_lows[-1][1]:.0f}")

    # ===== 1H =====
    print("\n═══ 1小时级别 ═══")
    print(f"收盘: {d1['c'].iloc[-1]:.0f}")
    print(f"ATR(14): {atr(d1):.0f} ({atr(d1)/d1['c'].iloc[-1]*100:.2f}%)")
    h1_highs, h1_lows = swing_points(d1, 3)
    if h1_highs:
        print(f"最近3根K线的摆动高点:")
        for ts, px in h1_highs[-3:]: print(f"  {fmt_time(ts)} @ {px:.0f}")
    if h1_lows:
        print(f"最近3根K线的摆动低点:")
        for ts, px in h1_lows[-3:]: print(f"  {fmt_time(ts)} @ {px:.0f}")

    # ===== 15m =====
    print("\n═══ 15分钟级别 ═══")
    print(f"收盘: {d15['c'].iloc[-1]:.0f}")
    print(f"ATR(14): {atr(d15):.0f} ({atr(d15)/d15['c'].iloc[-1]*100:.3f}%)")
    # 最近5根15m K线
    print("最近5根15m K线:")
    for ts, row in d15.tail(5).iterrows():
        direction = "🟢" if row['c'] > row['o'] else "🔴"
        vol_ratio = row['vol'] / d15['vol'].tail(20).mean()
        print(f"  {fmt_time(ts)} {direction} 开{row['o']:.0f} 高{row['h']:.0f} 低{row['l']:.0f} 收{row['c']:.0f} 量比{vol_ratio:.1f}x")

    # ===== 关键位 =====
    print("\n═══ 关键价位 ═══")
    px = d15['c'].iloc[-1]
    recent_high = max(d15['h'].tail(48).max(), d1['h'].tail(24).max())
    recent_low = min(d15['l'].tail(48).min(), d1['l'].tail(24).min())
    print(f"当前价: {px:.0f}")
    print(f"近2日高: {recent_high:.0f} | 近2日低: {recent_low:.0f}")
    range_pct = (recent_high - recent_low) / recent_low * 100
    print(f"区间幅度: {range_pct:.1f}%")
    if recent_low > 0:
        mid = (recent_high + recent_low) / 2
        pos = (px - recent_low) / (recent_high - recent_low) * 100
        print(f"当前在区间位置: {pos:.0f}% (0%=低, 50%=中, 100%=高)")

    print("\n📝 数据采集完成，交给格蕾丝分析。")

if __name__ == "__main__":
    main()
