alpacahq / alpaca-ts

A TypeScript Node.js library for the https://alpaca.markets REST API and WebSocket streams.
ISC License
154 stars 42 forks source link

Stream.onAuthentication #25

Closed drixie closed 3 years ago

drixie commented 3 years ago

Again, thanks for the great job you did on this library.

I ran this code

stream.subscribe(["AM_SPY"]); stream.on("aggregate_minute", function (message) { console.log(message); });

and got this error after which I got "Connected to websocket" in the console: Error: You can't send a message until you are authenticated!

Is it possible to have an event that fires upon authentication? Alternatively, I will like to see how to get around this in a Readme sample code.

drixie commented 3 years ago

I know I can use setTimeout, but that doesn't feel right.

I also can't use await because "new AlpacaStream" which handles authentication, is an object instantiation.

drixie commented 3 years ago

I realized I can still access the underlying ws object, so I will use stream.on("message") to filter for authorization stream and its current status.

But it will be nice to have a stream.onAuthentication event abstraction in this package's API. I am fairly new to JS, don't know anything about TS, otherwise I would submit a PR.

117 commented 3 years ago

There is an authenticated event already built in, use it like this:

let stream = new AlpacaStream({
  credentials: {
    key: '***',
    secret: '***',
  },
  stream: 'account',
})

stream.on('authenticated', () => {
  console.log('successfully authenticated')
})
117 commented 3 years ago

Also I agree with you that there should be more example code in the README or its own folder. 🙂