Sample code for 30+ languages & platforms
Dart

WebSocket Binance Trade Stream (subscribe and receive updates)

See more WebSocket Examples

Subscribe to a binance trade stream and receive updates.

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

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

  final ws = CkWebSocket();

  // 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.

  final rest = CkRest();

  // Connect to wss://stream.binance.com:9443
  try {
    rest.connect('stream.binance.com', 9443, true, false);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  try {
    ws.useConnection(rest);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  ws.addClientHeaders();

  //  Raw streams are accessed at /ws/<streamName>
  final String responseBody;
  try {
    responseBody = rest.fullRequestNoBody('GET', '/ws/btcusdt');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  try {
    ws.validateServerHandshake();
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    print(responseBody);
    print(rest.responseHeader);
    return;
  }

  print(responseBody);
  print(rest.responseHeader);

  // POST JSON to subscribe to a stream

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

  final json = CkJsonObject();
  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
  final finalFrame = true;
  try {
    ws.sendFrame(json.emit(), finalFrame);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  final jsonTradeData = CkJsonObject();
  jsonTradeData.emitCompact = false;

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

    try {
      ws.readFrame();
    } on ChilkatException catch (e) {
      print('Failed to receive a frame');
      print('ReadFrame fail reason = ${ws.readFrameFailReason}');
      print(e.lastErrorText);
      return;
    }

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

      jsonTradeData.load(receivedJson);
      print(jsonTradeData.emit());

      numTradesReceived++;
    }
  }

  // Close the websocket connection.
  try {
    ws.sendClose(true, 1000, 'Closing this websocket.');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Read the Close response.
  try {
    ws.readFrame();
  } on ChilkatException catch (e) {
    print('ReadFrame fail reason = ${ws.readFrameFailReason}');
    print(e.lastErrorText);
    return;
  }

  print('Success.');

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