BINANCE API - 如何使用用户数据流获取帐户信息

时间:2018-03-04 23:39:19

标签: javascript node.js api websocket

我正在使用Node和ws npm包来处理WebSockets。得到了文档(下面)中所述的listenKey,但我无法使用用户数据流获取我的帐户信息。我更喜欢使用流来读取我最新的帐户信息(余额等),因为每次使用Rest API都会产生一个惩罚(重量:5)。

我尝试过ws.send('outboundAccountInfo'),但没有快乐。

DOCS:https://github.com/binance-exchange/binance-official-api-docs/blob/master/user-data-stream.md

完整代码示例 - 不返回任何数据:

import request from 'request'
import WebSocket from 'ws'

import { API_KEY } from '../../assets/secrets'


const DATA_STREAM_ENDPOINT = 'wss://stream.binance.com:9443/ws'
const BINANCE_API_ROOT = 'https://api.binance.com'
const LISTEN_KEY_ENDPOINT = `${BINANCE_API_ROOT}/api/v1/userDataStream`

const fetchAccountWebsocketData = async() => { 
  const listenKey = await fetchListenKey()

  console.log('-> ', listenKey) // valid key is returned

  let ws

  try {
    ws = await openWebSocket(`${DATA_STREAM_ENDPOINT}/${listenKey}`)
  } catch (err) {
    throw(`ERROR - fetchAccountWebsocketData: ${err}`)
  }

  // Nothing returns from either
  ws.on('message', data => console.log(data))
  ws.on('outboundAccountInfo', accountData => console.log(accountData))
}

const openWebSocket = endpoint => {
  const p = new Promise((resolve, reject) => {
    const ws = new WebSocket(endpoint)

    console.log('\n-->> New Account Websocket')

    ws.on('open', () => {
      console.log('\n-->> Websocket Account open...')
      resolve(ws)
    }, err => { 
      console.log('fetchAccountWebsocketData error:', err)
      reject(err) 
    })
  })

  p.catch(err => console.log(`ERROR - fetchAccountWebsocketData: ${err}`))
  return p
}

const fetchListenKey = () => {
  const p = new Promise((resolve, reject) => {
    const options = {
      url: LISTEN_KEY_ENDPOINT, 
      headers: {'X-MBX-APIKEY': API_KEY}
    }

    request.post(options, (err, httpResponse, body) => {
      if (err) 
        return reject(err)

      resolve(JSON.parse(body).listenKey)
    })
  })

  p.catch(err => console.log(`ERROR - fetchListenKey: ${err}`))
  return p
}

export default fetchAccountWebsocketData

1 个答案:

答案 0 :(得分:0)

也在努力挣扎....几个小时了!

https://www.reddit.com/r/BinanceExchange/comments/a902cq/user_data_streams_has_anyone_used_it_successfully/

  

连接时,币安用户数据流不返回任何内容   仅当您的帐户发生变化时才使用此功能。尝试运行   代码,然后转到币安并在书中下订单,您应该   看到一些数据显示*