Python 新手就能搞定 Bitfinex API

2023/11/27閱讀時間約 7 分鐘

做 Bitfinex 放貸已經 2、3年了,曾經想過用 Bitfinex API 來記錄每天融資錢包的餘額,配合 Line Notify,每天傳餘額數字給自己,但苦於程式底子不足,就放棄了


2 年後的今天,我對於簽名、Nonce 等技術術語仍然一知半解,但我將 Bitfinex API 的網址直接提供給 ChatGPT,請他幫我寫程式,沒想到還真的寫出來了,過程中難免還是會出錯,但我把錯誤訊息丟回給 ChatGPT,它就能迅速幫我進行修改,最後終於完成,分享給大家


import requests
import json
import time
import hmac
import hashlib

# 設置您的 API 金鑰和秘密
api_key = 'YOUR_API_KEY'
api_secret = 'YOUR_API_SECRET'

# API 請求的資訊
api_path = 'v2/auth/r/wallets'
nonce = str(int(time.time() * 1000000))
body = {}

# 創建簽名
signature = '/api/' + api_path + nonce + json.dumps(body)
h = hmac.new(api_secret.encode(), signature.encode(), hashlib.sha384)
signature = h.hexdigest()

# 發送請求
url = 'https://api.bitfinex.com/' + api_path
headers = {
'bfx-nonce': nonce,
'bfx-apikey': api_key,
'bfx-signature': signature,
'content-type': 'application/json'
}

response = requests.post(url, headers=headers, data=json.dumps(body))

# 處理響應
if response.status_code == 200:
wallets = response.json()
# 查找 USD 餘額
usd_balance = next((wallet for wallet in wallets if wallet[0] == 'funding' and wallet[1] == 'USD'), None)
if usd_balance:
print("USD Balance:", usd_balance[2])
else:
print("USD wallet not found.")
else:
print("Error:", response.status_code, response.text)


加碼 Google Apps Script,因為我都用 Google Apps Script 串 Line 機器人,原以為有些東西只有 Python 套件才有,但反正最後還是成功寫出來了


function getUsdBalance() {
var api_key = 'YOUR_API_KEY';
var api_secret = 'YOUR_API_SECRET';

var api_path = 'v2/auth/r/wallets';
var nonce = new Date().getTime().toString() + '000'; // 增加三個零以提高精度
var body = JSON.stringify({});

var signature = '/api/' + api_path + nonce + body;
var hmac = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_384, signature, api_secret, Utilities.Charset.UTF_8);
var signatureHex = arrayToHex(hmac);

var url = 'https://api.bitfinex.com/' + api_path;
var headers = {
'bfx-nonce': nonce,
'bfx-apikey': api_key,
'bfx-signature': signatureHex,
'Content-Type': 'application/json'
};

var options = {
'method': 'post',
'headers': headers,
'payload': body,
'muteHttpExceptions': true
};

var response = UrlFetchApp.fetch(url, options);
if (response.getResponseCode() == 200) {
var wallets = JSON.parse(response.getContentText());
var usdBalance = wallets.find(function(wallet) {
return wallet[0] === 'funding' && wallet[1] === 'USD';
});
if (usdBalance) {
Logger.log("USD Balance: " + usdBalance[2]);
} else {
Logger.log("USD wallet not found.");
}
} else {
Logger.log("Error: " + response.getResponseCode() + " - " + response.getContentText());
}
}

function arrayToHex(byteArray) {
var hexString = '';
byteArray.forEach(function(byte) {
var byteHex = ('0' + (byte & 0xFF).toString(16)).slice(-2);
hexString += byteHex;
});
return hexString;
}
留言0
查看全部
發表第一個留言支持創作者!