-
Notifications
You must be signed in to change notification settings - Fork 223
/
client.go
371 lines (315 loc) · 7.94 KB
/
client.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package api
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"sort"
"strconv"
"strings"
"time"
v1 "github.com/alpacahq/marketstore/v4/contrib/alpacabkfeeder/api/v1"
"github.com/hashicorp/go-retryablehttp"
)
const (
rateLimitRetryCount = 3
rateLimitRetryDelay = time.Second
)
var (
// DefaultClient is the default Alpaca client using the
// environment variable set credentials.
DefaultClient = NewClient(Credentials())
base = "https://api.alpaca.markets"
dataURL = "https://data.alpaca.markets"
apiVersion = "v2"
clientTimeout = 10 * time.Second
// maximum number of retries
retryMax = 1
do = defaultDo
)
func defaultDo(c *Client, req *http.Request) (*http.Response, error) {
if c.credentials.OAuth != "" {
req.Header.Set("Authorization", "Bearer "+c.credentials.OAuth)
} else {
if c.credentials.AuthMethod == HeaderAuth {
req.Header.Set("APCA-API-KEY-ID", c.credentials.ID)
req.Header.Set("APCA-API-SECRET-KEY", c.credentials.Secret)
} else {
// default: Basic Auth
req.SetBasicAuth(c.credentials.ID, c.credentials.Secret)
}
}
retryClient := retryablehttp.NewClient()
retryClient.RetryMax = retryMax
client := retryClient.StandardClient() // *http.Client
client.Timeout = clientTimeout
var resp *http.Response
var err error
for i := 0; ; i++ {
resp, err = client.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusTooManyRequests {
break
}
if i >= rateLimitRetryCount {
break
}
time.Sleep(rateLimitRetryDelay)
}
if err = verify(resp); err != nil {
return nil, err
}
return resp, nil
}
const (
// v2MaxLimit is the maximum allowed limit parameter for all v2 endpoints.
v2MaxLimit = 10000
)
func init() {
if s := os.Getenv("APCA_API_BASE_URL"); s != "" {
base = s
} else if s := os.Getenv("ALPACA_BASE_URL"); s != "" {
// legacy compatibility...
base = s
}
if s := os.Getenv("APCA_DATA_URL"); s != "" {
dataURL = s
}
// also allow APCA_API_DATA_URL to be consistent with the python SDK
if s := os.Getenv("APCA_API_DATA_URL"); s != "" {
dataURL = s
}
if s := os.Getenv("APCA_API_VERSION"); s != "" {
apiVersion = s
}
if s := os.Getenv("APCA_API_CLIENT_TIMEOUT"); s != "" {
d, err := time.ParseDuration(s)
if err != nil {
log.Fatal("invalid APCA_API_CLIENT_TIMEOUT: " + err.Error())
}
clientTimeout = d
}
if s := os.Getenv("APCA_API_RETRY_MAX"); s != "" {
d, err := strconv.Atoi(s)
if err != nil {
log.Fatal("invalid APCA_API_RETRY_MAX: " + err.Error())
}
retryMax = d
}
}
// APIError wraps the detailed code and message supplied
// by Alpaca's API for debugging purposes.
type APIError struct {
Code int `json:"code"`
Message string `json:"message"`
}
func (e *APIError) Error() string {
return e.Message
}
// Client is an Alpaca REST API client.
type Client struct {
credentials *APIKey
}
type AuthMethod int
const (
BasicAuth = iota
HeaderAuth
)
func SetBaseUrl(baseUrl string) {
base = baseUrl
}
// NewClient creates a new Alpaca client with specified
// credentials.
func NewClient(credentials *APIKey) *Client {
return &Client{credentials: credentials}
}
// GetSnapshots returns the snapshots for multiple symbol.
func (c *Client) GetSnapshots(symbols []string) (map[string]*Snapshot, error) {
u, err := url.Parse(fmt.Sprintf("%s/v2/stocks/snapshots?symbols=%s",
dataURL, strings.Join(symbols, ",")))
if err != nil {
return nil, err
}
resp, err := c.get(u)
if err != nil {
return nil, err
}
var snapshots map[string]*Snapshot
if err = unmarshal(resp, &snapshots); err != nil {
return nil, err
}
return snapshots, nil
}
// GetMultiBars returns bars for the given symbols.
func (c *Client) GetMultiBars(
symbols []string, params GetBarsParams,
) (map[string][]Bar, error) {
bars := make(map[string][]Bar, len(symbols))
for item := range c.GetMultiBarsAsync(symbols, params) {
if err := item.Error; err != nil {
return nil, err
}
bars[item.Symbol] = append(bars[item.Symbol], item.Bar)
}
return bars, nil
}
// GetMultiBarsAsync returns a channel that will be populated with the bars for the requested symbols.
func (c *Client) GetMultiBarsAsync(symbols []string, params GetBarsParams) <-chan MultiBarItem {
ch := make(chan MultiBarItem)
go func() {
defer close(ch)
u, err := url.Parse(fmt.Sprintf("%s/v2/stocks/bars", dataURL))
if err != nil {
ch <- MultiBarItem{Error: err}
return
}
q := u.Query()
q.Set("symbols", strings.Join(symbols, ","))
setQueryBarParams(q, params, "")
received := 0
for params.TotalLimit == 0 || received < params.TotalLimit {
setQueryLimit(q, params.TotalLimit, params.PageLimit, received)
u.RawQuery = q.Encode()
resp, err := c.get(u)
if err != nil {
ch <- MultiBarItem{Error: err}
return
}
var barResp multiBarResponse
if err = unmarshal(resp, &barResp); err != nil {
ch <- MultiBarItem{Error: err}
return
}
sortedSymbols := make([]string, 0, len(barResp.Bars))
for symbol := range barResp.Bars {
sortedSymbols = append(sortedSymbols, symbol)
}
sort.Strings(sortedSymbols)
for _, symbol := range sortedSymbols {
bars := barResp.Bars[symbol]
for _, bar := range bars {
ch <- MultiBarItem{Symbol: symbol, Bar: bar}
}
received += len(bars)
}
if barResp.NextPageToken == nil {
return
}
q.Set("page_token", *barResp.NextPageToken)
}
}()
return ch
}
func setQueryBarParams(q url.Values, params GetBarsParams, feed string) {
setBaseQuery(q, params.Start, params.End, params.Feed, feed)
adjustment := Raw
if params.Adjustment != "" {
adjustment = params.Adjustment
}
q.Set("adjustment", string(adjustment))
timeframe := OneDay
if params.TimeFrame.N != 0 {
timeframe = params.TimeFrame
}
q.Set("timeframe", timeframe.String())
}
func setBaseQuery(q url.Values, start, end time.Time, feed, defaultFeed string) {
if !start.IsZero() {
q.Set("start", start.Format(time.RFC3339))
}
if !end.IsZero() {
q.Set("end", end.Format(time.RFC3339))
}
if feed != "" {
q.Set("feed", feed)
} else {
if defaultFeed != "" {
q.Set("feed", feed)
}
}
}
func setQueryLimit(q url.Values, totalLimit int, pageLimit int, received int) {
limit := 0 // use server side default if unset
if pageLimit != 0 {
limit = pageLimit
}
if totalLimit != 0 {
remaining := totalLimit - received
if remaining <= 0 { // this should never happen
return
}
if (limit == 0 || limit > remaining) && remaining <= v2MaxLimit {
limit = remaining
}
}
if limit != 0 {
q.Set("limit", fmt.Sprintf("%d", limit))
}
}
// ListAssets returns the list of assets, filtered by
// the input parameters.
func (c *Client) ListAssets(status *string) ([]v1.Asset, error) {
// TODO: add tests
apiVer := apiVersion
if strings.Contains(base, "broker") {
apiVer = "v1"
}
// TODO: support different asset classes
u, err := url.Parse(fmt.Sprintf("%s/%s/assets", base, apiVer))
if err != nil {
return nil, err
}
q := u.Query()
if status != nil {
q.Set("status", *status)
}
u.RawQuery = q.Encode()
resp, err := c.get(u)
if err != nil {
return nil, err
}
assets := []v1.Asset{}
if err = unmarshal(resp, &assets); err != nil {
return nil, err
}
return assets, nil
}
func (c *Client) get(u *url.URL) (*http.Response, error) {
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil {
return nil, err
}
return do(c, req)
}
func verify(resp *http.Response) (err error) {
if resp.StatusCode >= http.StatusMultipleChoices {
var body []byte
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
apiErr := APIError{}
err = json.Unmarshal(body, &apiErr)
if err != nil {
return fmt.Errorf("json unmarshal error: %s", err.Error())
}
if err == nil {
err = &apiErr
}
}
return
}
func unmarshal(resp *http.Response, data interface{}) error {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
return json.Unmarshal(body, data)
}