Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

WebSocket Binance Trade Stream (subscribe and receive updates)

See more WebSocket Examples

Subscribe to a binance trade stream and receive updates.

Chilkat Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.Rest,
  Chilkat.WebSocket,
  Chilkat.JsonObject;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  ws: TWebSocket;
  rest: TRest;
  responseBody: string;
  json: TJsonObject;
  finalFrame: Boolean;
  jsonTradeData: TJsonObject;
  receivedFinalFrame: Boolean;
  numTradesReceived: Integer;
  receivedJson: string;

begin
  success := False;

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

  ws := TWebSocket.Create;

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

  rest := TRest.Create;

  //  Connect to wss://stream.binance.com:9443
  success := rest.Connect('stream.binance.com',9443,True,False);
  if (success = False) then
    begin
      WriteLn(rest.LastErrorText);
      Exit;
    end;
  success := ws.UseConnection(rest);
  if (success = False) then
    begin
      WriteLn(ws.LastErrorText);
      Exit;
    end;
  ws.AddClientHeaders();

  //   Raw streams are accessed at /ws/<streamName>
  responseBody := rest.FullRequestNoBody('GET','/ws/btcusdt');
  if (rest.LastMethodSuccess = False) then
    begin
      WriteLn(rest.LastErrorText);
      Exit;
    end;
  success := ws.ValidateServerHandshake();
  if (success <> True) then
    begin
      WriteLn(ws.LastErrorText);
      WriteLn(responseBody);
      WriteLn(rest.ResponseHeader);
      Exit;
    end;

  WriteLn(responseBody);
  WriteLn(rest.ResponseHeader);

  //  POST JSON to subscribe to a stream

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

  json := TJsonObject.Create;
  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
  finalFrame := True;
  success := ws.SendFrame(json.Emit(),finalFrame);
  if (success <> True) then
    begin
      WriteLn(ws.LastErrorText);
      Exit;
    end;

  jsonTradeData := TJsonObject.Create;
  jsonTradeData.EmitCompact := False;

  //  Begin reading the trade stream response.
  //  We'll just read the 1st 10 updates and then exit..
  receivedFinalFrame := False;
  numTradesReceived := 0;
  while numTradesReceived < 5 do
    begin

      success := ws.ReadFrame();
      if (success <> True) then
        begin
          WriteLn('Failed to receive a frame');
          WriteLn('ReadFrame fail reason = ' + ws.ReadFrameFailReason);
          WriteLn(ws.LastErrorText);
          Exit;
        end;

      //  The responses we desire are in Text frames, where the opcode = 1.
      if (ws.FrameOpcodeInt = 1) then
        begin
          receivedJson := ws.GetFrameData();

          jsonTradeData.Load(receivedJson);
          WriteLn(jsonTradeData.Emit());

          numTradesReceived := numTradesReceived + 1;
        end;

    end;

  //  Close the websocket connection.
  success := ws.SendClose(True,1000,'Closing this websocket.');
  if (success <> True) then
    begin
      WriteLn(ws.LastErrorText);
      Exit;
    end;

  //  Read the Close response.
  success := ws.ReadFrame();
  if (success <> True) then
    begin
      WriteLn('ReadFrame fail reason = ' + ws.ReadFrameFailReason);
      WriteLn(ws.LastErrorText);
      Exit;
    end;

  WriteLn('Success.');

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


  ws.Free;
  rest.Free;
  json.Free;
  jsonTradeData.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.