NodeJS API Binance GET免费余额

q1qsirdb  于 2022-12-29  发布在  Node.js
关注(0)|答案(3)|浏览(170)

我是API新手,希望您能给我一些建议。我希望调用Binance API“GET /api/v3/account(HMAC SHA 256)”,只获取我账户上的免费资产。
我得到的代码的响应是这样的:

{
  "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"
  ]
}

我只想要自由余额,所以我尝试使用MAP方法,但我得到这个错误:

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

按照我的代码:

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();

先谢谢你们对我的帮助。

py49o6xq

py49o6xq1#

我猜你一定是新的 AJAX ,因为你错过了2个重要的事实

  1. AJAX 需要时间
  2. AJAX 响应始终为字符串
    考虑您的代码片段
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

正如您所看到的,您在第11行发送 AJAX 请求,但是您试图在第4行操作(预期的)数据!因此出现了错误Cannot read property 'map' of undefined at Object
接下来,ourRequest.responseText是一个属性,它将服务器响应保存在string中,它没有任何map属性,所以需要使用JSON.parse()将其转换为一个对象
所以这应该没问题

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();
fcg9iug3

fcg9iug32#

您是否尝试过使用CCXT连接binance API?
您可以执行以下操作:

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

p4tfgftt3#

我不知道我是否理解了你的问题,但是我用python创建了自己的脚本来跟踪我的投资组合。

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)

然后我创建一个excel文件与数据框。请,建议没有显示比南斯赚取。

相关问题