forked from f0cii/bybit-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
287 lines (254 loc) · 6.75 KB
/
api.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
package rest
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"log"
"net/http"
"sort"
"strings"
"time"
)
type ByBit struct {
baseURL string // https://api-testnet.bybit.com/open-api/
apiKey string
secretKey string
serverTimeOffset int64 // 时间偏差(ms)
client *http.Client
debugMode bool
}
func New(httpClient *http.Client, baseURL string, apiKey string, secretKey string, debugMode bool) *ByBit {
if httpClient == nil {
httpClient = &http.Client{
Timeout: 10 * time.Second,
}
}
return &ByBit{
baseURL: baseURL,
apiKey: apiKey,
secretKey: secretKey,
client: httpClient,
debugMode: debugMode,
}
}
// SetCorrectServerTime 校正服务器时间
func (b *ByBit) SetCorrectServerTime() (err error) {
var timeNow int64
timeNow, err = b.GetServerTime()
if err != nil {
return
}
b.serverTimeOffset = timeNow - time.Now().UnixNano()/1e6
return
}
// GetBalance Get Wallet Balance
// coin: BTC,EOS,XRP,ETH,USDT
func (b *ByBit) GetWalletBalance(coin string) (result Balance, err error) {
var ret GetBalanceResult
params := map[string]interface{}{}
params["coin"] = coin
_, err = b.SignedRequest(http.MethodGet, "v2/private/wallet/balance", params, &ret) // v2/private/wallet/balance
if err != nil {
return
}
switch coin {
case "BTC":
result = ret.Result.BTC
case "ETH":
result = ret.Result.ETH
case "EOS":
result = ret.Result.EOS
case "XRP":
result = ret.Result.XRP
case "USDT":
result = ret.Result.USDT
}
return
}
// GetLeverages 获取用户杠杆
func (b *ByBit) GetLeverages() (result map[string]LeverageItem, err error) {
var r GetLeverageResult
params := map[string]interface{}{}
_, err = b.SignedRequest(http.MethodGet, "user/leverage", params, &r)
if err != nil {
return
}
result = r.Result
return
}
// SetLeverage 设置杠杆
func (b *ByBit) SetLeverage(leverage int, symbol string) (err error) {
var r BaseResult
params := map[string]interface{}{}
params["symbol"] = symbol
params["leverage"] = fmt.Sprintf("%v", leverage)
_, err = b.SignedRequest(http.MethodPost, "user/leverage", params, &r)
if err != nil {
return
}
log.Println(r)
return
}
// GetPositions 获取我的仓位
func (b *ByBit) GetPositions() (result []Position, err error) {
var r PositionListResult
params := map[string]interface{}{}
var resp []byte
resp, err = b.SignedRequest(http.MethodGet, "position/list", params, &r)
if err != nil {
return
}
if r.RetCode != 0 {
err = fmt.Errorf("%v body: [%v]", r.RetMsg, string(resp))
return
}
for _, v := range r.Result {
result = append(result, b.convertPositionV1(v))
}
return
}
func (b *ByBit) convertPositionV1(position PositionV1) (result Position) {
result.ID = position.ID
result.UserID = position.UserID
result.RiskID = position.RiskID
result.Symbol = position.Symbol
result.Size = position.Size
result.Side = position.Side
result.EntryPrice = position.EntryPrice
result.LiqPrice = position.LiqPrice
result.BustPrice = position.BustPrice
result.TakeProfit = position.TakeProfit
result.StopLoss = position.StopLoss
result.TrailingStop = position.TrailingStop
result.PositionValue = position.PositionValue
result.Leverage = position.Leverage
result.PositionStatus = position.PositionStatus
result.AutoAddMargin = position.AutoAddMargin
result.OrderMargin = position.OrderMargin
result.PositionMargin = position.PositionMargin
result.OccClosingFee = position.OccClosingFee
result.OccFundingFee = position.OccFundingFee
result.ExtFields = position.ExtFields
result.WalletBalance = position.WalletBalance
result.CumRealisedPnl = position.CumRealisedPnl
result.CumCommission = position.CumCommission
result.RealisedPnl = position.RealisedPnl
result.DeleverageIndicator = position.DeleverageIndicator
result.OcCalcData = position.OcCalcData
result.CrossSeq = position.CrossSeq
result.PositionSeq = position.PositionSeq
result.CreatedAt = position.CreatedAt
result.UpdatedAt = position.UpdatedAt
result.UnrealisedPnl = position.UnrealisedPnl
return
}
// GetPosition 获取我的仓位
func (b *ByBit) GetPosition(symbol string) (result Position, err error) {
var r GetPositionResult
params := map[string]interface{}{}
params["symbol"] = symbol
var resp []byte
resp, err = b.SignedRequest(http.MethodGet, "v2/private/position/list", params, &r)
if err != nil {
return
}
if r.RetCode != 0 {
err = fmt.Errorf("%v body: [%v]", r.RetMsg, string(resp))
return
}
result = r.Result
return
}
func (b *ByBit) PublicRequest(method string, apiURL string, params map[string]interface{}, result interface{}) (resp []byte, err error) {
var keys []string
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
var p []string
for _, k := range keys {
p = append(p, fmt.Sprintf("%v=%v", k, params[k]))
}
param := strings.Join(p, "&")
fullURL := b.baseURL + apiURL
if param != "" {
fullURL += "?" + param
}
if b.debugMode {
log.Printf("PublicRequest: %v", fullURL)
}
var binBody = bytes.NewReader(make([]byte, 0))
// get a http request
var request *http.Request
request, err = http.NewRequest(method, fullURL, binBody)
if err != nil {
return
}
var response *http.Response
response, err = b.client.Do(request)
if err != nil {
return
}
defer response.Body.Close()
resp, err = ioutil.ReadAll(response.Body)
if err != nil {
return
}
if b.debugMode {
log.Printf("PublicRequest: %v", string(resp))
}
err = json.Unmarshal(resp, result)
return
}
func (b *ByBit) SignedRequest(method string, apiURL string, params map[string]interface{}, result interface{}) (resp []byte, err error) {
timestamp := time.Now().UnixNano()/1e6 + b.serverTimeOffset
params["api_key"] = b.apiKey
params["timestamp"] = timestamp
var keys []string
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
var p []string
for _, k := range keys {
p = append(p, fmt.Sprintf("%v=%v", k, params[k]))
}
param := strings.Join(p, "&")
signature := b.getSigned(param)
param += "&sign=" + signature
fullURL := b.baseURL + apiURL + "?" + param
if b.debugMode {
log.Printf("SignedRequest: %v", fullURL)
}
var binBody = bytes.NewReader(make([]byte, 0))
// get a http request
var request *http.Request
request, err = http.NewRequest(method, fullURL, binBody)
if err != nil {
return
}
var response *http.Response
response, err = b.client.Do(request)
if err != nil {
return
}
defer response.Body.Close()
resp, err = ioutil.ReadAll(response.Body)
if err != nil {
return
}
if b.debugMode {
log.Printf("SignedRequest: %v", string(resp))
}
err = json.Unmarshal(resp, result)
return
}
func (b *ByBit) getSigned(param string) string {
sig := hmac.New(sha256.New, []byte(b.secretKey))
sig.Write([]byte(param))
signature := hex.EncodeToString(sig.Sum(nil))
return signature
}