import json
import websocket
import ssl
import threading
import time
import hmac
import hashlib
import base64
import uuid  # 用于生成唯一订单 ID

# OKX 私有 WebSocket URL
OKX_WS_URL = "wss://ws.okx.com:8443/ws/v5/private"

# API 认证信息
API_KEY = "4a4d18ed-f671-4a26-92cb-c34388407d41"
SECRET_KEY = "A209BB83BEBC32727E3E807E43310554"
PASSPHRASE = "@89687828cC"

# 生成 OKX API 认证签名
def generate_signature(timestamp, method, request_path, body):
    message = f"{timestamp}{method}{request_path}{body}"
    mac = hmac.new(SECRET_KEY.encode(), message.encode(), hashlib.sha256)
    return base64.b64encode(mac.digest()).decode()

# WebSocket 连接成功时的回调函数
def on_open(ws):
    print("WebSocket连接已打开，开始认证...")
    timestamp = str(int(time.time()))
    signature = generate_signature(timestamp, "GET", "/users/self/verify", "")
    auth_message = {
        "op": "login",
        "args": [
            {
                "apiKey": API_KEY,
                "passphrase": PASSPHRASE,
                "timestamp": timestamp,
                "sign": signature
            }
        ]
    }
    ws.send(json.dumps(auth_message))

# WebSocket 接收到消息时的回调函数
def on_message(ws, message):
    print("收到的消息:", message)
    data = json.loads(message)
    if "event" in data and data["event"] == "login":
        print("认证成功...")
        # subscribe_message = {
        #     "op": "subscribe",
        #     "args": [
        #         # {"channel": "account"},
        #         # {"channel": "positions", "instType": "SWAP"}  # 确保加上 instType
        #     ]
        # }
        # ws.send(json.dumps(subscribe_message))
    # elif "arg" in data and "channel" in data["arg"] and data["arg"]["channel"] == "account":
    #     print("账户信息:", data)
    # elif "arg" in data and "channel" in data["arg"] and data["arg"]["channel"] == "positions":
    #     print("持仓信息:", data)


# WebSocket 连接关闭时的回调函数
def on_close(ws, close_status_code, close_msg):
    print("WebSocket连接已关闭")

# WebSocket 错误时的回调函数
def on_error(ws, error):
    print(f"WebSocket发生错误: {error}")

# 发送交易请求
def place_order(ws):
    print("发送买入订单...")

    order_message = {
        "id": "test123456789",  # 生成唯一订单 ID（最多 16 个字符）
        "op": "order",
        "args": [
            {
                "instId": "CSPR-USDT-SWAP",  # BTC/USDT合约
                "tdMode": "cross",  # 逐仓模式
                "side": "sell",  # 买入
                "ordType": "market",  # 市价单
                "sz": "1",  # 购买 1USDT 等值的 BTC 合约
                # "clOrdId": str(uuid.uuid4())[:16]  # 生成唯一订单 ID（最多 16 个字符）
                # "clOrdId": "test123456789"
                # "id": str(uuid.uuid4())[:16]  # 生成唯一订单 ID（最多 16 个字符）
            }
        ]
    }
    
    ws.send(json.dumps(order_message))  # 发送订单

    

# 创建并启动WebSocket连接    
def start_ws():
    ws = websocket.WebSocketApp(
        OKX_WS_URL,
        on_open=on_open,
        on_message=on_message,
        on_close=on_close,
        on_error=on_error
    )
    ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
    return ws  # 让它返回 WebSocket 连接


if __name__ == "__main__":
    # 启动 WebSocket 线程
    ws = websocket.WebSocketApp(
        OKX_WS_URL,
        on_open=on_open,
        on_message=on_message,
        on_close=on_close,
        on_error=on_error
    )

    ws_thread = threading.Thread(target=ws.run_forever, kwargs={"sslopt": {"cert_reqs": ssl.CERT_NONE}})
    ws_thread.start()

    # 确保 WebSocket 连接完成
    time.sleep(5)

    # 发送买入订单
    place_order(ws)
