-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcoincap.go
More file actions
209 lines (180 loc) · 4.29 KB
/
Copy pathcoincap.go
File metadata and controls
209 lines (180 loc) · 4.29 KB
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
package coincap
import (
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"strconv"
"time"
"github.com/gorilla/websocket"
)
//
// https://docs.coincap.io
//
// https://api.coincap.io/v2
//
// DefaultClient is the default client.
var DefaultClient = NewClient(nil, nil)
// NewClient creates new CoinCap client.
func NewClient(httpClient *http.Client, wsDialer *websocket.Dialer) Client {
if httpClient == nil {
httpClient = http.DefaultClient
}
if wsDialer == nil {
wsDialer = websocket.DefaultDialer
}
return Client{httpClient, wsDialer}
}
// Client gives access to CoinCap API.
type Client struct {
http *http.Client
ws *websocket.Dialer
}
func request[T any](c *Client, endpoint string, query url.Values) (T, Timestamp, error) {
resp, err := c.http.Do(&http.Request{
Method: http.MethodGet,
URL: &url.URL{
Scheme: "https",
Host: "api.coincap.io",
Path: "/v2/" + endpoint,
RawQuery: query.Encode(),
},
})
if err != nil {
var t T
return t, 0, err
}
defer resp.Body.Close()
r, err := decodeJSON[struct {
Data T `json:"data"`
Timestamp Timestamp `json:"timestamp"`
}](resp.Body)
if err != nil {
var t T
return t, 0, errors.New("coincap (" + resp.Status + "): " + err.Error())
}
return r.Data, r.Timestamp, nil
}
func decodeJSON[T any](r io.Reader) (*T, error) {
dec := json.NewDecoder(r)
var v T
err := dec.Decode(&v)
if err != nil {
b, _ := io.ReadAll(io.MultiReader(dec.Buffered(), r))
return nil, errors.New(err.Error() + "\n" + string(b))
}
return &v, nil
}
// Timestamp represents CoinCap timestamp
// (UNIX time in milliseconds).
type Timestamp int64
// Time converts CoinCap timestamp into local time.
func (t Timestamp) Time() time.Time {
return time.Unix(0, int64(t)*1e6)
}
func (t Timestamp) String() string {
return strconv.FormatInt(int64(t), 10)
}
// Interval type.
type Interval uint8
// Valid Intervals for historical market data
// Used when requesting Asset History and Candles
const (
Hour Interval = iota
Minute
FiveMinutes
FifteenMinutes
ThirtyMinutes
TwoHours
SixHours
TwelveHours
Day
FourHours
EightHours
Week
)
func (i Interval) data() (string, time.Duration, bool) {
switch i {
case Hour:
return "h1", time.Hour, false
case Minute:
return "m1", time.Minute, false
case FiveMinutes:
return "m5", 5 * time.Minute, false
case FifteenMinutes:
return "m15", 15 * time.Minute, false
case ThirtyMinutes:
return "m30", 30 * time.Minute, false
case TwoHours:
return "h2", 2 * time.Hour, false
case SixHours:
return "h6", 6 * time.Hour, false
case TwelveHours:
return "h12", 12 * time.Hour, false
case Day:
return "d1", 24 * time.Hour, false
case FourHours:
return "h4", 4 * time.Hour, true
case EightHours:
return "h8", 8 * time.Hour, true
case Week:
return "w1", 7 * 24 * time.Hour, true
}
return "", 0, false
}
// interval errors.
var (
ErrInvalidInterval = errors.New("invalid interval")
ErrInvalidTimeSpan = errors.New("invalid time span")
ErrIntervalBigger = errors.New("invalid interval: bigger then time span")
)
func utoa(num uint) string {
return strconv.FormatUint(uint64(num), 10)
}
// TrimParams contains limit and offset parameters.
type TrimParams struct {
Limit uint // maximum number of results.
Offset uint // skip the first N entries of the result set.
}
func (p *TrimParams) setTo(v *url.Values) {
if p == nil {
return
}
if p.Limit != 0 {
if p.Limit > 2000 {
p.Limit = 2000
}
v.Set("limit", utoa(p.Limit))
}
if p.Offset != 0 {
v.Set("offset", utoa(p.Offset))
}
}
// IntervalParams contains interval and time span parameters.
type IntervalParams struct {
Interval Interval // point-in-time interval.
Start time.Time // start time.
End time.Time // end time.
}
func (p *IntervalParams) setTo(v *url.Values, candles bool) error {
if p == nil {
p = &IntervalParams{}
}
str, dur, ext := p.Interval.data()
if ext && !candles || str == "" {
return ErrInvalidInterval
}
v.Set("interval", str)
if p.Start.IsZero() && p.End.IsZero() {
return nil
}
if span := p.End.Sub(p.Start); span < 0 || p.Start.IsZero() || p.End.After(time.Now()) {
return ErrInvalidTimeSpan
} else if span < dur {
return ErrIntervalBigger
}
v.Set("start", Timestamp(p.Start.UnixMilli()).String())
v.Set("end", Timestamp(p.End.UnixMilli()).String())
return nil
}