发布于 2025-02-06 08:28:27 · 阅读量: 175094
想在 Bithumb 交易所用 API 操作?这活儿不难,但门槛不低,尤其对小白来说,一不小心就容易被绕晕。别急,这篇干货直击痛点,让你少走弯路,直接上手撸代码!
在 Bithumb API 上撒欢之前,先得拿到 API Key,不然连门都进不去。
Bithumb API 走的是 RESTful,加上 HMAC SHA512 签名认证,安全性拉满。建议用 Python 玩,先装上 requests
和 hashlib
这俩工具包:
bash pip install requests hashlib
然后写个最基础的 API 访问代码,看看能不能正常拉取账户余额:
import time import requests import hashlib import hmac import json
API_KEY = "你的API Key" API_SECRET = "你的Secret Key"
def make_signature(endpoint, params): query_string = '&'.join([f"{k}={v}" for k, v in sorted(params.items())]) message = f"{endpoint}\0{query_string}\0{API_SECRET}" return hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha512).hexdigest()
def get_balance(): endpoint = "/info/balance" params = { "apiKey": API_KEY, "secretKey": API_SECRET, "currency": "BTC", "timestamp": str(int(time.time() * 1000)) } headers = {"api-client-type": "2"} # 2 代表 Python 客户端 params["signature"] = make_signature(endpoint, params)
url = "https://api.bithumb.com" + endpoint
response = requests.post(url, data=params, headers=headers)
return response.json()
print(get_balance()) # 看看能不能正常返回账户余额
交易是 API 里最香的功能,我们可以用 /trade/place
来搞定下单。
def place_order(order_type, price, quantity): endpoint = "/trade/place" params = { "apiKey": API_KEY, "secretKey": API_SECRET, "order_currency": "BTC", "payment_currency": "KRW", "units": str(quantity), "price": str(price), "type": order_type, # "bid" 表示买入, "ask" 表示卖出 "timestamp": str(int(time.time() * 1000)) } headers = {"api-client-type": "2"} params["signature"] = make_signature(endpoint, params)
url = "https://api.bithumb.com" + endpoint
response = requests.post(url, data=params, headers=headers)
return response.json()
print(place_order("bid", 50000000, 0.01))
买卖完了,得看看订单执行得咋样,API /info/orders
可以派上用场:
def get_order_status(order_id): endpoint = "/info/orders" params = { "apiKey": API_KEY, "secretKey": API_SECRET, "order_id": order_id, "order_currency": "BTC", "payment_currency": "KRW", "timestamp": str(int(time.time() * 1000)) } headers = {"api-client-type": "2"} params["signature"] = make_signature(endpoint, params)
url = "https://api.bithumb.com" + endpoint
response = requests.post(url, data=params, headers=headers)
return response.json()
print(get_order_status("1234567890"))
下错单?后悔了?用 /trade/cancel
直接撤单:
def cancel_order(order_id, order_type): endpoint = "/trade/cancel" params = { "apiKey": API_KEY, "secretKey": API_SECRET, "order_id": order_id, "type": order_type, # "bid" 代表买单, "ask" 代表卖单 "order_currency": "BTC", "payment_currency": "KRW", "timestamp": str(int(time.time() * 1000)) } headers = {"api-client-type": "2"} params["signature"] = make_signature(endpoint, params)
url = "https://api.bithumb.com" + endpoint
response = requests.post(url, data=params, headers=headers)
return response.json()
print(cancel_order("1234567890", "bid"))
以上就是 Bithumb API 的交易核心流程,搞定这几步,你就能靠 API 轻松交易 BTC 了。当然,实际应用中你还可以加上止盈止损、网格策略、自动化套利等功能,进一步提升你的交易体验!