-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient.go
More file actions
310 lines (251 loc) · 6.8 KB
/
client.go
File metadata and controls
310 lines (251 loc) · 6.8 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
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
package bingx
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"time"
"github.com/magicaleks/go-bingx/common"
)
// API Endpoints
const (
baseApiUrl = "https://open-api.bingx.com"
// baseTestApiUrl = "" Unactual
)
// Side type of order
type SideType string
// PositionSide type of order
type PositionSideType string
// Type of order
type OrderType string
type OrderStatus string
type OrderSpecType string
type OrderWorkingType string
const (
timestampKey = "timestamp"
signatureKey = "signature"
recvWindowKey = "recvWindow"
BuySideType SideType = "BUY"
SellSideType SideType = "SELL"
ShortPositionSideType PositionSideType = "SHORT"
LongPositionSideType PositionSideType = "LONG"
BothPositionSideType PositionSideType = "BOTH"
LimitOrderType OrderType = "LIMIT"
MarketOrderType OrderType = "MARKET"
NewOrderStatus OrderStatus = "NEW"
PartiallyFilledOrderStatus OrderStatus = "PARTIALLY_FILLED"
FilledOrderStatus OrderStatus = "FILLED"
CanceledOrderStatus OrderStatus = "CANCELED"
ExpiredOrderStatus OrderStatus = "EXPIRED"
NewOrderSpecType OrderSpecType = "NEW"
CanceledOrderSpecType OrderSpecType = "CANCELED"
CalculatedOrderSpecType OrderSpecType = "CALCULATED"
ExpiredOrderSpecType OrderSpecType = "EXPIRED"
TradeOrderSpecType OrderSpecType = "TRADE"
MarkOrderWorkingType OrderWorkingType = "MARK_PRICE"
ContractOrderWorkingType OrderWorkingType = "CONTRACT_PRICE"
IndexOrderWorkingType OrderWorkingType = "INDEX_PRICE"
)
type Interval string
const (
Interval1 Interval = "1m"
Interval3 Interval = "3m"
Interval5 Interval = "5m"
Interval15 Interval = "15m"
Interval30 Interval = "30m"
Interval60 Interval = "1h"
Interval2h Interval = "2h"
Interval4h Interval = "4h"
Interval6h Interval = "6h"
Interval8h Interval = "8h"
Interval12h Interval = "12h"
Interval1d Interval = "1d"
Interval3d Interval = "3d"
Interval1w Interval = "1w"
Interval1M Interval = "1M"
)
func getApiEndpoint() string {
return baseApiUrl
}
type doFunc func(*http.Request) (*http.Response, error)
// Client define API client
type Client struct {
APIKey string
SecretKey string
BaseURL string
UserAgent string
HTTPClient *http.Client
Debug bool
Logger *log.Logger
TimeOffset int64
do doFunc
}
// Init Api Client from apiKey & secretKey
func NewClient(apiKey, secretKey string) *Client {
return &Client{
APIKey: apiKey,
SecretKey: secretKey,
BaseURL: getApiEndpoint(),
UserAgent: "Bingx/golang",
HTTPClient: http.DefaultClient,
Logger: log.New(os.Stderr, "bingx-golang", log.LstdFlags),
}
}
func (c *Client) debug(message string, args ...interface{}) {
if c.Debug {
c.Logger.Printf(message, args...)
}
}
func (c *Client) parseRequest(r *request, opts ...RequestOption) (err error) {
for _, opt := range opts {
opt(r)
}
err = r.validate()
if err != nil {
return err
}
recvWindow := r.recvWindow
if recvWindow == 0 {
recvWindow = 10000
}
r.setParam(recvWindowKey, recvWindow)
timestamp := time.Now().UnixNano() / 1e6
if r.query != nil {
r.setParam(timestampKey, timestamp)
c.debug(r.query.Encode())
sign := computeHmac256(r.query.Encode(), c.SecretKey)
r.setParam(signatureKey, sign)
} else {
r.setFormParam(timestampKey, timestamp)
sign := computeHmac256(r.form.Encode(), c.SecretKey)
r.setFormParam(signatureKey, sign)
}
queryString := r.query.Encode()
body := &bytes.Buffer{}
bodyString := r.form.Encode()
header := http.Header{}
if r.header != nil {
header = r.header.Clone()
}
if bodyString != "" {
header.Set("Content-Type", "application/x-www-form-urlencoded")
body = bytes.NewBufferString(bodyString)
}
fullUrl := fmt.Sprintf("%s%s", c.BaseURL, r.endpoint)
if queryString != "" {
fullUrl = fmt.Sprintf("%s?%s", fullUrl, queryString)
}
header.Add("X-BX-APIKEY", c.APIKey)
r.fullUrl = fullUrl
r.header = header
r.body = body
return nil
}
func computeHmac256(strMessage string, strSecret string) string {
key := []byte(strSecret)
h := hmac.New(sha256.New, key)
h.Write([]byte(strMessage))
return hex.EncodeToString(h.Sum(nil))
}
func (c *Client) callAPI(ctx context.Context, r *request, opts ...RequestOption) (data []byte, err error) {
err = c.parseRequest(r, opts...)
if err != nil {
return []byte{}, err
}
req, err := http.NewRequest(r.method, r.fullUrl, r.body)
if err != nil {
return []byte{}, err
}
req = req.WithContext(ctx)
req.Header = r.header
// c.debug("request: %#v", req)
c.debug("request url: %#v", req.URL.String())
f := c.do
if f == nil {
f = c.HTTPClient.Do
}
res, err := f(req)
if err != nil {
return []byte{}, err
}
data, err = io.ReadAll(res.Body)
if err != nil {
return []byte{}, err
}
defer func() {
cerr := res.Body.Close()
if err == nil && cerr != nil {
err = cerr
}
}()
// c.debug("response: %#v", res)
c.debug("response body: %s", string(data))
c.debug("response status code: %d", res.StatusCode)
apiErr := new(common.APIError)
json.Unmarshal(data, apiErr)
if apiErr.Code != 0 {
return nil, apiErr
}
return data, nil
}
type GetServerTimeService struct {
c *Client
}
func (s *GetServerTimeService) Do(ctx context.Context, opts ...RequestOption) (res int64, err error) {
r := &request{method: http.MethodGet, endpoint: "/openApi/swap/v2/server/time"}
data, err := s.c.callAPI(ctx, r, opts...)
if err != nil {
return 0, err
}
resp := new(struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data map[string]int64 `json:"data"`
})
err = json.Unmarshal(data, &resp)
if err != nil {
return 0, err
}
res = resp.Data["serverTime"]
return res, nil
}
func (c *Client) NewGetServerTimeService() *GetServerTimeService {
return &GetServerTimeService{c: c}
}
func (c *Client) NewGetBalanceService() *GetBalanceService {
return &GetBalanceService{c: c}
}
func (c *Client) NewGetAccountListenKeyService() *GetAccountListenKeyService {
return &GetAccountListenKeyService{c: c}
}
func (c *Client) NewGetOpenPositionsService() *GetOpenPositionsService {
return &GetOpenPositionsService{c: c}
}
func (c *Client) NewCreateOrderService() *CreateOrderService {
return &CreateOrderService{c: c}
}
func (c *Client) NewCancelOrderService() *CancelOrderService {
return &CancelOrderService{c: c}
}
func (c *Client) NewGetOrderService() *GetOrderService {
return &GetOrderService{c: c}
}
func (c *Client) NewGetOpenOrdersService() *GetOpenOrdersService {
return &GetOpenOrdersService{c: c}
}
func (c *Client) NewGetKlinesService() *GetKlinesService {
return &GetKlinesService{c: c}
}
func (c *Client) NewGetSymbolDataService() *GetSymbolDataService {
return &GetSymbolDataService{c: c}
}
func (c *Client) NewCancelAllOrdersService() *CancelAllOrdersService {
return &CancelAllOrdersService{c: c}
}