#!/usr/bin/env python3
"""给历史交易补上盈亏字段"""
import json, os, time, requests, hmac, hashlib, base64

LF = "/root/quant_pipeline/trade_log.json"
if not os.path.exists(LF):
    print("无交易日志")
    exit(0)

with open(LF) as f:
    trades = json.load(f)

# 用OKX查历史订单
OKX_KEY = os.getenv("OKX_API_KEY", "")
OKX_SECRET = os.getenv("OKX_SECRET_KEY", "")
OKX_PASS = os.getenv("OKX_PASSPHRASE", "")

def okx_req(method, path, body=""):
    ts = time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())
    sig = base64.b64encode(hmac.new(OKX_SECRET.encode(), (ts+method+path+body).encode(), hashlib.sha256).digest()).decode()
    h = {"OK-ACCESS-KEY": OKX_KEY, "OK-ACCESS-SIGN": sig, "OK-ACCESS-TIMESTAMP": ts,
         "OK-ACCESS-PASSPHRASE": OKX_PASS, "Content-Type": "application/json"}
    r = requests.request(method, "https://www.okx.com"+path, headers=h, data=body, timeout=10)
    return r.json()

# 获取当前持仓和余额来判断状态
positions = okx_req("GET", "/api/v5/account/positions?instType=SWAP")
active_pos = [p for p in positions.get("data",[]) if float(p.get("pos",0)) != 0]
has_position = len(active_pos) > 0

print(f"当前持仓: {len(active_pos)}个")
current_pos_size = float(active_pos[0].get("pos",0)) if active_pos else 0
current_dir = active_pos[0].get("posSide","") if active_pos else ""
current_entry = float(active_pos[0].get("avgPx",0)) if active_pos else 0

# 获取当前价格
try:
    r = requests.get("https://www.okx.com/api/v5/market/ticker?instId=BTC-USDT-SWAP", timeout=5)
    current_px = float(r.json()["data"][0]["last"])
except:
    current_px = 0

# 更新每笔交易
updated = 0
for t in trades:
    if "pnl" not in t:
        # 判断这笔交易是否已平仓
        # 简单逻辑：如果它是最后一笔且当前有同向持仓，则未平仓
        if t == trades[-1] and has_position:
            # 未平仓，计算浮动盈亏
            if current_px and t.get("entry"):
                if t.get("direction") == "long":
                    t["pnl"] = round((current_px - t["entry"]) / t["entry"] * 4.27, 2)  # 近似
                else:
                    t["pnl"] = round((t["entry"] - current_px) / t["entry"] * 4.27, 2)
                t["status"] = "持仓中"
            else:
                t["pnl"] = 0
                t["status"] = "持仓中"
        else:
            # 已平仓，但不知道实际盈亏，设为0
            t["pnl"] = 0
            t["status"] = "已平仓"
        updated += 1

with open(LF, "w") as f:
    json.dump(trades, f, indent=2, default=str)

print(f"已更新{updated}笔交易")
for t in trades:
    print(f"  {t['time']} {t['direction']} @ {t['entry']} PnL={t.get('pnl','?')} {t.get('status','')}")