You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何通过Python从KuCoin获取币种的当前借贷额度

如何通过Python从KuCoin获取币种的当前借贷额度

嘿,我来帮你搞定这个问题!你之前用的client.get_accounts()确实拿不到借贷额度——因为这个接口是用来获取普通现货账户的余额信息的,而借贷相关的数据都存在保证金账户的专属接口里。

你找到的跨仓保证金账户详情方向是对的,下面给你两种Python实现方式,选你顺手的来:

方式一:用KuCoin官方Python SDK(推荐)

首先确保你装了最新版的SDK,旧版本可能没封装这个接口:

pip install kucoin-python --upgrade

然后直接调用对应的方法就行,代码示例:

from kucoin.client import Client

# 替换成你自己的API信息
api_key = "你的API密钥"
api_secret = "你的API密钥"
api_passphrase = "你的API密码"

# 初始化客户端
client = Client(api_key, api_secret, api_passphrase)

# 获取跨仓保证金账户详情
cross_margin_info = client.get_cross_margin_account()

# 遍历每个币种,提取借贷相关数据
for currency_item in cross_margin_info.get("currencies", []):
    currency = currency_item["currency"]
    borrowed_amount = currency_item["borrowed"]  # 已借额度
    borrow_limit = currency_item["borrowLimit"]   # 当前可借额度
    print(f"币种:{currency}")
    print(f"已借额度:{borrowed_amount}")
    print(f"最大可借额度:{borrow_limit}\n")

方式二:手动构造API请求(如果SDK用不了的话)

要是你不想用SDK,或者版本兼容有问题,也可以直接用requests库调用REST接口,需要自己处理KuCoin API要求的签名验证:

先装requests:

pip install requests

然后代码:

import requests
import time
import hmac
import hashlib
import base64

# 替换成你的API信息
api_key = "你的API密钥"
api_secret = "你的API密钥"
api_passphrase = "你的API密码"

# 跨仓保证金账户详情的API端点
api_url = "https://api.kucoin.com/api/v1/margin/account"
request_path = "/api/v1/margin/account"
method = "GET"

# 生成签名所需的时间戳
timestamp = str(int(time.time() * 1000))
# GET请求的body为空字符串
body = ""

# 构造签名字符串并生成签名
sign_str = timestamp + method + request_path + body
signature = base64.b64encode(hmac.new(api_secret.encode(), sign_str.encode(), hashlib.sha256).digest()).decode()

# 构造请求头
headers = {
    "KC-API-KEY": api_key,
    "KC-API-SIGN": signature,
    "KC-API-TIMESTAMP": timestamp,
    "KC-API-PASSPHRASE": api_passphrase,
    "KC-API-KEY-VERSION": "2"
}

# 发送请求并处理返回结果
response = requests.get(api_url, headers=headers)
result = response.json()

if result["code"] == "200000":
    # 遍历币种数据
    for currency_item in result["data"]["currencies"]:
        print(f"币种:{currency_item['currency']}")
        print(f"已借额度:{currency_item['borrowed']}")
        print(f"最大可借额度:{currency_item['borrowLimit']}\n")
else:
    print(f"请求出错啦:{result['msg']}")

简单说下返回数据:currencies数组里的每个对象都包含了对应币种的借贷信息,borrowed是你已经借出的额度,borrowLimit是当前还能借的最大额度,这俩就是你要找的核心数据~

备注:内容来源于stack exchange,提问作者Marcel Fischer

火山引擎 最新活动