#!/usr/bin/env python3
"""
持仓检查器 — 给格蕾丝AI交易用
输出：当前是否有持仓、盈亏、最新结构摘要
无持仓时输出 NO_POSITION（agent可据此静默跳过）
"""
import requests, hmac, base64, hashlib, json, os
import pandas as pd
from datetime import datetime, timezone, timedelta

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

def load_env(path='/root/.hermes/.env'):
    env = {}
    with open(path) as f:
        for line in f:
            line = line.strip()
            if line and '=' in line and not line.startswith('#'):
                k, v = line.split('=', 1)
                env[k.strip()] = v.strip().strip('"').strip("'")
    return env

env = load_env()
api_key = env['OKX_API_KEY']
secret = env['OKX_SECRET_KEY']
passphrase = env['OKX_PASSPHRASE']

base = "https://www.okx.com"

def okx_request(method, path, params=None, body=''):
    ts = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
    qs = ''
    if params:
        qs = '?' + '&'.join(f"{k}={v}" for k, v in params.items())
    full_path = path + qs
    msg = ts + method + full_path + body
    mac = hmac.new(secret.encode(), msg.encode(), hashlib.sha256)
    h = base64.b64encode(mac.digest()).decode()
    headers = {
        'OK-ACCESS-KEY': api_key,
        'OK-ACCESS-SIGN': h,
        'OK-ACCESS-TIMESTAMP': ts,
        'OK-ACCESS-PASSPHRASE': passphrase,
        'Content-Type': 'application/json'
    }
    resp = requests.request(method, base + full_path, headers=headers, data=body if body else None, timeout=15)
    return resp.json()

def get_candles(bar, limit=50):
    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 main():
    now = datetime.now(timezone(timedelta(hours=8)))
    # 查持仓
    r = okx_request('GET', '/api/v5/account/positions', params={'instId': INST})
    if r.get('code') != '0':
        print(f"ERROR: {r.get('msg')}")
        return

    positions = [p for p in r.get('data', []) if p.get('instId') == INST and float(p.get('pos', 0)) != 0]
    if not positions:
        print("NO_POSITION")
        return

    p = positions[0]
    side = "LONG" if p.get('posSide') == 'long' or float(p.get('pos')) > 0 else "SHORT"
    pos_size = abs(float(p.get('pos', 0)))
    avg_px = float(p.get('avgPx', 0))
    upl = float(p.get('upl', 0))
    upl_ratio = float(p.get('uplRatio', 0)) * 100
    lever = p.get('lever', '?')
    mark_px = float(p.get('markPx', 0))
    liq_px = p.get('liqPx', 'N/A')

    print(f"POSITION_ACTIVE")
    print(f"时间: {now.strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"方向: {side}")
    print(f"数量: {pos_size} 张 | 杠杆: {lever}x")
    print(f"开仓均价: {avg_px:.1f} | 标记价: {mark_px:.1f}")
    print(f"未实现盈亏: {upl:+.3f} USDT ({upl_ratio:+.2f}%)")
    print(f"强平价: {liq_px}")

    # 最近K线结构
    d1 = get_candles("1H", 12)
    d15 = get_candles("15m", 12)
    print(f"\n最近3根1H K线:")
    for ts, row in d1.tail(3).iterrows():
        d = "🟢" if row['c'] > row['o'] else "🔴"
        print(f"  {ts.strftime('%H:%M')} {d} 开{row['o']:.0f} 高{row['h']:.0f} 低{row['l']:.0f} 收{row['c']:.0f}")
    print(f"\n最近3根15m K线:")
    for ts, row in d15.tail(3).iterrows():
        d = "🟢" if row['c'] > row['o'] else "🔴"
        print(f"  {ts.strftime('%H:%M')} {d} 开{row['o']:.0f} 高{row['h']:.0f} 低{row['l']:.0f} 收{row['c']:.0f}")

    # 简单判断: 距离强平多远
    if liq_px != 'N/A':
        dist = abs(mark_px - float(liq_px)) / mark_px * 100
        print(f"\n距强平: {dist:.2f}%")

if __name__ == "__main__":
    main()
