-
-
Notifications
You must be signed in to change notification settings - Fork 272
/
client.go
256 lines (205 loc) · 5.51 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
package binanceapi
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"crypto/tls"
"encoding/json"
"fmt"
"net"
"net/http"
"net/url"
"strconv"
"time"
"github.com/c9s/requestgen"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/c9s/bbgo/pkg/types"
)
const defaultHTTPTimeout = time.Second * 10
const RestBaseURL = "https://api.binance.com"
const DebugRequestResponse = false
var dialer = &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}
var defaultTransport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: dialer.DialContext,
MaxIdleConns: 100,
MaxConnsPerHost: 100,
MaxIdleConnsPerHost: 100,
// TLSNextProto: make(map[string]func(string, *tls.Conn) http.RoundTripper),
ExpectContinueTimeout: 0,
ForceAttemptHTTP2: true,
TLSClientConfig: &tls.Config{},
}
var DefaultHttpClient = &http.Client{
Timeout: defaultHTTPTimeout,
Transport: defaultTransport,
}
type RestClient struct {
requestgen.BaseAPIClient
Key, Secret string
recvWindow int
timeOffset int64
}
func NewClient(baseURL string) *RestClient {
if len(baseURL) == 0 {
baseURL = RestBaseURL
}
u, err := url.Parse(baseURL)
if err != nil {
panic(err)
}
client := &RestClient{
BaseAPIClient: requestgen.BaseAPIClient{
BaseURL: u,
HttpClient: DefaultHttpClient,
},
}
// client.AccountService = &AccountService{client: client}
return client
}
func (c *RestClient) Auth(key, secret string) {
c.Key = key
// pragma: allowlist nextline secret
c.Secret = secret
}
// NewRequest create new API request. Relative url can be provided in refURL.
func (c *RestClient) NewRequest(ctx context.Context, method, refURL string, params url.Values, payload interface{}) (*http.Request, error) {
rel, err := url.Parse(refURL)
if err != nil {
return nil, err
}
if params != nil {
rel.RawQuery = params.Encode()
}
body, err := castPayload(payload)
if err != nil {
return nil, err
}
pathURL := c.BaseURL.ResolveReference(rel)
return http.NewRequestWithContext(ctx, method, pathURL.String(), bytes.NewReader(body))
}
func (c *RestClient) SetTimeOffsetFromServer(ctx context.Context) error {
req, err := c.NewRequest(ctx, "GET", "/api/v3/time", nil, nil)
if err != nil {
return err
}
resp, err := c.SendRequest(req)
if err != nil {
return err
}
var a struct {
ServerTime types.MillisecondTimestamp `json:"serverTime"`
}
err = resp.DecodeJSON(&a)
if err != nil {
return err
}
c.timeOffset = currentTimestamp() - a.ServerTime.Time().UnixMilli()
return nil
}
func (c *RestClient) SendRequest(req *http.Request) (*requestgen.Response, error) {
if DebugRequestResponse {
logrus.Debugf("-> request: %+v", req)
response, err := c.BaseAPIClient.SendRequest(req)
logrus.Debugf("<- response: %s", string(response.Body))
return response, err
}
return c.BaseAPIClient.SendRequest(req)
}
// newAuthenticatedRequest creates new http request for authenticated routes.
func (c *RestClient) NewAuthenticatedRequest(ctx context.Context, method, refURL string, params url.Values, payload interface{}) (*http.Request, error) {
if len(c.Key) == 0 {
return nil, errors.New("empty api key")
}
if len(c.Secret) == 0 {
return nil, errors.New("empty api secret")
}
rel, err := url.Parse(refURL)
if err != nil {
return nil, err
}
if params == nil {
params = url.Values{}
}
if c.recvWindow > 0 {
params.Set("recvWindow", strconv.Itoa(c.recvWindow))
}
params.Set("timestamp", strconv.FormatInt(currentTimestamp()-c.timeOffset, 10))
rawQuery := params.Encode()
pathURL := c.BaseURL.ResolveReference(rel)
body, err := castPayload(payload)
if err != nil {
return nil, err
}
toSign := rawQuery + string(body)
signature := sign(c.Secret, toSign)
// sv is the extra url parameters that we need to attach to the request
sv := url.Values{}
sv.Set("signature", signature)
if rawQuery == "" {
rawQuery = sv.Encode()
} else {
rawQuery = rawQuery + "&" + sv.Encode()
}
if rawQuery != "" {
pathURL.RawQuery = rawQuery
}
req, err := http.NewRequestWithContext(ctx, method, pathURL.String(), bytes.NewReader(body))
if err != nil {
return nil, err
}
// if our payload body is not an empty string
if len(body) > 0 {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
req.Header.Add("Accept", "application/json")
// Build authentication headers
req.Header.Add("X-MBX-APIKEY", c.Key)
return req, nil
}
// sign uses sha256 to sign the payload with the given secret
func sign(secret, payload string) string {
var sig = hmac.New(sha256.New, []byte(secret))
_, err := sig.Write([]byte(payload))
if err != nil {
return ""
}
return fmt.Sprintf("%x", sig.Sum(nil))
}
func currentTimestamp() int64 {
return FormatTimestamp(time.Now())
}
// FormatTimestamp formats a time into Unix timestamp in milliseconds, as requested by Binance.
func FormatTimestamp(t time.Time) int64 {
return t.UnixNano() / int64(time.Millisecond)
}
func castPayload(payload interface{}) ([]byte, error) {
if payload != nil {
switch v := payload.(type) {
case string:
return []byte(v), nil
case []byte:
return v, nil
case map[string]interface{}:
var params = url.Values{}
for a, b := range v {
params.Add(a, fmt.Sprintf("%v", b))
}
return []byte(params.Encode()), nil
default:
body, err := json.Marshal(v)
return body, err
}
}
return nil, nil
}
type APIResponse struct {
Code string `json:"code"`
Message string `json:"msg"`
Data json.RawMessage `json:"data"`
}