Using Javascript, I’m able to successfully query Alpaca Market Data from ‘https://data.alpaca.markets/v1’ with fetch(). I’m now trying to implement websocket streaming using Socket.IO, but I keep getting 404 errors with whatever I try.
The code I’m using:
var url = 'wss://data.alpaca.markets/stream';
var params = {
'action': 'authenticate',
'data': {
'key_id': ALPACA_API_KEY_ID,
'secret_key': ALPACA_API_SECRET_KEY
}
}
For the actual connection event I’ve tried all of the following, because I’m not entirely sure how I’m supposed to be passing the handshake data. Each of the following returns a 404 error:
var socket = io(url);
var socket = io(url, { query: params });
var socket = io(url, { query: JSON.stringify(params) });
I’ve tried a number of other tweaks to various things in an attempt to get it to work, but every response I get is a 404. Any help on troubleshooting this is appreciated. I know there’s an Alpaca JS library that could be used, but I’d like to get this working without that, if possible.
The code below should get you connected without the need for any third party libraries.
var url = 'wss://data.alpaca.markets/stream';
var request = {
'action': 'authenticate',
'data': {
'key_id': YOUR_API_KEY_ID,
'secret_key': YOUR_API_SECRET_KEY
}
};
var socket = new WebSocket(url);
socket.onerror = function(event) {
throw Error('Websocket connection error');
};
socket.onopen = function(event) {
// Send handshake data
socket.send(JSON.stringify(request));
};
socket.onmessage = function(event) {
let msg = JSON.parse(event.data);
console.log(msg);
switch(msg.stream) {
case 'authorization':
if (msg.data.status === 'authorized') {
// Connected and ready for subsequent messages
console.log('Connected');
}
else if (msg.data.status === 'unauthorized') {
throw Error('Websocket error: ' + msg.data.error);
}
break;
case 'listening':
if (msg.data.error) {
throw Error('Websocket error: ' + msg.data.error);
}
else {
// Everything's OK and we should now be streaming
}
break;
default:
// Whatever code you want to use to process the data in 'msg.data'
break;
};
Also, once you’re connected, you can request to start listening by doing (this would be for getting minute bars):
Sorry for unclear question Erik. I am streaming now, but it is streaming like below, I cannot find actual candle data. And than you again for your help!
It might be the symbol you’re using, then. I get the same thing when I try streaming ‘AM.YI’… try ‘AM.AAPL’ just for testing purposes. If that works for you, then it’s the symbol. I’m not familiar with ‘YI’, but one thing to keep in mind is that Alpaca only feeds data for stocks that are traded on US exchanges. So if ‘YI’ is traded only outside of the US, then you won’t be able to get data for it through this API.