Open Websocket and Subscribe to Stream, Step 2


PHOTO EMBED

Wed Dec 09 2020 20:47:23 GMT+0000 (UTC)

Saved by @sam

// alpaca-api.js

// Import Libraries and set up Stream endpoint here (Step 1) ✅

// 1. Define a function for Websocket Instantiation
const alpacaOpenStream = () => {
  const options = {
    WebSocket,
    maxRetries: 100,
  };
// this creates the Reconnecting Websocket, it will be passed in proceeding steps
  const ws = new ReconnectingWebSocket(ALPACA_STREAM_URL, [], options);
  return ws;
};
// 2. Define a function for Alpaca /stream Authentication
const alpacaSubscribeAuth = async (ws, access_token) => {
  ws.send(
    JSON.stringify({
      action: 'authenticate',
      data: {
        oauth_token: access_token,
      },
     })
    );
  };
// 3. Define a function for subscribing to the Alpaca 'trade_updates' stream
const alpacaSubscribeToTrades = (ws) => {
  ws.send(
    JSON.stringify({
      action: 'listen',
      data: {
      streams: ['trade_updates'],
      },
    })
  );
};
content_copyCOPY