Ben
Ben

Reputation: 5422

BINANCE API - How to get Account info with User Data Stream

I'm using Node and the ws npm package to work with WebSockets. Got the listenKey as stated in the docs (below), but I'm unable to get my account info using User Data Stream. I'd prefer to use a stream to read my most current account info (balances, etc) since using the Rest API to do it incurs a penalty (WEIGHT: 5) each time.

I've tried doing ws.send('outboundAccountInfo') but no joy.

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

Full code example - does not return any data:

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

Upvotes: 11

Views: 14518

Answers (1)

Nikita Yo LAHOLA
Nikita Yo LAHOLA

Reputation: 432

Was stuggling too .... for hours !!!

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

The binance user data stream doesn't return anything when you connect to it, only when something changes in your account. Try running your code, then go to binance and place an order in the book, you should see some data show up*

Upvotes: 5

Related Questions