API Binance GET free Balance

Viewed 13513

I'm new with API and I will appreciate your kind advice. I would like to recall Binance API "GET /api/v3/account (HMAC SHA256)" to get only the free assets available on my account.

The response with the code I get, it's something like:

{
  "makerCommission": 15,
  "takerCommission": 15,
  "buyerCommission": 0,
  "sellerCommission": 0,
  "canTrade": true,
  "canWithdraw": true,
  "canDeposit": true,
  "updateTime": 123456789,
  "accountType": "SPOT",
  "balances": [
    {
      "asset": "BTC",
      "free": "4723846.89208129",
      "locked": "0.00000000"
    },
    {
      "asset": "LTC",
      "free": "4763368.68006011",
      "locked": "0.00000000"
    }
  ],
    "permissions": [
    "SPOT"
  ]
}

I just want the free balance, so I tried using the MAP methos, but I'm obtaining this error:

Cannot read property 'map' of undefined at Object.<anonymous><C:\Users\etc..
at Module._compile (internal/module/cjs/loader.js1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Function.executeEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/run_main_module.js:17:47

Following my code:

    const crypto = require('crypto');
    var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
    var burl = "https://api.binance.com";
    var endPoint = "/api/v3/account";
    var dataQueryString = "timestamp=" + Date.now();
    var keys = {
        "APIkey" :'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
        "SECRETkey" : 'BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB'
        }
    var signature = crypto.createHmac('sha256',keys['SECRETkey']).update(dataQueryString).digest('hex');
    var url = burl + endPoint + '?' + dataQueryString + '&signature=' + signature;
    var ourRequest = new XMLHttpRequest();
    ourRequest.open('GET',url,true);
    ourRequest.setRequestHeader('X-MBX-APIKEY', keys['APIkey']);
    let arrayCleaned = ourRequest.responseText.balances.map(ele => {
            return {
                "asset" : ele.asset,
                "free" : ele.free
            }
        })
    console.log(arrayCleaned);
    ourRequest.send();

Thank you all in advance for helping me.

3 Answers

I am guessing you must be new to AJAX because you are missing 2 important facts

  1. AJAX takes time
  2. AJAX response is always a string

Consider your snippet

var ourRequest = new XMLHttpRequest();
ourRequest.open('GET',url,true);   
//           ^---- doesn't actually send any request https://stackoverflow.com/q/29362977/6160662
ourRequest.setRequestHeader('X-MBX-APIKEY', keys['APIkey']);
let arrayCleaned = ourRequest.responseText.balances.map(ele => {  //Line 4
        return {
            "asset" : ele.asset,
            "free" : ele.free
        }
    })
console.log(arrayCleaned);
ourRequest.send(); //Line 11

As you can see you are sending the ajax request on line 11 but you are trying to manipulate the (prospective) data on line 4! hence the error Cannot read property 'map' of undefined at Object

Next thing is ourRequest.responseText is a property that holds the server response in string it doesn't have any map property. So you need to convert it into an object by using JSON.parse()

So this should work fine

var ourRequest = new XMLHttpRequest();
ourRequest.open('GET',url,true);
ourRequest.setRequestHeader('X-MBX-APIKEY', keys['APIkey']);

var arrayCleaned = [];
ourRequest.onload = function () {
    // Convert data string to an object
    var data = JSON.parse(ourRequest.responseText); // string -->to Object

    arrayCleaned = data.balances.map(ele => {
        return {
            "asset" : ele.asset,
            "free" : ele.free
        }
    })
    console.log(arrayCleaned);
};

ourRequest.send();

Have you tried using CCXT to connect to the binance API?

You can do the following:

;(async () => {
    const binance = ccxt.binance ({'apiKey': 'YOURAPIKEY', 'secret': 'YOURSECRET'})
    const balance = await binance.fetchBalance ()
    const free = balance['free']
    console.log (free)
}) ()

I don't know if I understood you question, but I created my own script to track my portfolio using python. This may help:

    from binance.client import Client

def editar_df_binance(lista):
    df = pd.DataFrame(lista)
    df["free"] = df["free"].astype(float)  #Convertimos las columnas a valores float
    df["locked"] = df["locked"].astype(float)  #Convertimos las columnas a valores float
    filtro1 = df["free"] > 0
    filtro2 = df["locked"] > 0
    df = df[filtro1 | filtro2]
    df["Fecha"] = hoy
    df = df.rename(columns={"asset": "Moneda", "free": "Saldo", "locked": "Bloqueado"}).sort_values(by="Saldo", ascending=False)  #Renombramos y ordenamos
    df["Moneda"] = df["Moneda"].apply(editar_moneda_binance)  #Vamos a corregir el nombre de las monedas de earn que aparecen con "LD"
    df = df[["Fecha", "Moneda", "Saldo", "Bloqueado"]]

    return df
    
def editar_moneda_binance(moneda):
    if moneda.startswith("LD"):
        return moneda.replace("LD", "")
    return moneda
    
    
if __name__ == '__main__':
    ###############Balance Binance###################  (Falta la parte de earn)
    api_key = os.environ.get('binance_api')
    api_secret = os.environ.get('binance_secret')
    client = Client(api_key, api_secret)
    diccionario = client.get_account()["balances"]  #Obtener valores de balance
    df_binance = editar_df_binance(diccionario)

Then I create an excel file with dataframe. Please, advice that Binance Earn are not shown.

Related