发布于 2025-02-07 11:44:22 · 阅读量: 178538
想玩转 Bitfinex API?这可不是随便点几下就能搞定的事儿,但别慌,跟着这篇指南走,包你顺利上车,爽快撸 API!
首先,得有个 Bitfinex 账号,没有的话先去注册,记得开 两步验证(2FA),不然 API 可不给你面子。
然后,登录后进入 API Key 管理界面:
💡 注意:
- API Key 只显示一次,别搞丢了,不然得重新申请。
- API Secret 也要保存好,这可是你访问 API 的通行证!
API 搞定了,接下来是技术活,得装上 Bitfinex API SDK,推荐用 Python,方便又强大:
bash pip install bitfinex
或者如果你更偏爱 requests
,那就手动请求也行:
bash pip install requests
直接上代码,连通 Bitfinex API,检查 API Key 是否有效:
import requests import time import hmac import hashlib
API_KEY = '你的API Key' API_SECRET = '你的API Secret' BASE_URL = 'https://api.bitfinex.com'
def get_headers(endpoint, payload): payload_json = json.dumps(payload) payload_encoded = base64.b64encode(payload_json.encode()) signature = hmac.new(API_SECRET.encode(), payload_encoded, hashlib.sha384).hexdigest()
return {
'bfx-apikey': API_KEY,
'bfx-signature': signature,
'bfx-nonce': str(int(time.time() * 1000))
}
def check_account_info(): endpoint = '/v2/auth/r/wallets' payload = {} headers = get_headers(endpoint, payload)
response = requests.post(BASE_URL + endpoint, headers=headers, json=payload)
return response.json()
print(check_account_info())
如果返回你的钱包数据,说明 API 正常运行,可以愉快开整了!
搞定了连接,接下来尝试挂单,买点 BTC 玩玩:
def place_order(symbol, amount, price, side): endpoint = '/v2/auth/w/order/submit' payload = { "type": "LIMIT", "symbol": symbol, "amount": str(amount), "price": str(price), "side": side }
headers = get_headers(endpoint, payload)
response = requests.post(BASE_URL + endpoint, headers=headers, json=payload)
return response.json()
print(place_order('tBTCUSD', 0.01, 42000, 'buy'))
注意:Bitfinex 交易对一般是 tBTCUSD
这种格式,别写成 BTC/USDT
,不然 API 可不认!
想看看自己挂的单?来查查订单列表:
def get_orders(): endpoint = '/v2/auth/r/orders' payload = {} headers = get_headers(endpoint, payload)
response = requests.post(BASE_URL + endpoint, headers=headers, json=payload)
return response.json()
print(get_orders())
后悔了?单子不想要了?来取消订单:
def cancel_order(order_id): endpoint = '/v2/auth/w/order/cancel' payload = {"id": order_id}
headers = get_headers(endpoint, payload)
response = requests.post(BASE_URL + endpoint, headers=headers, json=payload)
return response.json()
print(cancel_order(123456))
看看自己还有多少钱:
def get_balance(): endpoint = '/v2/auth/r/wallets' payload = {}
headers = get_headers(endpoint, payload)
response = requests.post(BASE_URL + endpoint, headers=headers, json=payload)
return response.json()
print(get_balance())
Bitfinex API 没有专门的 Logout 机制,API Key 只要没被撤销就一直有效。如果要彻底退出 API 访问,直接去 Bitfinex 后台把 API Key 删除 就行。
Bitfinex API 的玩法可不少,比如 WebSocket 实时数据、杠杆交易、期货操作等,以上只是基础用法,更多骚操作可以自己摸索,或者直接翻 Bitfinex API 文档!