/
txhistory.go
93 lines (78 loc) · 2.15 KB
/
txhistory.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
package tdam
import (
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
func (a *Account) TradeHistoryCallback(symbol Symbol, start *time.Time, cb func(symbol Symbol, data []byte)) error {
token, err := a.TDAMToken()
if err != nil {
return err
}
transport := &http.Transport{TLSClientConfig: &tls.Config{}}
client := &http.Client{Transport: transport}
endpoint := fmt.Sprintf("https://api.tdameritrade.com/v1/accounts/%s/transactions", a.AccountId)
current := time.Now()
if current.Sub(*start) < 1*time.Hour {
fmt.Printf("%s less than an hour old, skipping\n", symbol)
return nil
}
for {
req, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
prevMonth := current.AddDate(0, -6, 0)
startTime := start
if startTime == nil || startTime.Before(prevMonth) {
startTime = &prevMonth
}
//fmt.Printf("%s: %s - %s\n", symbol, startTime, current)
query := req.URL.Query()
query.Add("type", "TRADE")
query.Add("symbol", string(symbol))
query.Add("startDate", startTime.Format("2006-01-02"))
query.Add("endDate", current.Format("2006-01-02"))
req.URL.RawQuery = query.Encode()
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return fmt.Errorf("status %d: %s\n", resp.StatusCode, resp.Status)
}
body, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
val := []interface{}{}
if err := json.Unmarshal(body, &val); err != nil {
return err
}
if len(val) == 0 && start == nil {
return nil
}
cb(symbol, body)
current = current.AddDate(0, -6, 0)
if start != nil && current.Before(*start) {
return nil
}
time.Sleep(100 * time.Millisecond)
}
return nil
}
func (a *Account) TradeHistory(symbol Symbol, start *time.Time) (out []Transaction, err error) {
out = []Transaction{}
a.TradeHistoryCallback(symbol, start, func(symbol Symbol, data []byte) {
var transactions []Transaction
//fmt.Printf("%s: %s\n", symbol, data)
if e := json.Unmarshal(data, &transactions); e != nil {
err = e
} else {
out = append(out, transactions...)
}
})
return
}