/
account.go
61 lines (52 loc) · 1.29 KB
/
account.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
package tdam
import (
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func (c *Client) GetAccounts() ([]*Account, error) {
token, err := c.TDAMToken()
if err != nil {
return nil, err
}
transport := &http.Transport{TLSClientConfig: &tls.Config{}}
client := &http.Client{Transport: transport}
req, err := http.NewRequest("GET", "https://api.tdameritrade.com/v1/accounts", nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
query := req.URL.Query()
query.Add("fields", "positions")
query.Add("fields", "orders")
req.URL.RawQuery = query.Encode()
resp, err := client.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
fmt.Printf("status %d: %s\n", resp.StatusCode, resp.Status)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
defer resp.Body.Close()
/*
dump, err := httputil.DumpResponse(resp, true)
fmt.Printf("%s\n", dump)
*/
var accounts []*Account
if err := json.NewDecoder(resp.Body).Decode(&accounts); err != nil {
return nil, err
}
for _, a := range accounts {
a.Client = c
for _, p := range a.RawPositions {
if err := p.Instrument.populateFromSymbol(); err != nil {
fmt.Printf("error populating instrument: %v", err)
}
}
}
return accounts, nil
}