簡體   English   中英

Binance python api 查詢全球賬戶余額

[英]Binance python api query for global account balance

您好,我正在使用 Binance api 和 python,我只能擁有我的 SPOT 賬戶余額。 我正在使用這個:

client.get_account()

不幸的是,不包括質押資產(收入余額),所以我無法呈現整個情況。 有什么方法可以通過 api 查詢我在 Binance 上的所有資產嗎? 我是否應該將賺取/儲蓄賬戶余額與現貨賬戶余額分開查詢? 謝謝

我已經實現了以下代碼。 它為您提供:

  • 應用unRealizedProfit總體Future余額

  • 整體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)

示例 output:

./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 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={}&timestamp={}".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&timestamp={}".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 = "&current={}&status=SUBSCRIBABLE&timestamp={}".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))

得到這樣的東西:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM