Parent function for Creating Websocket, and Listener Setup


PHOTO EMBED

Wed Dec 09 2020 22:08:40 GMT+0000 (UTC)

Saved by @sam

const createSocket = (access_token) => {
  // websocket setup
	const ws = alpacaOpenStream();
	
	ws.addEventListener('open', async function open() {
    // authenticate, then subscribe to trade_updates
    await alpacaSubscribeAuth(ws, access_token);
		alpacaSubscribeToTrades(ws);

		console.log('Opened ⚡️tream ⚡️ocket');
	});
	
	ws.addEventListener('message', function incoming(msg) {
		console.log('Message: 📬 ', JSON.parse(msg.data));
   		if (msg.stream === 'trade_updates' && msg.data.event === 'new') {
     		console.log('New Trade 💹: ', msg.data);
   		}
	});
	return ws;
};
// finally call the function!
createSocket(access_token);
content_copyCOPY