Sample code for 30+ languages & platforms
PHP

WebSocket Binance Trade Stream (subscribe and receive updates)

See more WebSocket Examples

Subscribe to a binance trade stream and receive updates.

Chilkat PHP Downloads

PHP
<?php

use Chilkat2\JsonObject;
use Chilkat2\Rest;
use Chilkat2\WebSocket;

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

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

$rest = new Rest();

// Connect to wss://stream.binance.com:9443
try {
    $rest->Connect('stream.binance.com', 9443, true, false);

    $ws->UseConnection($rest);

    $ws->AddClientHeaders();

    //  Raw streams are accessed at /ws/<streamName>
    $responseBody = $rest->FullRequestNoBody('GET', '/ws/btcusdt');
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

try {
    $ws->ValidateServerHandshake();
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    echo $responseBody, "\n";
    echo $rest->ResponseHeader, "\n";
    exit;
}

echo $responseBody, "\n";
echo $rest->ResponseHeader, "\n";

// POST JSON to subscribe to a stream

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

$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
$finalFrame = true;
try {
    $ws->SendFrame($json->Emit(), $finalFrame);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

$jsonTradeData = new JsonObject();
$jsonTradeData->EmitCompact = false;

// Begin reading the trade stream response.
// We'll just read the 1st 10 updates and then exit..
$numTradesReceived = 0;
while ($numTradesReceived < 5) {
    try {
        $ws->ReadFrame();
    } catch (\Chilkat2\Exception $e) {
        echo "Failed to receive a frame\n";
        echo 'ReadFrame fail reason = ', $ws->ReadFrameFailReason, "\n";
        echo $e->getMessage(), "\n";
        exit;
    }

    // The responses we desire are in Text frames, where the opcode = 1.
    if ($ws->FrameOpcodeInt == 1) {
        $receivedJson = $ws->GetFrameData();

        $jsonTradeData->Load($receivedJson);
        echo $jsonTradeData->Emit(), "\n";

        $numTradesReceived = $numTradesReceived + 1;
    }
}

// Close the websocket connection.
try {
    $ws->SendClose(true, 1000, 'Closing this websocket.');
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

// Read the Close response.
try {
    $ws->ReadFrame();
} catch (\Chilkat2\Exception $e) {
    echo 'ReadFrame fail reason = ', $ws->ReadFrameFailReason, "\n";
    echo $e->getMessage(), "\n";
    exit;
}

echo "Success.\n";

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