-
-
Notifications
You must be signed in to change notification settings - Fork 283
/
public.go
322 lines (259 loc) · 6.86 KB
/
public.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
package max
import (
"fmt"
"io/ioutil"
"net/url"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
"github.com/valyala/fastjson"
"github.com/c9s/bbgo/pkg/types"
)
type PublicService struct {
client *RestClient
}
type Market struct {
ID string `json:"id"`
Name string `json:"name"`
BaseUnit string `json:"base_unit"`
BaseUnitPrecision int `json:"base_unit_precision"`
QuoteUnit string `json:"quote_unit"`
QuoteUnitPrecision int `json:"quote_unit_precision"`
MinBaseAmount float64 `json:"min_base_amount"`
MinQuoteAmount float64 `json:"min_quote_amount"`
}
type Ticker struct {
Time time.Time
At int64 `json:"at"`
Buy string `json:"buy"`
Sell string `json:"sell"`
Open string `json:"open"`
High string `json:"high"`
Low string `json:"low"`
Last string `json:"last"`
Volume string `json:"vol"`
VolumeInBTC string `json:"vol_in_btc"`
}
func (s *PublicService) Timestamp() (serverTimestamp int64, err error) {
// sync timestamp with server
req, err := s.client.newRequest("GET", "v2/timestamp", nil, nil)
if err != nil {
return 0, err
}
response, err := s.client.sendRequest(req)
if err != nil {
return 0, err
}
err = response.DecodeJSON(&serverTimestamp)
if err != nil {
return 0, err
}
return serverTimestamp, nil
}
func (s *PublicService) Markets() ([]Market, error) {
req, err := s.client.newRequest("GET", "v2/markets", url.Values{}, nil)
if err != nil {
return nil, err
}
response, err := s.client.sendRequest(req)
if err != nil {
return nil, err
}
var m []Market
if err := response.DecodeJSON(&m); err != nil {
return nil, err
}
return m, nil
}
func (s *PublicService) Tickers() (map[string]Ticker, error) {
var endPoint = "v2/tickers"
req, err := s.client.newRequest("GET", endPoint, url.Values{}, nil)
if err != nil {
return nil, err
}
response, err := s.client.sendRequest(req)
if err != nil {
return nil, err
}
v, err := fastjson.ParseBytes(response.Body)
if err != nil {
return nil, err
}
o, err := v.Object()
if err != nil {
return nil, err
}
var tickers = make(map[string]Ticker)
o.Visit(func(key []byte, v *fastjson.Value) {
var ticker = mustParseTicker(v)
tickers[string(key)] = ticker
})
return tickers, nil
}
func (s *PublicService) Ticker(market string) (*Ticker, error) {
var endPoint = "v2/tickers/" + market
req, err := s.client.newRequest("GET", endPoint, url.Values{}, nil)
if err != nil {
return nil, err
}
response, err := s.client.sendRequest(req)
if err != nil {
return nil, err
}
v, err := fastjson.ParseBytes(response.Body)
if err != nil {
return nil, err
}
var ticker = mustParseTicker(v)
return &ticker, nil
}
func mustParseTicker(v *fastjson.Value) Ticker {
var at = v.GetInt64("at")
return Ticker{
Time: time.Unix(at, 0),
At: at,
Buy: string(v.GetStringBytes("buy")),
Sell: string(v.GetStringBytes("sell")),
Volume: string(v.GetStringBytes("vol")),
VolumeInBTC: string(v.GetStringBytes("vol_in_btc")),
Last: string(v.GetStringBytes("last")),
Open: string(v.GetStringBytes("open")),
High: string(v.GetStringBytes("high")),
Low: string(v.GetStringBytes("low")),
}
}
type Interval int64
func ParseInterval(a string) (Interval, error) {
switch strings.ToLower(a) {
case "1m":
return 1, nil
case "5m":
return 5, nil
case "15m":
return 15, nil
case "30m":
return 30, nil
case "1h":
return 60, nil
case "2h":
return 60 * 2, nil
case "3h":
return 60 * 3, nil
case "4h":
return 60 * 4, nil
case "6h":
return 60 * 6, nil
case "8h":
return 60 * 8, nil
case "12h":
return 60 * 12, nil
case "1d":
return 60 * 24, nil
case "3d":
return 60 * 24 * 3, nil
case "1w":
return 60 * 24 * 7, nil
}
return 0, fmt.Errorf("incorrect resolution: %q", a)
}
type KLine struct {
Symbol string
Interval string
StartTime, EndTime time.Time
Open, High, Low, Close float64
Volume float64
Closed bool
}
func (k KLine) KLine() types.KLine {
return types.KLine{
Exchange: "max",
Symbol: strings.ToUpper(k.Symbol), // global symbol
Interval: types.Interval(k.Interval),
StartTime: k.StartTime,
EndTime: k.EndTime,
Open: k.Open,
Close: k.Close,
High: k.High,
Low: k.Low,
Volume: k.Volume,
// QuoteVolume: util.MustParseFloat(k.QuoteAssetVolume),
// LastTradeID: 0,
// NumberOfTrades: k.TradeNum,
Closed: k.Closed,
}
}
func (s *PublicService) KLines(symbol string, resolution string, start time.Time, limit int) ([]KLine, error) {
queries := url.Values{}
queries.Set("market", symbol)
interval, err := ParseInterval(resolution)
if err != nil {
return nil, err
}
queries.Set("period", strconv.Itoa(int(interval)))
nilTime := time.Time{}
if start != nilTime {
queries.Set("timestamp", strconv.FormatInt(start.Unix(), 10))
}
if limit > 0 {
queries.Set("limit", strconv.Itoa(limit)) // default to 30, max limit = 10,000
}
req, err := s.client.newRequest("GET", fmt.Sprintf("%s/k", s.client.BaseURL), queries, nil)
if err != nil {
return nil, fmt.Errorf("request build error: %s", err.Error())
}
resp, err := s.client.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %s", err.Error())
}
defer func() {
if err := resp.Body.Close(); err != nil {
logger.WithError(err).Error("failed to close resp body")
}
}()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return parseKLines(body, symbol, resolution, interval)
}
func parseKLines(payload []byte, symbol, resolution string, interval Interval) (klines []KLine, err error) {
var parser fastjson.Parser
v, err := parser.ParseBytes(payload)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse payload: %s", payload)
}
arr, err := v.Array()
if err != nil {
return nil, errors.Wrapf(err, "failed to get array: %s", payload)
}
for _, x := range arr {
slice, err := x.Array()
if err != nil {
return nil, errors.Wrapf(err, "failed to get array: %s", payload)
}
if len(slice) < 6 {
return nil, fmt.Errorf("unexpected length of ohlc elements: %s", payload)
}
ts, err := slice[0].Int64()
if err != nil {
return nil, fmt.Errorf("failed to parse timestamp: %s", payload)
}
startTime := time.Unix(ts, 0)
endTime := time.Unix(ts, 0).Add(time.Duration(interval)*time.Minute - time.Millisecond)
isClosed := time.Now().Before(endTime)
klines = append(klines, KLine{
Symbol: symbol,
Interval: resolution,
StartTime: startTime,
EndTime: endTime,
Open: slice[1].GetFloat64(),
High: slice[2].GetFloat64(),
Low: slice[3].GetFloat64(),
Close: slice[4].GetFloat64(),
Volume: slice[5].GetFloat64(),
Closed: isClosed,
})
}
return klines, nil
}