Subscribe to Channels

Once a connection is established through a websocket, you are ready to send and receive data. Our API has public and private channels that you can subscribe to. Once you are subscribed, you will receive the data of this channel.

Subscribe to a channel

Below is an example on how to subscribe and unsubscribe to a channel:

const ws = new Sunbeam(client, opts)

const pair = 'tBTCUSD'

ws.on('open', () => {
  ws.subscribe('pub', 'book', ({ symbol: pair }))
  
  ws.unsubscribe('pub', 'book', ({ symbol: pair }))
})
const WebSocket = require('ws');

const ws = new WebSocket('wss://api.bitfinex.com/ws/2');

ws.on('open', () => {
  ws.send(JSON.stringify({
    event: 'subscribe',
    channel: 'book',
    symbol: 'tBTCUSD',
  }));
  
  ws.send(JSON.stringify({
    event: 'unsubscribe',
    channel: 'book',
    symbol: 'tBTCUSD',
  }));
});

Sunbeam also provides additional built in methods that allows you to subscribe and receive data:

const ws = new Sunbeam(client, opts)

const pair = 'tBTCUSD'

ws.on('open', () => {
  ws.subscribePublicTrades(pair)
  ws.subscribeOrderbook(pair)
  
  ws.onOrderbook({ symbol: pair }, (ob) => {
    console.log(`ws.onOrderbook({ symbol: ${pair} })`)
    console.log(ob)
  })

  ws.onOrders({}, (data) => {
    console.log('ws.onOrders({})')
    console.log(data)
  })
})

To subscribe to the private channels, call ws.auth() first. It will subscribe you to wallet, trade and order updates for the account that you have defined when creating a Sunbeam instance with opts.eos.auth.

const ws = new Sunbeam(client, opts)

ws.on('open', async () => {
  // subscribe to private order updates, wallet updates and trade updates
  await ws.auth()
})

Next up is a guide to handle orders.


What’s Next