-
Notifications
You must be signed in to change notification settings - Fork 33
/
bybit_api_client.go
311 lines (276 loc) · 7.05 KB
/
bybit_api_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
package bybit_connector
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"github.com/wuhewuhe/bybit.go.api/models"
"io"
"log"
"net/http"
"net/url"
"os"
"strconv"
"time"
"github.com/bitly/go-simplejson"
jsoniter "github.com/json-iterator/go"
"github.com/wuhewuhe/bybit.go.api/handlers"
)
var json = jsoniter.ConfigCompatibleWithStandardLibrary
type BybitClientRequest struct {
c *Client
params map[string]interface{}
isUta bool
}
type ServerResponse struct {
RetCode int `json:"retCode"`
RetMsg string `json:"retMsg"`
Result interface{} `json:"result"`
RetExtInfo struct{} `json:"retExtInfo"`
Time int64 `json:"time"`
}
func SendRequest(ctx context.Context, opts []RequestOption, r *request, s *BybitClientRequest, err error) []byte {
r.setParams(s.params)
data, err := s.c.callAPI(ctx, r, opts...)
return data
}
func GetServerResponse(err error, data []byte) (*ServerResponse, error) {
if err != nil {
return nil, err
}
resp := new(ServerResponse)
err = json.Unmarshal(data, resp)
if err != nil {
return nil, err
}
return resp, nil
}
func GetBatchOrderServerResponse(err error, data []byte) (*models.BatchOrderServerResponse, error) {
if err != nil {
return nil, err
}
resp := new(models.BatchOrderServerResponse)
err = json.Unmarshal(data, resp)
if err != nil {
return nil, err
}
return resp, nil
}
// Client define API client
type Client struct {
APIKey string
APISecret string
BaseURL string
HTTPClient *http.Client
Debug bool
Logger *log.Logger
do doFunc
ProxyURL string
}
type doFunc func(req *http.Request) (*http.Response, error)
type ClientOption func(*Client)
// WithDebug print more details in debug mode
func WithDebug(debug bool) ClientOption {
return func(c *Client) {
c.Debug = debug
}
}
// WithBaseURL is a client option to set the base URL of the Bybit HTTP client.
func WithBaseURL(baseURL string) ClientOption {
return func(c *Client) {
c.BaseURL = baseURL
}
}
// WithProxyURL is a client option to set the proxy url
func WithProxyURL(proxyURL string) ClientOption {
return func(c *Client) {
c.ProxyURL = proxyURL
}
}
func PrettyPrint(i interface{}) string {
s, _ := json.MarshalIndent(i, "", " ")
return string(s)
}
func (c *Client) debug(format string, v ...interface{}) {
if c.Debug {
c.Logger.Printf(format, v...)
}
}
// 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 GetCurrentTime() int64 {
now := time.Now()
unixNano := now.UnixNano()
timeStamp := unixNano / int64(time.Millisecond)
return timeStamp
}
func newJSON(data []byte) (j *simplejson.Json, err error) {
j, err = simplejson.NewJson(data)
if err != nil {
return nil, err
}
return j, nil
}
// NewBybitHttpClient NewClient Create client function for initialising new Bybit client
func NewBybitHttpClient(apiKey string, APISecret string, options ...ClientOption) *Client {
c := &Client{
APIKey: apiKey,
APISecret: APISecret,
BaseURL: MAINNET,
HTTPClient: http.DefaultClient,
Logger: log.New(os.Stderr, Name, log.LstdFlags),
}
// Apply the provided options
for _, opt := range options {
opt(c)
}
if c.ProxyURL != "" {
proxyURL, err := url.Parse(c.ProxyURL)
if err != nil {
c.Logger.Printf("Error parsing proxy URL: %v", err)
return nil // Or handle this more gracefully
}
c.HTTPClient.Transport = &http.Transport{
Proxy: http.ProxyURL(proxyURL),
}
}
return c
}
func (c *Client) parseRequest(r *request, opts ...RequestOption) (err error) {
// set request options from user
for _, opt := range opts {
opt(r)
}
err = r.validate()
if err != nil {
return err
}
fullURL := fmt.Sprintf("%s%s", c.BaseURL, r.endpoint)
queryString := r.query.Encode()
header := http.Header{}
body := &bytes.Buffer{}
if r.params != nil {
body = bytes.NewBuffer(r.params)
}
if r.header != nil {
header = r.header.Clone()
}
header.Set("User-Agent", fmt.Sprintf("%s/%s", Name, Version))
if r.secType == secTypeSigned {
timeStamp := GetCurrentTime()
header.Set(signTypeKey, "2")
header.Set(apiRequestKey, c.APIKey)
header.Set(timestampKey, strconv.FormatInt(timeStamp, 10))
if r.recvWindow == "" {
r.recvWindow = "5000"
}
header.Set(recvWindowKey, r.recvWindow)
var signatureBase []byte
if r.method == "POST" {
header.Set("Content-Type", "application/json")
signatureBase = []byte(strconv.FormatInt(timeStamp, 10) + c.APIKey + r.recvWindow + string(r.params[:]))
} else {
signatureBase = []byte(strconv.FormatInt(timeStamp, 10) + c.APIKey + r.recvWindow + queryString)
}
hmac256 := hmac.New(sha256.New, []byte(c.APISecret))
hmac256.Write(signatureBase)
signature := hex.EncodeToString(hmac256.Sum(nil))
header.Set(signatureKey, signature)
}
if queryString != "" {
fullURL = fmt.Sprintf("%s?%s", fullURL, queryString)
}
c.debug("full url: %s, body: %s", fullURL, body)
r.fullURL = fullURL
r.body = body
r.header = header
return 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 nil, 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)
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()
// Only overwrite the returned error if the original error was nil and an
// error occurred while closing the body.
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)
if res.StatusCode >= http.StatusBadRequest {
var (
apiErr = new(handlers.APIError)
)
e := json.Unmarshal(data, apiErr)
if e != nil {
c.debug("failed to unmarshal json: %s", e)
}
return nil, apiErr
}
return data, nil
}
// NewPlaceOrderService quick order endpoint
func (c *Client) NewPlaceOrderService(category, symbol, side, orderType, qty string) *Order {
return &Order{
c: c,
category: category,
symbol: symbol,
side: side,
orderType: orderType,
qty: qty,
}
}
func (c *Client) NewUtaBybitServiceWithParams(params map[string]interface{}) *BybitClientRequest {
return &BybitClientRequest{
c: c,
params: params,
isUta: true,
}
}
func (c *Client) NewUtaBybitServiceNoParams() *BybitClientRequest {
return &BybitClientRequest{
c: c,
isUta: true,
}
}
func (c *Client) NewClassicalBybitServiceWithParams(params map[string]interface{}) *BybitClientRequest {
return &BybitClientRequest{
c: c,
params: params,
isUta: false,
}
}
func (c *Client) NewClassicalBybitServiceNoParams() *BybitClientRequest {
return &BybitClientRequest{
c: c,
isUta: false,
}
}