forked from thrasher-corp/gocryptotrader
-
Notifications
You must be signed in to change notification settings - Fork 1
/
yobit.go
496 lines (430 loc) · 13.3 KB
/
yobit.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
489
490
491
492
493
494
495
496
package yobit
import (
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/woshidama323/gocryptotrader/common"
"github.com/woshidama323/gocryptotrader/config"
"github.com/woshidama323/gocryptotrader/currency"
exchange "github.com/woshidama323/gocryptotrader/exchanges"
"github.com/woshidama323/gocryptotrader/exchanges/request"
"github.com/woshidama323/gocryptotrader/exchanges/ticker"
"github.com/woshidama323/gocryptotrader/exchanges/websocket/wshandler"
log "github.com/woshidama323/gocryptotrader/logger"
)
const (
apiPublicURL = "https://yobit.net/api"
apiPrivateURL = "https://yobit.net/tapi"
apiPublicVersion = "3"
publicInfo = "info"
publicTicker = "ticker"
publicDepth = "depth"
publicTrades = "trades"
privateAccountInfo = "getInfo"
privateTrade = "Trade"
privateActiveOrders = "ActiveOrders"
privateOrderInfo = "OrderInfo"
privateCancelOrder = "CancelOrder"
privateTradeHistory = "TradeHistory"
privateGetDepositAddress = "GetDepositAddress"
privateWithdrawCoinsToAddress = "WithdrawCoinsToAddress"
privateCreateCoupon = "CreateYobicode"
privateRedeemCoupon = "RedeemYobicode"
yobitAuthRate = 0
yobitUnauthRate = 0
)
// Yobit is the overarching type across the Yobit package
type Yobit struct {
exchange.Base
Ticker map[string]Ticker
}
// SetDefaults sets current default value for Yobit
func (y *Yobit) SetDefaults() {
y.Name = "Yobit"
y.Enabled = true
y.Fee = 0.2
y.Verbose = false
y.RESTPollingDelay = 10
y.AuthenticatedAPISupport = true
y.Ticker = make(map[string]Ticker)
y.APIWithdrawPermissions = exchange.AutoWithdrawCryptoWithAPIPermission |
exchange.WithdrawFiatViaWebsiteOnly
y.RequestCurrencyPairFormat.Delimiter = "_"
y.RequestCurrencyPairFormat.Uppercase = false
y.RequestCurrencyPairFormat.Separator = "-"
y.ConfigCurrencyPairFormat.Delimiter = "_"
y.ConfigCurrencyPairFormat.Uppercase = true
y.AssetTypes = []string{ticker.Spot}
y.SupportsAutoPairUpdating = false
y.SupportsRESTTickerBatching = true
y.Requester = request.New(y.Name,
request.NewRateLimit(time.Second, yobitAuthRate),
request.NewRateLimit(time.Second, yobitUnauthRate),
common.NewHTTPClientWithTimeout(exchange.DefaultHTTPTimeout))
y.APIUrlDefault = apiPublicURL
y.APIUrl = y.APIUrlDefault
y.APIUrlSecondaryDefault = apiPrivateURL
y.APIUrlSecondary = y.APIUrlSecondaryDefault
y.Websocket = wshandler.New()
}
// Setup sets exchange configuration parameters for Yobit
func (y *Yobit) Setup(exch *config.ExchangeConfig) {
if !exch.Enabled {
y.SetEnabled(false)
} else {
y.Enabled = true
y.AuthenticatedAPISupport = exch.AuthenticatedAPISupport
y.SetAPIKeys(exch.APIKey, exch.APISecret, "", false)
y.RESTPollingDelay = exch.RESTPollingDelay
y.Verbose = exch.Verbose
y.HTTPDebugging = exch.HTTPDebugging
y.Websocket.SetWsStatusAndConnection(exch.Websocket)
y.BaseCurrencies = exch.BaseCurrencies
y.AvailablePairs = exch.AvailablePairs
y.EnabledPairs = exch.EnabledPairs
y.SetHTTPClientTimeout(exch.HTTPTimeout)
y.SetHTTPClientUserAgent(exch.HTTPUserAgent)
err := y.SetCurrencyPairFormat()
if err != nil {
log.Fatal(err)
}
err = y.SetAssetTypes()
if err != nil {
log.Fatal(err)
}
err = y.SetAutoPairDefaults()
if err != nil {
log.Fatal(err)
}
err = y.SetAPIURL(exch)
if err != nil {
log.Fatal(err)
}
err = y.SetClientProxyAddress(exch.ProxyAddress)
if err != nil {
log.Fatal(err)
}
}
}
// GetInfo returns the Yobit info
func (y *Yobit) GetInfo() (Info, error) {
resp := Info{}
path := fmt.Sprintf("%s/%s/%s/", y.APIUrl, apiPublicVersion, publicInfo)
return resp, y.SendHTTPRequest(path, &resp)
}
// GetTicker returns a ticker for a specific currency
func (y *Yobit) GetTicker(symbol string) (map[string]Ticker, error) {
type Response struct {
Data map[string]Ticker
}
response := Response{}
path := fmt.Sprintf("%s/%s/%s/%s", y.APIUrl, apiPublicVersion, publicTicker, symbol)
return response.Data, y.SendHTTPRequest(path, &response.Data)
}
// GetDepth returns the depth for a specific currency
func (y *Yobit) GetDepth(symbol string) (Orderbook, error) {
type Response struct {
Data map[string]Orderbook
}
response := Response{}
path := fmt.Sprintf("%s/%s/%s/%s", y.APIUrl, apiPublicVersion, publicDepth, symbol)
return response.Data[symbol],
y.SendHTTPRequest(path, &response.Data)
}
// GetTrades returns the trades for a specific currency
func (y *Yobit) GetTrades(symbol string) ([]Trades, error) {
type Response struct {
Data map[string][]Trades
}
response := Response{}
path := fmt.Sprintf("%s/%s/%s/%s", y.APIUrl, apiPublicVersion, publicTrades, symbol)
return response.Data[symbol], y.SendHTTPRequest(path, &response.Data)
}
// GetAccountInformation returns a users account info
func (y *Yobit) GetAccountInformation() (AccountInfo, error) {
result := AccountInfo{}
err := y.SendAuthenticatedHTTPRequest(privateAccountInfo, url.Values{}, &result)
if err != nil {
return result, err
}
if result.Error != "" {
return result, errors.New(result.Error)
}
return result, nil
}
// Trade places an order and returns the order ID if successful or an error
func (y *Yobit) Trade(pair, orderType string, amount, price float64) (int64, error) {
req := url.Values{}
req.Add("pair", pair)
req.Add("type", orderType)
req.Add("amount", strconv.FormatFloat(amount, 'f', -1, 64))
req.Add("rate", strconv.FormatFloat(price, 'f', -1, 64))
result := Trade{}
err := y.SendAuthenticatedHTTPRequest(privateTrade, req, &result)
if err != nil {
return int64(result.OrderID), err
}
if result.Error != "" {
return int64(result.OrderID), errors.New(result.Error)
}
return int64(result.OrderID), nil
}
// GetOpenOrders returns the active orders for a specific currency
func (y *Yobit) GetOpenOrders(pair string) (map[string]ActiveOrders, error) {
req := url.Values{}
req.Add("pair", pair)
result := map[string]ActiveOrders{}
return result, y.SendAuthenticatedHTTPRequest(privateActiveOrders, req, &result)
}
// GetOrderInformation returns the order info for a specific order ID
func (y *Yobit) GetOrderInformation(orderID int64) (map[string]OrderInfo, error) {
req := url.Values{}
req.Add("order_id", strconv.FormatInt(orderID, 10))
result := map[string]OrderInfo{}
return result, y.SendAuthenticatedHTTPRequest(privateOrderInfo, req, &result)
}
// CancelExistingOrder cancels an order for a specific order ID
func (y *Yobit) CancelExistingOrder(orderID int64) (bool, error) {
req := url.Values{}
req.Add("order_id", strconv.FormatInt(orderID, 10))
result := CancelOrder{}
err := y.SendAuthenticatedHTTPRequest(privateCancelOrder, req, &result)
if err != nil {
return false, err
}
if result.Error != "" {
return false, errors.New(result.Error)
}
return true, nil
}
// GetTradeHistory returns the trade history
func (y *Yobit) GetTradeHistory(tidFrom, count, tidEnd, since, end int64, order, pair string) (map[string]TradeHistory, error) {
req := url.Values{}
req.Add("from", strconv.FormatInt(tidFrom, 10))
req.Add("count", strconv.FormatInt(count, 10))
req.Add("from_id", strconv.FormatInt(tidFrom, 10))
req.Add("end_id", strconv.FormatInt(tidEnd, 10))
req.Add("order", order)
req.Add("since", strconv.FormatInt(since, 10))
req.Add("end", strconv.FormatInt(end, 10))
req.Add("pair", pair)
result := TradeHistoryResponse{}
err := y.SendAuthenticatedHTTPRequest(privateTradeHistory, req, &result)
if err != nil {
return nil, err
}
if result.Success == 0 {
return nil, errors.New(result.Error)
}
return result.Data, nil
}
// GetCryptoDepositAddress returns the deposit address for a specific currency
func (y *Yobit) GetCryptoDepositAddress(coin string) (DepositAddress, error) {
req := url.Values{}
req.Add("coinName", coin)
result := DepositAddress{}
err := y.SendAuthenticatedHTTPRequest(privateGetDepositAddress, req, &result)
if err != nil {
return result, err
}
if result.Success != 1 {
return result, fmt.Errorf("%s", result.Error)
}
return result, nil
}
// WithdrawCoinsToAddress initiates a withdrawal to a specified address
func (y *Yobit) WithdrawCoinsToAddress(coin string, amount float64, address string) (WithdrawCoinsToAddress, error) {
req := url.Values{}
req.Add("coinName", coin)
req.Add("amount", strconv.FormatFloat(amount, 'f', -1, 64))
req.Add("address", address)
result := WithdrawCoinsToAddress{}
err := y.SendAuthenticatedHTTPRequest(privateWithdrawCoinsToAddress, req, &result)
if err != nil {
return result, err
}
if result.Error != "" {
return result, errors.New(result.Error)
}
return result, nil
}
// CreateCoupon creates an exchange coupon for a sepcific currency
func (y *Yobit) CreateCoupon(currency string, amount float64) (CreateCoupon, error) {
req := url.Values{}
req.Add("currency", currency)
req.Add("amount", strconv.FormatFloat(amount, 'f', -1, 64))
var result CreateCoupon
err := y.SendAuthenticatedHTTPRequest(privateCreateCoupon, req, &result)
if err != nil {
return result, err
}
if result.Error != "" {
return result, errors.New(result.Error)
}
return result, nil
}
// RedeemCoupon redeems an exchange coupon
func (y *Yobit) RedeemCoupon(coupon string) (RedeemCoupon, error) {
req := url.Values{}
req.Add("coupon", coupon)
result := RedeemCoupon{}
err := y.SendAuthenticatedHTTPRequest(privateRedeemCoupon, req, &result)
if err != nil {
return result, err
}
if result.Error != "" {
return result, errors.New(result.Error)
}
return result, nil
}
// SendHTTPRequest sends an unauthenticated HTTP request
func (y *Yobit) SendHTTPRequest(path string, result interface{}) error {
return y.SendPayload(http.MethodGet,
path,
nil,
nil,
result,
false,
false,
y.Verbose,
y.HTTPDebugging,
y.HTTPRecording)
}
// SendAuthenticatedHTTPRequest sends an authenticated HTTP request to Yobit
func (y *Yobit) SendAuthenticatedHTTPRequest(path string, params url.Values, result interface{}) (err error) {
if !y.AuthenticatedAPISupport {
return fmt.Errorf(exchange.WarningAuthenticatedRequestWithoutCredentialsSet,
y.Name)
}
if params == nil {
params = url.Values{}
}
n := y.Requester.GetNonce(false).String()
params.Set("nonce", n)
params.Set("method", path)
encoded := params.Encode()
hmac := common.GetHMAC(common.HashSHA512,
[]byte(encoded),
[]byte(y.APISecret))
if y.Verbose {
log.Debugf("Sending POST request to %s calling path %s with params %s\n",
apiPrivateURL,
path,
encoded)
}
headers := make(map[string]string)
headers["Key"] = y.APIKey
headers["Sign"] = common.HexEncodeToString(hmac)
headers["Content-Type"] = "application/x-www-form-urlencoded"
return y.SendPayload(http.MethodPost,
apiPrivateURL,
headers,
strings.NewReader(encoded),
result,
true,
true,
y.Verbose,
y.HTTPDebugging,
y.HTTPRecording)
}
// GetFee returns an estimate of fee based on type of transaction
func (y *Yobit) GetFee(feeBuilder *exchange.FeeBuilder) (float64, error) {
var fee float64
switch feeBuilder.FeeType {
case exchange.CryptocurrencyTradeFee:
fee = calculateTradingFee(feeBuilder.PurchasePrice, feeBuilder.Amount)
case exchange.CryptocurrencyWithdrawalFee:
fee = getWithdrawalFee(feeBuilder.Pair.Base)
case exchange.InternationalBankDepositFee:
fee = getInternationalBankDepositFee(feeBuilder.FiatCurrency,
feeBuilder.BankTransactionType)
case exchange.InternationalBankWithdrawalFee:
fee = getInternationalBankWithdrawalFee(feeBuilder.FiatCurrency,
feeBuilder.Amount,
feeBuilder.BankTransactionType)
case exchange.OfflineTradeFee:
fee = calculateTradingFee(feeBuilder.PurchasePrice, feeBuilder.Amount)
}
if fee < 0 {
fee = 0
}
return fee, nil
}
func calculateTradingFee(price, amount float64) (fee float64) {
return 0.002 * price * amount
}
func getWithdrawalFee(c currency.Code) float64 {
return WithdrawalFees[c]
}
func getInternationalBankWithdrawalFee(c currency.Code, amount float64, bankTransactionType exchange.InternationalBankTransactionType) float64 {
var fee float64
switch bankTransactionType {
case exchange.PerfectMoney:
if c == currency.USD {
fee = 0.02 * amount
}
case exchange.Payeer:
switch c {
case currency.USD:
fee = 0.03 * amount
case currency.RUR:
fee = 0.006 * amount
}
case exchange.AdvCash:
switch c {
case currency.USD:
fee = 0.04 * amount
case currency.RUR:
fee = 0.03 * amount
}
case exchange.Qiwi:
if c == currency.RUR {
fee = 0.04 * amount
}
case exchange.Capitalist:
if c == currency.USD {
fee = 0.06 * amount
}
}
return fee
}
// getInternationalBankDepositFee; No real fees for yobit deposits, but want to be explicit on what each payment type supports
func getInternationalBankDepositFee(c currency.Code, bankTransactionType exchange.InternationalBankTransactionType) float64 {
var fee float64
switch bankTransactionType {
case exchange.PerfectMoney:
if c == currency.USD {
fee = 0
}
case exchange.Payeer:
switch c {
case currency.USD:
fee = 0
case currency.RUR:
fee = 0
}
case exchange.AdvCash:
switch c {
case currency.USD:
fee = 0
case currency.RUR:
fee = 0
}
case exchange.Qiwi:
if c == currency.RUR {
fee = 0
}
case exchange.Capitalist:
switch c {
case currency.USD:
fee = 0
case currency.RUR:
fee = 0
}
}
return fee
}