#!/usr/bin/env python3
"""
交易监督器 — 每日检查交易纪律执行情况
用法：
  python3 trade_supervisor.py         # 检查今天执行情况
  python3 trade_supervisor.py --daily # 生成每日监督报告
"""
import requests, hmac, base64, hashlib, json, os, sys
from datetime import datetime, timezone, timedelta

TZ = timezone(timedelta(hours=8))

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 check_now():
    """实时检查：持仓、余额、杠杆"""
    now = datetime.now(TZ).strftime('%Y-%m-%d %H:%M:%S')
    print(f"=== 监督检查 {now} ===")
    
    # 余额
    r = okx_request('GET', '/api/v5/account/balance')
    if r.get('code') == '0':
        for d in r.get('data', []):
            for det in d.get('details', []):
                if det.get('ccy') == 'USDT':
                    eq = float(det.get('eq', 0))
                    print(f"余额: {eq:.4f} USDT")
    
    # 持仓
    r2 = okx_request('GET', '/api/v5/account/positions', params={'instId': 'BTC-USDT-SWAP'})
    positions = [p for p in r2.get('data', []) if p.get('instId') == 'BTC-USDT-SWAP' and float(p.get('pos', 0)) != 0]
    if positions:
        for p in positions:
            side = "多" if float(p.get('pos')) > 0 else "空"
            print(f"持仓: {side} | 数量={p.get('pos')} | 开仓均价={p.get('avgPx')} | 浮盈={p.get('upl')}U")
    else:
        print("持仓: 无")
    
    # 杠杆模式
    r3 = okx_request('GET', '/api/v5/account/leverage-info', params={'instId': 'BTC-USDT-SWAP', 'mgnMode': 'isolated'})
    if r3.get('code') == '0' and r3.get('data'):
        for d in r3['data']:
            print(f"杠杆: {d.get('lever')}x 逐仓")
    
    # 纪律检查
    print("\n=== 纪律检查 ===")
    # 检查今天订单数
    r4 = okx_request('GET', '/api/v5/trade/orders-history-archive', params={'instType': 'SWAP', 'instId': 'BTC-USDT-SWAP', 'limit': '10'})
    today = datetime.now(TZ).strftime('%Y-%m-%d')
    today_count = 0
    if r4.get('code') == '0':
        for o in r4.get('data', []):
            ts = datetime.fromtimestamp(int(o.get('uTime', 0))/1000, TZ).strftime('%Y-%m-%d')
            if ts == today:
                today_count += 1
    print(f"今日订单数: {today_count} (规则: ≤1笔主动单)")
    if today_count > 2:
        print("⚠️ 警告: 今日订单数异常！可能违反一天一笔纪律")

if __name__ == '__main__':
    check_now()
