import requests
import os
import json
from decimal import Decimal
from datetime import datetime
import time

# 记录程序开始时间
start_time = time.time()




def get_instruments(instType):
    url = "https://www.okx.com/api/v5/public/instruments"
    
    # 设置请求参数
    params = {
        "instType": instType  # 通过参数传递产品类型
    }

    # 发送 GET 请求
    response = requests.get(url, params=params)
    
    if response.status_code == 200:
        # 请求成功，返回的数据
        return response.json()
    else:
        # 如果请求失败，打印错误信息
        return f"Error: {response.status_code}"

# 调用函数并打印结果
swap_data = get_instruments("SWAP")['data']

usdt_swap_pairs = set()
swap_info = {}

for item in swap_data:
    inst_id = item['instId']
    if inst_id.endswith('-USDT-SWAP'):
        spot_like_id = inst_id.replace('-SWAP', '')
        usdt_swap_pairs.add(spot_like_id)
        swap_info[spot_like_id] = {
            "sw-instId": inst_id,
            "sw-minSz": str(Decimal(item['minSz']))
        }

# 取得 SPOT 現貨清單
spot_data = get_instruments("SPOT")['data']
spot_pairs = set()
spot_info = {}

for item in spot_data:
    inst_id = item['instId']
    spot_pairs.add(inst_id)
    spot_info[inst_id] = {
        "sp-instId": inst_id,
        "sp-minSz": str(Decimal(item['minSz']))
    }

# 找出可套利的交易對
common_pairs = sorted(usdt_swap_pairs & spot_pairs)


def get_funding_rate(instId):
    url = "https://www.okx.com/api/v5/public/funding-rate"
    
    # 设置请求参数
    params = {
        "instId": instId  # 通过参数传递产品类型
    }

    # 发送 GET 请求
    response = requests.get(url, params=params)
    
    if response.status_code == 200:
        # 请求成功，返回的数据
        return response.json()
    else:
        # 如果请求失败，打印错误信息
        return f"Error: {response.status_code}"


# 建立結果清單
result = []

for pair in common_pairs:
    coin = pair.split('-')[0]

    # 預設 funding_apy 為 None
    funding_apy = None

    try:
        inst_id = swap_info[pair]["sw-instId"]
        data = get_funding_rate(inst_id)['data'][0]

        funding_rate = float(data['fundingRate'])

        # 計算 funding APY
        funding_time = datetime.utcfromtimestamp(int(data['fundingTime']) / 1000)
        next_time = datetime.utcfromtimestamp(int(data['nextFundingTime']) / 1000)
        interval_hr = (next_time - funding_time).total_seconds() / 3600
        daily_times = 24 / interval_hr
        funding_apy = funding_rate * daily_times * 365

        # 格式化為百分比文字（保留4位小數）
        funding_apy = format(funding_apy * 100, '.4f')

    except Exception as e:
        print(f"查詢 {pair} 資費失敗：{e}")
        funding_apy = None

    result.append({
        "coin": coin,
        "sp-minSz": spot_info[pair]["sp-minSz"],
        "sw-minSz": swap_info[pair]["sw-minSz"],
        "funding_apy": funding_apy
    })

# 儲存 JSON
current_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(current_dir, "可套利交易對.json")

with open(file_path, "w", encoding="utf-8") as f:
    json.dump(result, f, indent=4)

print(f"總共可套利交易對數量: {len(result)}")
print(f"儲存完成，檔名：{file_path}")



# 记录程序结束时间
end_time = time.time()

# 计算程序执行的总时间
execution_time = end_time - start_time

# 输出程序执行时间
print(f"程序执行时间: {execution_time:.4f} 秒")


# 等待用户输入，防止程序关闭
input("按 Enter 键退出...")