Skip to content

Commit

Permalink
Merge pull request #52 from alpacahq/feature/websocket-connect-failure
Browse files Browse the repository at this point in the history
Add delayed reconnects on socket open failures
  • Loading branch information
ttt733 authored Sep 5, 2019
2 parents a53685a + f8be3e4 commit 52fcd94
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 13 deletions.
20 changes: 16 additions & 4 deletions alpaca/stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ const (
AccountUpdates = "account_updates"
)

const (
MaxConnectionAttempts = 3
)

var (
once sync.Once
str *Stream
Expand Down Expand Up @@ -217,9 +221,17 @@ func openSocket() *websocket.Conn {
scheme = "ws"
}
u := url.URL{Scheme: scheme, Host: ub.Host, Path: "/stream"}
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
panic(err)
connectionAttempts := 0
for connectionAttempts < MaxConnectionAttempts {
connectionAttempts++
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err == nil {
return c
}
if connectionAttempts == MaxConnectionAttempts {
panic(err)
}
time.Sleep(1 * time.Second)
}
return c
panic(fmt.Errorf("Error: Could not open Alpaca stream (max retries exceeded)."))
}
30 changes: 21 additions & 9 deletions polygon/stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ const (
Quotes = "Q"
)

const (
MaxConnectionAttempts = 3
)

var (
once sync.Once
str *Stream
Expand Down Expand Up @@ -238,14 +242,22 @@ func openSocket() *websocket.Conn {
if !ok {
polygonStreamEndpoint = "wss://alpaca.socket.polygon.io/stocks"
}
c, _, err := websocket.DefaultDialer.Dial(polygonStreamEndpoint, nil)
if err != nil {
panic(err)
}
// read connection message
msg := []PolgyonServerMsg{}
if err = c.ReadJSON(&msg); err != nil {
panic(err)
connectionAttempts := 0
for connectionAttempts < MaxConnectionAttempts {
connectionAttempts++
c, _, err := websocket.DefaultDialer.Dial(polygonStreamEndpoint, nil)
if err != nil {
if connectionAttempts == MaxConnectionAttempts {
panic(err)
}
} else {
// consume connection message
msg := []PolgyonServerMsg{}
if err = c.ReadJSON(&msg); err != nil {
return c
}
}
time.Sleep(1 * time.Second)
}
return c
panic(fmt.Errorf("Error: Could not open Polygon stream (max retries exceeded)."))
}

0 comments on commit 52fcd94

Please sign in to comment.