-
Notifications
You must be signed in to change notification settings - Fork 34
/
watchlists.go
70 lines (59 loc) · 1.51 KB
/
watchlists.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package robinhood
import (
"context"
"golang.org/x/sync/errgroup"
)
// A Watchlist is a list of stock Instruments that an investor is tracking in
// his Robinhood portfolio/app.
type Watchlist struct {
Name string `json:"name"`
URL string `json:"url"`
User string `json:"user"`
Client *Client `json:",ignore"`
}
// GetWatchlists retrieves the watchlists for a given set of credentials/accounts.
func (c *Client) GetWatchlists(ctx context.Context) ([]Watchlist, error) {
var r struct{ Results []Watchlist }
err := c.GetAndDecode(ctx, EPWatchlists, &r)
if err != nil {
return nil, err
}
if r.Results != nil {
for i := range r.Results {
r.Results[i].Client = c
}
}
return r.Results, nil
}
// GetInstruments returns the list of Instruments associated with a Watchlist.
func (w *Watchlist) GetInstruments(ctx context.Context) ([]Instrument, error) {
var r struct {
Results []struct {
Instrument, URL string
}
}
err := w.Client.GetAndDecode(ctx, w.URL, &r)
if err != nil {
return nil, err
}
insts := make([]*Instrument, len(r.Results))
eg, ctx := errgroup.WithContext(ctx)
for i := range r.Results {
// shadow for safe closure access
i := i
eg.Go(func() error {
inst, err := w.Client.GetInstrument(ctx, r.Results[i].Instrument)
insts[i] = inst
return err
})
}
err = eg.Wait()
// Filter slice for empties (if error)
retInsts := make([]Instrument, 0, len(r.Results))
for _, inst := range insts {
if inst != nil {
retInsts = append(retInsts, *inst)
}
}
return retInsts, err
}