您好,我正在将 Binance api 与 python 一起使用,我所能拥有的只是我的 SPOT 账户余额。我正在使用这个:
client.get_account()
不幸的是,不包括质押资产(收入余额),所以我无法呈现整个情况。有什么方法可以通过 api 查询我在 Binance 上的所有资产吗?我是否应该将赚取/储蓄账户余额与现货账户余额分开查询?谢谢
您好,我正在将 Binance api 与 python 一起使用,我所能拥有的只是我的 SPOT 账户余额。我正在使用这个:
client.get_account()
不幸的是,不包括质押资产(收入余额),所以我无法呈现整个情况。有什么方法可以通过 api 查询我在 Binance 上的所有资产吗?我是否应该将赚取/储蓄账户余额与现货账户余额分开查询?谢谢
我Binance Python API
用来获取余额spot
和margin
余额futures
。请查看@Partha D.
获取收入帐户的解决方案。
我已经实现了以下代码。它为您提供:
申请总Future
余额unRealizedProfit
整体spot
余额,将所有资产的 BTC 值转换并求和。
可能还有改进的余地,但它确实可以完成工作。
#!/usr/bin/env python3
class ClientHelper:
def __init__(self, client):
self.client = client
def _format(self, value, decimal=2):
return format(float(value), ".2f")
def transfer_futures_to_spot(self, amount):
self.client.futures_account_transfer(asset="USDT", amount=float(amount), type="2")
def transfer_spot_to_futures(self, amount):
self.client.futures_account_transfer(asset="USDT", amount=float(amount), type="1")
def transfer_spot_to_margin(self, amount):
self.client.transfer_spot_to_margin(asset="USDT", amount=float(amount), type="1")
def get_balance_margin_USDT(self):
try:
_len = len(self.client.get_margin_account()["userAssets"])
for x in range(_len):
if self.client.get_margin_account()["userAssets"][x]["asset"] == "USDT":
balance_USDT = self.lient.get_margin_account()["userAssets"][x]["free"]
return float(balance_USDT)
except:
pass
return 0
def spot_balance(self):
sum_btc = 0.0
balances = self.client.get_account()
for _balance in balances["balances"]:
asset = _balance["asset"]
if float(_balance["free"]) != 0.0 or float(_balance["locked"]) != 0.0:
try:
btc_quantity = float(_balance["free"]) + float(_balance["locked"])
if asset == "BTC":
sum_btc += btc_quantity
else:
_price = self.client.get_symbol_ticker(symbol=asset + "BTC")
sum_btc += btc_quantity * float(_price["price"])
except:
pass
current_btc_price_USD = self.client.get_symbol_ticker(symbol="BTCUSDT")["price"]
own_usd = sum_btc * float(current_btc_price_USD)
print(" * Spot => %.8f BTC == " % sum_btc, end="")
print("%.8f USDT" % own_usd)
def get_futures_usdt(self, is_both=True) -> float:
futures_usd = 0.0
for asset in self.client.futures_account_balance():
name = asset["asset"]
balance = float(asset["balance"])
if name == "USDT":
futures_usd += balance
if name == "BNB" and is_both:
current_bnb_price_USD = self.client.get_symbol_ticker(symbol="BNBUSDT")["price"]
futures_usd += balance * float(current_bnb_price_USD)
return float(futures_usd)
def _get_futures_usdt(self):
"""USDT in Futures, unRealizedProfit is also included"""
futures_usd = self.get_futures_usdt(is_both=False)
futures = self.client.futures_position_information()
for future in futures:
if future["positionAmt"] != "0" and float(future["unRealizedProfit"]) != 0.00000000:
futures_usd += float(future["unRealizedProfit"])
return format(futures_usd, ".2f")
def main(client_helper):
for balance in balances["balances"]:
if balance["asset"] == "USDT":
usdt_balance = balance["free"]
break
margin_usdt = client_helper.get_balance_margin_USDT()
futures_usd = client_helper._get_futures_usdt()
futures_usd = client_helper._get_futures_usdt()
print(f" * Futures={futures_usd} USD | SPOT={client_helper._format(usdt_balance)} USD | MARGIN={margin_usdt} ")
client_helper.spot_balance()
if __name__ == "__main__":
client = Client(api_key, api_secret)
client_helper = ClientHelper(client)
main(client_helper)
示例输出:
./get_balance.py
* Futures=72.36 USD | SPOT=0.00 USD | MARGIN=0
* Spot => 0.01591034 BTC == 562.09649436 USDT
在为自己寻找答案时,我在 Reddit 上看到了这篇文章,我对其进行了最低限度的重新格式化以适合我的屏幕,并添加了以下get_all_earn_products
功能:
## From https://www.reddit.com/r/binance/comments/k6b1r7/
## accessing_earn_with_api/gu21o15/?utm_source=share
## &utm_medium=web2x&context=3
import hmac
import hashlib
import requests
import json
import time
uri = "https://api.binance.com"
## Fill in your Binance API key and Secret keys:
binance_api_key = ""
binance_api_secret = ""
def get_timestamp_offset():
url = "{}/api/v3/time".format(uri)
payload = {}
headers = {"Content-Type": "application/json"}
response = requests.request("GET", url, headers=headers, data=payload)
result = json.loads(response.text)["serverTime"] - int(time.time() * 1000)
return result
def generate_signature(query_string):
m = hmac.new(binance_api_secret.encode("utf-8"),
query_string.encode("utf-8"),
hashlib.sha256)
return m.hexdigest()
def get_flexible_savings_balance(asset):
""" Get your balance in Bincance Earn :: Flexible Savings """
timestamp = int(time.time() * 1000 + get_timestamp_offset())
query_string = "asset={}×tamp={}".format(asset, timestamp)
signature = generate_signature(query_string)
url = "{}/sapi/v1/lending/daily/token/position?{}&signature={}".format(
uri, query_string, signature)
payload = {}
headers = {"Content-Type": "application/json",
"X-MBX-APIKEY": binance_api_key}
result = json.loads(requests.request("GET", url, headers=headers, data=payload).text)
return result
def get_locked_savings_balance(asset, project_id):
""" Get your balance in Bincance Earn :: Locked Savings """
timestamp = int(time.time() * 1000 + get_timestamp_offset())
query_string = "asset={}&projectId={}&status=HOLDING×tamp={}".format(
asset, project_id, timestamp)
signature = generate_signature(query_string)
url = "{}/sapi/v1/lending/project/position/list?{}&signature={}".format(
uri, query_string, signature)
payload = {}
headers = {"Content-Type": "application/json",
"X-MBX-APIKEY": binance_api_key}
result = json.loads(requests.request("GET", url, headers=headers, data=payload).text)
return result
def get_all_earn_products():
""" Gets all savings products from Binance """
def get_earn_products(current_page=1):
""" Gets 50 savings products in "current" page ...modified from source:
https://binance-docs.github.io/apidocs/spot/en/#savings-endpoints """
timestamp = int(time.time() * 1000 + get_timestamp_offset())
query_string = "¤t={}&status=SUBSCRIBABLE×tamp={}".format(
current_page, timestamp)
signature = generate_signature(query_string)
url = "{}/sapi/v1/lending/daily/product/list?{}&signature={}".format(
uri, query_string, signature)
payload = {}
headers = {"Content-Type": "application/json",
"X-MBX-APIKEY": binance_api_key}
result = json.loads(requests.request("GET", url, headers=headers, data=payload).text)
return result
all_products = []
more_products = True
current_page = 0
while more_products:
current_page += 1
prod = get_earn_products(current_page=current_page)
all_products.extend(prod)
if len(prod)==50:
more_products = True
else:
more_products = False
return all_products
if __name__=="__main__":
# flex = get_flexible_savings_balance("BTC")
# print (flex)
# print ('')
# lock = get_locked_savings_balance("FUN", "CFUN14DAYSS001")
# print (json.dumps(lock, indent=2))
# print ('')
earn_products = get_all_earn_products()
print ("There are", len(earn_products), "subscribable earn products.\n")
print ("The frist two of them are:\n\n",
json.dumps(earn_products[0:2], indent=2))
得到这样的东西:
There are 140 subscribable earn products.
The frist two of them are:
[
{
"productId": "AVAX001",
"asset": "AVAX",
"status": "PURCHASING",
"canPurchase": true,
"canRedeem": true,
"featured": true,
"avgAnnualInterestRate": "0.01214355",
"purchasedAmount": "8042.32212732",
"upLimit": "10000000",
"upLimitPerUser": "10000000",
"minPurchaseAmount": "0.1",
"tierAnnualInterestRate": {
">5AVAX": "0.00200020",
"0-5AVAX": "0.03000300"
}
},
{
"productId": "LUNA001",
"asset": "LUNA",
"status": "PURCHASING",
"canPurchase": true,
"canRedeem": true,
"featured": true,
"avgAnnualInterestRate": "0.01214355",
"purchasedAmount": "21092.73974528",
"upLimit": "10000000",
"upLimitPerUser": "10000000",
"minPurchaseAmount": "0.1",
"tierAnnualInterestRate": {
"0-5LUNA": "0.03000300",
">5LUNA": "0.00200020"
}
}
]
lock = get_locked_savings_balance("FUN", "CFUN14DAYSS001")
print (json.dumps(lock, indent=2))
在上述代码的末尾......得到这样的东西 -
[
{
"asset": "FUN",
"canTransfer": true,
"createTimestamp": 1640453123000,
"duration": 14,
"endTime": 1641686300000,
"interest": "3.45",
"interestRate": "0.44999286",
"lot": 20,
"positionId": 1438863,
"principal": "200",
"projectId": "CFUN14DAYSS001",
"projectName": "FUN",
"purchaseTime": 1640453154000,
"redeemDate": "2022-01-09",
"startTime": 1640476700000,
"status": "HOLDING",
"type": "CUSTOMIZED_FIXED"
}
]