-
-
Notifications
You must be signed in to change notification settings - Fork 67
/
client.go
488 lines (400 loc) · 9.96 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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
package bybit
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"time"
)
const (
// MainNetBaseURL :
MainNetBaseURL = "https://api.bybit.com"
// MainNetBaseURL2 :
MainNetBaseURL2 = "https://api.bytick.com"
)
// Client :
type Client struct {
httpClient *http.Client
debug bool
logger *log.Logger
baseURL string
key string
secret string
referer string
checkResponseBody checkResponseBodyFunc
syncTimeDeltaNanoSeconds int64
}
func (c *Client) debugf(format string, v ...interface{}) {
if c.debug {
c.logger.Printf(format, v...)
}
}
// NewClient :
func NewClient() *Client {
return &Client{
httpClient: &http.Client{},
logger: newDefaultLogger(),
baseURL: MainNetBaseURL,
checkResponseBody: checkResponseBody,
}
}
// WithHTTPClient :
func (c *Client) WithHTTPClient(httpClient *http.Client) *Client {
c.httpClient = httpClient
return c
}
// WithDebug :
func (c *Client) WithDebug(debug bool) *Client {
c.debug = debug
return c
}
// WithLogger :
func (c *Client) WithLogger(logger *log.Logger) *Client {
c.debug = true
c.logger = logger
return c
}
// WithAuth :
func (c *Client) WithAuth(key string, secret string) *Client {
c.key = key
c.secret = secret
return c
}
func (c Client) withCheckResponseBody(f checkResponseBodyFunc) *Client {
c.checkResponseBody = f
return &c
}
// WithBaseURL :
func (c *Client) WithBaseURL(url string) *Client {
c.baseURL = url
return c
}
func (c *Client) WithReferer(referer string) *Client {
c.referer = referer
return c
}
// Request :
func (c *Client) Request(req *http.Request, dst interface{}) (err error) {
c.debugf("request: %v", req)
resp, err := c.httpClient.Do(req)
c.debugf("response: %v", resp)
if err != nil {
return err
}
c.debugf("response status code: %v", resp.StatusCode)
defer func() {
cerr := resp.Body.Close()
if err == nil && cerr != nil {
err = cerr
}
}()
switch {
case 200 <= resp.StatusCode && resp.StatusCode <= 299:
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
if c.checkResponseBody == nil {
return errors.New("checkResponseBody func should be set")
}
if err := c.checkResponseBody(body); err != nil {
return err
}
if err := json.Unmarshal(body, &dst); err != nil {
return err
}
c.debugf("response body: %v", string(body))
return nil
case resp.StatusCode == http.StatusBadRequest:
return fmt.Errorf("%v: Need to send the request with GET / POST (must be capitalized)", ErrBadRequest)
case resp.StatusCode == http.StatusUnauthorized:
return fmt.Errorf("%w: invalid key/secret", ErrInvalidRequest)
case resp.StatusCode == http.StatusForbidden:
return fmt.Errorf("%w: not permitted", ErrForbiddenRequest)
case resp.StatusCode == http.StatusNotFound:
return fmt.Errorf("%w: wrong path", ErrPathNotFound)
default:
return fmt.Errorf("unexpected status code %d", resp.StatusCode)
}
}
// hasAuth : check has auth key and secret
func (c *Client) hasAuth() bool {
return c.key != "" && c.secret != ""
}
func (c *Client) populateSignature(src url.Values) url.Values {
if src == nil {
src = url.Values{}
}
src.Add("api_key", c.key)
src.Add("timestamp", strconv.FormatInt(c.getTimestamp(), 10))
if c.referer != "" {
src.Add("referer", c.referer)
}
src.Add("sign", getSignature(src, c.secret))
return src
}
func (c *Client) populateSignatureForBody(src []byte) []byte {
body := map[string]interface{}{}
if err := json.Unmarshal(src, &body); err != nil {
panic(err)
}
body["api_key"] = c.key
body["timestamp"] = strconv.FormatInt(c.getTimestamp(), 10)
if c.referer != "" {
body["referer"] = c.referer
}
body["sign"] = getSignatureForBody(body, c.secret)
result, err := json.Marshal(body)
if err != nil {
panic(err)
}
return result
}
func getV5Signature(
timestamp int64,
key string,
queryString string,
secret string,
) string {
val := strconv.FormatInt(timestamp, 10) + key
val = val + queryString
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(val))
return hex.EncodeToString(h.Sum(nil))
}
func getV5SignatureForBody(
timestamp int64,
key string,
body []byte,
secret string,
) string {
val := strconv.FormatInt(timestamp, 10) + key
val = val + string(body)
h := hmac.New(sha256.New, []byte(secret))
h.Write([]byte(val))
return hex.EncodeToString(h.Sum(nil))
}
func getSignature(src url.Values, key string) string {
keys := make([]string, len(src))
i := 0
_val := ""
for k := range src {
keys[i] = k
i++
}
sort.Strings(keys)
for _, k := range keys {
_val += k + "=" + src.Get(k) + "&"
}
_val = _val[0 : len(_val)-1]
h := hmac.New(sha256.New, []byte(key))
_, err := io.WriteString(h, _val)
if err != nil {
panic(err)
}
return fmt.Sprintf("%x", h.Sum(nil))
}
func getSignatureForBody(src map[string]interface{}, key string) string {
keys := make([]string, len(src))
i := 0
_val := ""
for k := range src {
keys[i] = k
i++
}
sort.Strings(keys)
for _, k := range keys {
_val += k + "=" + fmt.Sprintf("%v", src[k]) + "&"
}
_val = _val[0 : len(_val)-1]
h := hmac.New(sha256.New, []byte(key))
_, err := io.WriteString(h, _val)
if err != nil {
panic(err)
}
return fmt.Sprintf("%x", h.Sum(nil))
}
func (c *Client) getPublicly(path string, query url.Values, dst interface{}) error {
u, err := url.Parse(c.baseURL)
if err != nil {
return err
}
u.Path = path
u.RawQuery = query.Encode()
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil {
return err
}
if err := c.Request(req, &dst); err != nil {
return err
}
return nil
}
func (c *Client) getPrivately(path string, query url.Values, dst interface{}) error {
if !c.hasAuth() {
return fmt.Errorf("this is private endpoint, please set api key and secret")
}
u, err := url.Parse(c.baseURL)
if err != nil {
return err
}
u.Path = path
query = c.populateSignature(query)
u.RawQuery = query.Encode()
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil {
return err
}
if err := c.Request(req, &dst); err != nil {
return err
}
return nil
}
func (c *Client) getV5Privately(path string, query url.Values, dst interface{}) error {
if !c.hasAuth() {
return fmt.Errorf("this is private endpoint, please set api key and secret")
}
u, err := url.Parse(c.baseURL)
if err != nil {
return err
}
u.Path = path
u.RawQuery = query.Encode()
timestamp := c.getTimestamp()
sign := getV5Signature(timestamp, c.key, query.Encode(), c.secret)
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil {
return err
}
req.Header.Set("X-BAPI-API-KEY", c.key)
req.Header.Set("X-BAPI-TIMESTAMP", strconv.FormatInt(timestamp, 10))
req.Header.Set("X-BAPI-SIGN", sign)
if err := c.Request(req, &dst); err != nil {
return err
}
return nil
}
func (c *Client) postJSON(path string, body []byte, dst interface{}) error {
if !c.hasAuth() {
return fmt.Errorf("this is private endpoint, please set api key and secret")
}
u, err := url.Parse(c.baseURL)
if err != nil {
return err
}
u.Path = path
body = c.populateSignatureForBody(body)
req, err := http.NewRequest(http.MethodPost, u.String(), bytes.NewBuffer(body))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
if err := c.Request(req, &dst); err != nil {
return err
}
return nil
}
func (c *Client) postV5JSON(path string, body []byte, dst interface{}) error {
if !c.hasAuth() {
return fmt.Errorf("this is private endpoint, please set api key and secret")
}
u, err := url.Parse(c.baseURL)
if err != nil {
return err
}
u.Path = path
timestamp := c.getTimestamp()
sign := getV5SignatureForBody(timestamp, c.key, body, c.secret)
req, err := http.NewRequest(http.MethodPost, u.String(), bytes.NewBuffer(body))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-BAPI-API-KEY", c.key)
req.Header.Set("X-BAPI-TIMESTAMP", strconv.FormatInt(timestamp, 10))
req.Header.Set("X-BAPI-SIGN", sign)
if c.referer != "" {
req.Header.Set("X-Referer", c.referer)
}
if err := c.Request(req, &dst); err != nil {
return err
}
return nil
}
func (c *Client) postForm(path string, body url.Values, dst interface{}) error {
if !c.hasAuth() {
return fmt.Errorf("this is private endpoint, please set api key and secret")
}
u, err := url.Parse(c.baseURL)
if err != nil {
return nil
}
u.Path = path
body = c.populateSignature(body)
req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(body.Encode()))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if err != nil {
return err
}
if err := c.Request(req, &dst); err != nil {
return err
}
return nil
}
func (c *Client) deletePrivately(path string, query url.Values, dst interface{}) error {
if !c.hasAuth() {
return fmt.Errorf("this is private endpoint, please set api key and secret")
}
u, err := url.Parse(c.baseURL)
if err != nil {
return err
}
u.Path = path
query = c.populateSignature(query)
u.RawQuery = query.Encode()
req, err := http.NewRequest(http.MethodDelete, u.String(), nil)
if err != nil {
return err
}
if err := c.Request(req, &dst); err != nil {
return err
}
return nil
}
func (c *Client) getTimestamp() int64 {
return (time.Now().UnixNano() - c.syncTimeDeltaNanoSeconds) / 1000000
}
func (c *Client) updateSyncTimeDelta(
remoteServerTimeRaw string,
localTimestampNanoseconds int64,
) error {
remoteServerTimeNS, err := strconv.ParseInt(remoteServerTimeRaw, 10, 64)
if err != nil {
return fmt.Errorf("parse server time: %w", err)
}
c.syncTimeDeltaNanoSeconds = localTimestampNanoseconds - remoteServerTimeNS
return nil
}
func (c *Client) SyncServerTime() error {
r, err := c.NewTimeService().GetServerTime()
if err != nil {
return fmt.Errorf("get server time: %w", err)
}
if r.Result.TimeNano == "" {
return errors.New("server time is empty")
}
return c.updateSyncTimeDelta(r.Result.TimeNano, time.Now().UnixNano())
}