Sample code for 30+ languages & platforms
React Native

WebSocket Binance Trade Stream (subscribe and receive updates)

See more WebSocket Examples

Subscribe to a binance trade stream and receive updates.

Chilkat React Native Downloads

React Native
import { JsonObject, Rest, WebSocket } from '@chilkat/react-native'

async function chilkatExample() {
  // This example requires the Chilkat API to have been previously unlocked.
  // See Global Unlock Sample for sample code.

  const ws = new WebSocket();

  // For brevity, this example does not check for errors when etablishing the WebSocket connection.
  // See Establish WebSocket Connection for more complete sample code for making the connection.

  const rest = new Rest();

  // Connect to wss://stream.binance.com:9443
  try {
    await rest.connectAsync('stream.binance.com', 9443, true, false);
  } catch {
    console.log(rest.lastErrorText);
    return;
  }

  try {
    ws.useConnection(rest);
  } catch {
    console.log(ws.lastErrorText);
    return;
  }

  ws.addClientHeaders();

  //  Raw streams are accessed at /ws/<streamName>
  let responseBody: string;
  try {
    responseBody = await rest.fullRequestNoBodyAsync('GET', '/ws/btcusdt');
  } catch {
    console.log(rest.lastErrorText);
    return;
  }

  try {
    ws.validateServerHandshake();
  } catch {
    console.log(ws.lastErrorText);
    console.log(responseBody);
    console.log(rest.responseHeader);
    return;
  }

  console.log(responseBody);
  console.log(rest.responseHeader);

  // POST JSON to subscribe to a stream

  // {
  // "method": "SUBSCRIBE",
  // "params":
  // [
  // "btcusdt@aggTrade",
  // "btcusdt@depth"
  // ],
  // "id": 1
  // }

  const json = new JsonObject();
  json.updateString('method', 'SUBSCRIBE');
  json.updateString('params[0]', 'btcusdt@aggTrade');
  json.updateString('params[1]', 'btcusdt@depth');
  json.updateInt('id', 1);

  // Send a full message in a single frame
  const finalFrame = true;
  try {
    await ws.sendFrameAsync(json.emit(), finalFrame);
  } catch {
    console.log(ws.lastErrorText);
    return;
  }

  const jsonTradeData = new JsonObject();
  jsonTradeData.emitCompact = false;

  // Begin reading the trade stream response.
  // We'll just read the 1st 10 updates and then exit..
  let numTradesReceived = 0;
  while (numTradesReceived < 5) {

    try {
      await ws.readFrameAsync();
    } catch {
      console.log('Failed to receive a frame');
      console.log(`ReadFrame fail reason = ${ws.readFrameFailReason}`);
      console.log(ws.lastErrorText);
      return;
    }

    // The responses we desire are in Text frames, where the opcode = 1.
    if (ws.frameOpcodeInt === 1) {
      const receivedJson = ws.getFrameData();

      jsonTradeData.load(receivedJson);
      console.log(jsonTradeData.emit());

      numTradesReceived++;
    }
  }

  // Close the websocket connection.
  try {
    await ws.sendCloseAsync(true, 1000, 'Closing this websocket.');
  } catch {
    console.log(ws.lastErrorText);
    return;
  }

  // Read the Close response.
  try {
    await ws.readFrameAsync();
  } catch {
    console.log(`ReadFrame fail reason = ${ws.readFrameFailReason}`);
    console.log(ws.lastErrorText);
    return;
  }

  console.log('Success.');

  // The output of the above code is shown here:
}