Comments (3)
Also have the same error which is crash my application every day. Error log:
10:14:07.773 DEBUG \fusion\libs\alpaca\src\lib\AlpacaService.ts:42 Alpaca Status: connecting
Error: WebSocket is not open: readyState 0 (CONNECTING)
at WebSocket.ping (C:\www\fusion\node_modules\@alpacahq\alpaca-trade-api\node_modules\ws\lib\websocket.js:323:13)
at AlpacaStocksClient.ping (C:\www\fusion\node_modules\@alpacahq\alpaca-trade-api\dist\resources\datav2\websocket.js:159:19)
at Timeout._onTimeout (C:\www\fusion\node_modules\@alpacahq\alpaca-trade-api\dist\resources\datav2\websocket.js:128:18)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)
10:14:19.608 DEBUG \fusion\libs\alpaca\src\lib\AlpacaService.ts:42 Alpaca Status: authenticating
10:14:19.612 DEBUG \fusion\libs\alpaca\src\lib\AlpacaService.ts:42 Alpaca Status: connected
10:14:19.819 DEBUG \fusion\libs\alpaca\src\lib\AlpacaService.ts:42 Alpaca Status: authenticated
10:14:19.821 INFO \fusion\libs\alpaca\src\lib\AlpacaService.ts:113 Alpaca Subscribe quotes
Exit...
My code:
this.alpacaClient = new Alpaca({
dataStreamUrl: 'wss://stream.data.alpaca.markets',
keyId: process.env.NX_APCA_API_KEY_ID,
secretKey: process.env.NX_APCA_API_SECRET_KEY,
paper: true,
feed: 'sip',
apiVersion: 2,
})
const websocket = this.alpacaClient.data_stream_v2
websocket.onStateChange((state) => {
this._alpacaState = state
alpacaLogger.debug('Status: ' + state)
if (state === STATE.AUTHENTICATED) {
this.subscribeQuotes()
this.subscribeTrades()
}
})
websocket.onError((err) => {
alpacaLogger.debug('Error:' + err, 'hidden')
})
websocket.onConnect(() => {
console.log('Alpaca connected!')
})
websocket.onStockQuote((quote) => {
....
})
websocket.onDisconnect(() => {
alpacaLogger.debug('Disconnected...')
})
websocket.connect()
from alpaca-trade-api-js.
Can you add a code snippet on how you connect the WebSocket and also when/how you subscribe to stuff ?
ItΒ΄s not intended to simply run the JS file with Node, this is not actually a binary or standalone application but rather a library which should be used in context of code.
Also, the error indicates that you should only send subscriptions once the websocket is actually connected which can be determined by the "onConnect" function, eg:
function initAlpaca() {
// Setup alpaca
let alpaca = new Alpaca({
keyId: 'PK...',
secretKey: 'EQ...',
paper: true,
})
// Get websocket for stock data
const stockStream = alpaca.data_stream_v2;
// Log errors
stockStream.onError(e => console.log(e))
// Run this function to execute stuff once connected, for instance subscribe to bars etc.
stockStream.onConnect(() => {
console.log("Alpaca connected!")
stockStream.subscribeForBars(["TSLA"])
})
// Process streamed data
stockStream.onStockBar(bar => console.log(bar))
// Trigger the websocket to connect
stockStream.connect()
}
from alpaca-trade-api-js.
I'm just messing around with the node_modules right now, it looks like changing this code (from "node_modules\@alpacahq\alpaca-trade-api\dist\resources\datav2\websocket.js"
in the following way resolves things. I say looks like because there are some other unchecked calls that I'm seeing, such as conn.ping()
, so probably a similar change needs to be made wherever the error comes up.
Old:
authenticate() {
const authMsg = {
action: "auth",
key: this.session.apiKey,
secret: this.session.secretKey,
};
this.conn.send(this.msgpack.encode(authMsg));
this.emit(STATE.AUTHENTICATING);
this.session.currentState = STATE.AUTHENTICATING;
}
New:
authenticate() {
const authMsg = {
action: "auth",
key: this.session.apiKey,
secret: this.session.secretKey,
};
if (this.conn.readyState == this.conn.OPEN){ // Check the socket state before calling send in case of a disconnect after the last 'open' emission
this.conn.send(this.msgpack.encode(authMsg));
this.emit(STATE.AUTHENTICATING);
this.session.currentState = STATE.AUTHENTICATING;
}
}
It seems like, somehow, the socket has disconnected between emission of the OPEN
state and the call to authenticate()
. An authenticate()
call is registered as a callback for the OPEN
state when you call connect()
.
I think there's a better way of doing this which doesn't involve constantly checking the websocket state, and instead just properly handling the disconnect instead by cancelling any pending authorization or pings or whatever else. However, I know next to nothing about this project's internals, so this is the best I have.
from alpaca-trade-api-js.
Related Issues (20)
- [Question]: Max number of bars returned from getBarsV2 HOT 1
- [Bug]: getBarsV2 returns AlpacaBar objects without symbols HOT 1
- getSnapshot previous close price discrepancy[Bug]:
- [Question]: page_token is null instead of empty string HOT 2
- [Question]: What replaced Alpaca.getAggregates()? HOT 1
- [Question]: Is there a way to call the Announcement functions? HOT 1
- [Bug]: importing alpaca-trade-api in react HOT 2
- [Bug]: WebSocket is not open: readyState 0 (CONNECTING)'
- [Bug]: Update Node deps / NodeJS14 -> 18
- [Bug]: getLatestCryptoQuote is not a function HOT 1
- [Question]: Why does order.getAll not take all params? HOT 1
- [Bug]: DataV2 `pageLimit` not respected when `limit` is not specified HOT 1
- [Question]: How to Take Profit and set Stop Loss HOT 1
- [Bug]: Cannot open bracket order starting with sell stop
- [Bug]: GetNewsParams->includeContent should be include_content HOT 2
- [Bug]: Date precision
- Support intraday_reporting on getPortfolioHistory
- [Question]: Has getCryptoBars() been replaced by getLatestCryptoBars() ? HOT 1
- [Bug]: Status Code 422 for createOrder
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. πππ
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google β€οΈ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from alpaca-trade-api-js.