TLDR; Here is a little bit of PHP using the TexTalk library for those who don’t want to rip their hair out.
I struggled for the better part of 2 days trying to figure out wtf was going on after following the api documents to the letter. It wasn’t until I printed the frigging JS example out that I realized they’d converted the timestamp to a string, where the api docs just above showed it passed as an integer.
Much like everything else coinbase, the error is quite informative by saying nothing about timestamp being invalid..
After that, I realized that even though the v2 API will give me every symbol back, I can ONLY push the symbols my api key had access to, or it would would accept the json subscribe and silently sit there until the socket times out.
Anyway… Don’t be dumb. Plagiarize
while (true) {
echo("Starting CB Websocket\n");
$timestamp = str(time());
$channel = 'ticker';
$symbols = ['BTC-USD', 'ETH-USD'];
$symbol_list = implode(',', $symbols);
$signature_string = "$timestamp$channel$symbol_list";
$signature = hash_hmac('sha256', utf8_encode($signature_string), utf8_encode('YOUR SECRET'), false);
$client = new Client("wss://advanced-trade-ws.coinbase.com:443");
$subscribe = [
'type' => 'subscribe',
'channel' => $channel,
'api_key' => 'YOUR API',
'product_ids' => $symbol_array,
'signature' => $signature,
'timestamp' => $timestamp,
];
$json = json_encode($subscribe);
$client->text($json);
while($client){
try {
$message = $client->receive();
if ($message) {
$json_message = json_decode($message, true);
# We can have events without an event... Makes total sense.
if (!isset($json_message['events'])) {
continue;
}
foreach ($json_message['events'] as $event) {
# Because why the **** not... this doesn't have to be here for some reason
if (!isset($event['tickers'])) {
continue;
}
foreach ($event['tickers'] as $ticker) {
$symbol = str_replace("-", "/", $ticker['product_id']);
$price = $ticker['price'];
# Did you know that sometimes a ticker can return with all the information, but a null price? Yup...
if (! $price) {
continue;
}
## WHATEVER YOU WANT TO DO WITH THE PRICE AND SYMBOL ##
}
}
}
} catch (\WebSocket\ConnectionException $e) {
echo("Websocket disconnected. Restarting\n");
break;
}
}
sleep(5);
}