[英]Binance python api query for global account balance
Hello i am using Binance api with python and all i can have is my SPOT account balance.您好,我正在使用 Binance api 和 python,我只能拥有我的 SPOT 账户余额。 I am using this:
我正在使用这个:
client.get_account()
Unfortunately staking assets (Earn balance) is not included so i can't have the whole situation rendered.不幸的是,不包括质押资产(收入余额),所以我无法呈现整个情况。 Is there any way to query all my assets on Binance with apis?
有什么方法可以通过 api 查询我在 Binance 上的所有资产吗? Should i query the Earn/savings account balance separately to the spot account balance?
我是否应该将赚取/储蓄账户余额与现货账户余额分开查询? Thank you
谢谢
I have implemented following code piece.我已经实现了以下代码。 It gives you:
它为您提供:
Overall Future
balance applying unRealizedProfit
应用
unRealizedProfit
总体Future
余额
Overall spot
balance, converting all assest's BTC value and sums them.整体
spot
余额,转换所有资产的 BTC 值并将它们相加。
There might be room for improvement but it does the job.可能还有改进的余地,但它确实可以完成工作。
#!/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)
Example output:示例 output:
./get_balance.py
* Futures=72.36 USD | SPOT=0.00 USD | MARGIN=0
* Spot => 0.01591034 BTC == 562.09649436 USDT
In searching for the answer for myself, I came across this post on Reddit , which I minimally re-formatted to fit on my screen, and added the get_all_earn_products
function:在为自己寻找答案时,我在 Reddit 上看到了这篇文章,我对其进行了最低限度的重新格式化以适合我的屏幕,并添加了
get_all_earn_products
function:
## 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 (lock)
# 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))
to get something like this:得到这样的东西:
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"
}
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.