This repository has been archived by the owner on Feb 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 262
/
ccxtExchange_test.go
607 lines (533 loc) · 16.2 KB
/
ccxtExchange_test.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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
package plugins
import (
"fmt"
"github.com/stretchr/testify/require"
"log"
"math"
"strconv"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stellar/kelp/api"
"github.com/stellar/kelp/model"
)
type exchangeAuthData struct {
apiKey api.ExchangeAPIKey
params []api.ExchangeParam
}
var supportedExchanges = []string{"binance", "coinbasepro"}
var emptyAPIKey = api.ExchangeAPIKey{}
var emptyParams = api.ExchangeParam{}
var supportedTradingExchanges = map[string]exchangeAuthData{
"binance": exchangeAuthData{
apiKey: api.ExchangeAPIKey{},
params: []api.ExchangeParam{},
},
}
var testOrderConstraints = map[string]map[model.TradingPair]model.OrderConstraints{
"binance": map[model.TradingPair]model.OrderConstraints{
*model.MakeTradingPair(model.XLM, model.USDT): *model.MakeOrderConstraints(4, 5, 0.1),
*model.MakeTradingPair(model.XLM, model.BTC): *model.MakeOrderConstraints(8, 4, 1.0),
},
"kraken": map[model.TradingPair]model.OrderConstraints{
*model.MakeTradingPair(model.XLM, model.USD): *model.MakeOrderConstraints(6, 8, 30.0),
*model.MakeTradingPair(model.XLM, model.BTC): *model.MakeOrderConstraints(8, 8, 30.0),
},
"bitstamp": map[model.TradingPair]model.OrderConstraints{
*model.MakeTradingPair(model.XLM, model.USD): *model.MakeOrderConstraints(5, 2, 25.0),
},
}
func getEsParamFactory(exchangeName string) ccxtExchangeSpecificParamFactory {
if v, ok := ccxtExchangeSpecificParamFactoryMap["ccxt-"+exchangeName]; ok {
return v
}
return nil
}
func TestGetTickerPrice_Ccxt(t *testing.T) {
if testing.Short() {
return
}
for _, exchangeName := range supportedExchanges {
t.Run(exchangeName, func(t *testing.T) {
testCcxtExchange, e := makeCcxtExchange(
exchangeName,
testOrderConstraints[exchangeName],
[]api.ExchangeAPIKey{emptyAPIKey},
[]api.ExchangeParam{emptyParams},
[]api.ExchangeHeader{},
false,
getEsParamFactory(exchangeName),
)
if !assert.NoError(t, e) {
return
}
pair := model.TradingPair{Base: model.XLM, Quote: model.BTC}
pairs := []model.TradingPair{pair}
m, e := testCcxtExchange.GetTickerPrice(pairs)
if !assert.NoError(t, e) {
return
}
assert.Equal(t, 1, len(m))
ticker := m[pair]
assert.True(t, ticker.AskPrice.AsFloat() < 1, ticker.AskPrice.AsString())
assert.True(t, ticker.BidPrice.AsFloat() < 1, ticker.BidPrice.AsString())
assert.True(t, ticker.BidPrice.AsFloat() < ticker.AskPrice.AsFloat(), fmt.Sprintf("bid price (%s) should be less than ask price (%s)", ticker.BidPrice.AsString(), ticker.AskPrice.AsString()))
assert.True(t, ticker.LastPrice.AsFloat() < 1, ticker.LastPrice.AsString())
})
}
}
func TestGetOrderBook_Ccxt(t *testing.T) {
if testing.Short() {
return
}
for _, exchangeName := range supportedExchanges {
for _, obDepth := range []int32{1, 5, 8, 10, 15, 16, 20} {
t.Run(fmt.Sprintf("%s_%d", exchangeName, obDepth), func(t *testing.T) {
testCcxtExchange, e := makeCcxtExchange(
exchangeName,
testOrderConstraints[exchangeName],
[]api.ExchangeAPIKey{emptyAPIKey},
[]api.ExchangeParam{emptyParams},
[]api.ExchangeHeader{},
false,
getEsParamFactory(exchangeName),
)
if !assert.NoError(t, e) {
return
}
pair := model.TradingPair{Base: model.XLM, Quote: model.BTC}
ob, e := testCcxtExchange.GetOrderBook(&pair, obDepth)
if !assert.NoError(t, e) {
return
}
assert.Equal(t, ob.Pair(), &pair)
assert.True(t, len(ob.Asks()) > 0, fmt.Sprintf("%d", len(ob.Asks())))
assert.True(t, len(ob.Bids()) > 0, fmt.Sprintf("%d", len(ob.Bids())))
assert.True(t, ob.Asks()[0].OrderAction.IsSell())
assert.True(t, ob.Asks()[0].OrderType.IsLimit())
assert.True(t, ob.Bids()[0].OrderAction.IsBuy())
assert.True(t, ob.Bids()[0].OrderType.IsLimit())
assert.True(t, ob.Asks()[0].Price.AsFloat() > 0, ob.Asks()[0].Price.AsString())
assert.True(t, ob.Asks()[0].Volume.AsFloat() > 0)
assert.True(t, ob.Bids()[0].Price.AsFloat() > 0, ob.Bids()[0].Price.AsString())
assert.True(t, ob.Bids()[0].Volume.AsFloat() > 0)
})
}
}
}
func TestGetTrades_Ccxt(t *testing.T) {
if testing.Short() {
return
}
for _, exchangeName := range supportedExchanges {
t.Run(exchangeName, func(t *testing.T) {
testCcxtExchange, e := makeCcxtExchange(
exchangeName,
testOrderConstraints[exchangeName],
[]api.ExchangeAPIKey{emptyAPIKey},
[]api.ExchangeParam{},
[]api.ExchangeHeader{},
false,
getEsParamFactory(exchangeName),
)
if !assert.NoError(t, e) {
return
}
pair := model.TradingPair{Base: model.XLM, Quote: model.BTC}
// TODO test with cursor once implemented
tradeResult, e := testCcxtExchange.GetTrades(&pair, nil)
if !assert.NoError(t, e) {
return
}
wantCursorInt64 := tradeResult.Trades[len(tradeResult.Trades)-1].Timestamp.AsInt64() + 1
assert.Equal(t, strconv.FormatInt(wantCursorInt64, 10), tradeResult.Cursor)
validateTrades(t, pair, tradeResult.Trades)
})
}
}
func TestGetTradeHistory_Ccxt(t *testing.T) {
if testing.Short() {
return
}
for exchangeName, authData := range supportedTradingExchanges {
t.Run(exchangeName, func(t *testing.T) {
testCcxtExchange, e := makeCcxtExchange(
exchangeName,
testOrderConstraints[exchangeName],
[]api.ExchangeAPIKey{authData.apiKey},
authData.params,
[]api.ExchangeHeader{},
false,
getEsParamFactory(exchangeName),
)
if !assert.NoError(t, e) {
return
}
pair := model.TradingPair{Base: model.XLM, Quote: model.BTC}
// TODO test with cursor once implemented
tradeHistoryResult, e := testCcxtExchange.GetTradeHistory(pair, nil, nil)
if !assert.NoError(t, e) {
return
}
if len(tradeHistoryResult.Trades) > 0 {
assert.NotNil(t, tradeHistoryResult.Cursor)
} else {
assert.Nil(t, tradeHistoryResult.Cursor)
}
validateTrades(t, pair, tradeHistoryResult.Trades)
})
}
}
func validateTrades(t *testing.T, pair model.TradingPair, trades []model.Trade) {
for _, trade := range trades {
if !assert.Equal(t, &pair, trade.Pair) {
return
}
if !assert.True(t, trade.Price.AsFloat() > 0, trade.Price.AsString()) {
return
}
if !assert.True(t, trade.Volume.AsFloat() > 0, trade.Volume.AsString()) {
return
}
if !assert.Equal(t, trade.OrderType, model.OrderTypeLimit) {
return
}
if !assert.True(t, trade.Timestamp.AsInt64() > 0, fmt.Sprintf("%d", trade.Timestamp.AsInt64())) {
return
}
if !assert.NotNil(t, trade.TransactionID) {
return
}
if !assert.NotNil(t, trade.Cost) {
return
}
if !assert.NotNil(t, trade.Fee) {
return
}
if trade.OrderAction != model.OrderActionBuy && trade.OrderAction != model.OrderActionSell {
assert.Fail(t, "trade.OrderAction should be either OrderActionBuy or OrderActionSell: %v", trade.OrderAction)
return
}
minPrecision := math.Min(float64(trade.Price.Precision()), float64(trade.Volume.Precision()))
nonZeroCalculatedCost := trade.Price.AsFloat()*trade.Volume.AsFloat() > math.Pow(10, -minPrecision)
if nonZeroCalculatedCost && !assert.True(t, trade.Cost.AsFloat() > 0, fmt.Sprintf("(price) %s x (volume) %s = (cost) %s", trade.Price.AsString(), trade.Volume.AsString(), trade.Cost.AsString())) {
return
}
}
}
func TestGetLatestTradeCursor_Ccxt(t *testing.T) {
for exchangeName, authData := range supportedTradingExchanges {
t.Run(exchangeName, func(t *testing.T) {
testCcxtExchange, e := makeCcxtExchange(
exchangeName,
testOrderConstraints[exchangeName],
[]api.ExchangeAPIKey{authData.apiKey},
authData.params,
[]api.ExchangeHeader{},
false,
getEsParamFactory(exchangeName),
)
if !assert.NoError(t, e) {
return
}
startIntervalMillis := time.Now().UnixNano() / int64(time.Millisecond)
cursor, e := testCcxtExchange.GetLatestTradeCursor()
if !assert.NoError(t, e) {
return
}
endIntervalMillis := time.Now().UnixNano() / int64(time.Millisecond)
if !assert.IsType(t, "string", cursor) {
return
}
cursorString := cursor.(string)
cursorInt, e := strconv.ParseInt(cursorString, 10, 64)
if !assert.NoError(t, e) {
return
}
if !assert.True(t, startIntervalMillis <= cursorInt, fmt.Sprintf("returned cursor (%d) should gte the start time of the function call in milliseconds (%d)", cursorInt, startIntervalMillis)) {
return
}
if !assert.True(t, endIntervalMillis >= cursorInt, fmt.Sprintf("returned cursor (%d) should lte the end time of the function call in milliseconds (%d)", cursorInt, endIntervalMillis)) {
return
}
})
}
}
func TestGetAccountBalances_Ccxt(t *testing.T) {
if testing.Short() {
return
}
for exchangeName, authData := range supportedTradingExchanges {
t.Run(exchangeName, func(t *testing.T) {
testCcxtExchange, e := makeCcxtExchange(
exchangeName,
testOrderConstraints[exchangeName],
[]api.ExchangeAPIKey{authData.apiKey},
authData.params,
[]api.ExchangeHeader{},
false,
getEsParamFactory(exchangeName),
)
if !assert.NoError(t, e) {
return
}
balances, e := testCcxtExchange.GetAccountBalances([]interface{}{
model.XLM,
model.BTC,
model.USD,
})
if !assert.NoError(t, e) {
return
}
log.Printf("balances: %+v\n", balances)
if !assert.Equal(t, 20.0, balances[model.XLM].AsFloat()) {
return
}
if !assert.Equal(t, 0.0, balances[model.BTC].AsFloat()) {
return
}
if !assert.Equal(t, 0.0, balances[model.USD].AsFloat()) {
return
}
assert.Fail(t, "force fail")
})
}
}
func TestGetOpenOrders_Ccxt(t *testing.T) {
if testing.Short() {
return
}
tradingPairs := []model.TradingPair{
{Base: model.XLM, Quote: model.BTC},
{Base: model.XLM, Quote: model.USDT},
}
for exchangeName, authData := range supportedTradingExchanges {
for _, pair := range tradingPairs {
t.Run(exchangeName, func(t *testing.T) {
testCcxtExchange, e := makeCcxtExchange(
exchangeName,
testOrderConstraints[exchangeName],
[]api.ExchangeAPIKey{authData.apiKey},
authData.params,
[]api.ExchangeHeader{},
false,
getEsParamFactory(exchangeName),
)
if !assert.NoError(t, e) {
return
}
m, e := testCcxtExchange.GetOpenOrders([]*model.TradingPair{&pair})
if !assert.NoError(t, e) {
return
}
if !assert.Equal(t, 1, len(m)) {
return
}
openOrders := m[pair]
if !assert.True(t, len(openOrders) > 0, fmt.Sprintf("%d", len(openOrders))) {
return
}
for _, o := range openOrders {
log.Printf("open order: %+v\n", o)
isValid := validateOpenOrder(t, &pair, o)
if !isValid {
return
}
}
assert.Fail(t, "force fail")
})
}
}
}
func validateOpenOrder(t *testing.T, pair *model.TradingPair, o model.OpenOrder) bool {
if !assert.Equal(t, pair, o.Order.Pair) {
return false
}
// OrderAction has it's underlying type as a boolean so will always be valid
if !assert.Equal(t, model.OrderTypeLimit, o.Order.OrderType) {
return false
}
if !assert.True(t, o.Order.Price.AsFloat() > 0, o.Order.Price.AsString()) {
return false
}
if !assert.True(t, o.Order.Volume.AsFloat() > 0, o.Order.Volume.AsString()) {
return false
}
if !assert.NotNil(t, o.Order.Timestamp) {
return false
}
if !assert.True(t, len(o.ID) > 0, o.ID) {
return false
}
if !assert.NotNil(t, o.StartTime) {
return false
}
// ExpireTime is always nil for now
if !assert.Nil(t, o.ExpireTime) {
return false
}
if !assert.NotNil(t, o.VolumeExecuted) {
return false
}
// additional check to see if the two timestamps match
if !assert.Equal(t, o.Order.Timestamp, o.StartTime) {
return false
}
return true
}
func TestAddOrder_Ccxt(t *testing.T) {
if testing.Short() {
return
}
for exchangeName, authData := range supportedTradingExchanges {
for _, kase := range []struct {
pair *model.TradingPair
orderAction model.OrderAction
orderType model.OrderType
price *model.Number
volume *model.Number
}{
{
pair: &model.TradingPair{Base: model.XLM, Quote: model.BTC},
orderAction: model.OrderActionSell,
orderType: model.OrderTypeLimit,
price: model.NumberFromFloat(0.000041, 6),
volume: model.NumberFromFloat(60.12345678, 6),
}, {
pair: &model.TradingPair{Base: model.XLM, Quote: model.BTC},
orderAction: model.OrderActionBuy,
orderType: model.OrderTypeLimit,
price: model.NumberFromFloat(0.000026, 6),
volume: model.NumberFromFloat(40.012345, 6),
}, {
pair: &model.TradingPair{Base: model.XLM, Quote: model.USDT},
orderAction: model.OrderActionSell,
orderType: model.OrderTypeLimit,
price: model.NumberFromFloat(0.15, 6),
volume: model.NumberFromFloat(51.5, 6),
},
} {
t.Run(exchangeName, func(t *testing.T) {
testCcxtExchange, e := makeCcxtExchange(
exchangeName,
testOrderConstraints[exchangeName],
[]api.ExchangeAPIKey{authData.apiKey},
authData.params,
[]api.ExchangeHeader{},
false,
getEsParamFactory(exchangeName),
)
if !assert.NoError(t, e) {
return
}
txID, e := testCcxtExchange.AddOrder(
&model.Order{
Pair: kase.pair,
OrderAction: kase.orderAction,
OrderType: kase.orderType,
Price: kase.price,
Volume: kase.volume,
},
api.SubmitModeBoth,
)
if !assert.NoError(t, e) {
return
}
log.Printf("transactionID from order: %s\n", txID)
if !assert.NotNil(t, txID) {
return
}
if !assert.NotEqual(t, "", txID.String()) {
return
}
assert.Fail(t, "force fail")
})
}
}
}
func TestCancelOrder_Ccxt(t *testing.T) {
if testing.Short() {
return
}
// TODO error converting type and ID for bitstamp
for exchangeName, authData := range supportedTradingExchanges {
for _, kase := range []struct {
orderID string
pair *model.TradingPair
}{
{
orderID: "",
pair: &model.TradingPair{Base: model.XLM, Quote: model.BTC},
}, {
orderID: "",
pair: &model.TradingPair{Base: model.XLM, Quote: model.USDT},
},
} {
t.Run(exchangeName, func(t *testing.T) {
testCcxtExchange, e := makeCcxtExchange(
exchangeName,
testOrderConstraints[exchangeName],
[]api.ExchangeAPIKey{authData.apiKey},
authData.params,
[]api.ExchangeHeader{},
false,
getEsParamFactory(exchangeName),
)
if !assert.NoError(t, e) {
return
}
result, e := testCcxtExchange.CancelOrder(model.MakeTransactionID(kase.orderID), *kase.pair)
if !assert.NoError(t, e) {
return
}
log.Printf("result from cancel order (transactionID=%s): %s\n", kase.orderID, result.String())
if !assert.Equal(t, model.CancelResultCancelSuccessful, result) {
return
}
})
}
}
}
func TestGetOrderConstraints_Ccxt_Precision(t *testing.T) {
// coinbasepro gives incorrect precision values so we do not test it here
testCases := []struct {
exchangeName string
pair *model.TradingPair
wantPricePrecision int8
wantVolPrecision int8
}{
{
// disable ccxt-kraken based tests for now because of the 403 Forbidden Security check API error
// exchangeName: "kraken",
// pair: &model.TradingPair{Base: model.XLM, Quote: model.USD},
// wantPricePrecision: 6,
// wantVolPrecision: 8,
// }, {
exchangeName: "binance",
pair: &model.TradingPair{Base: model.XLM, Quote: model.USDT},
wantPricePrecision: 4,
wantVolPrecision: 4,
}, {
exchangeName: "binance",
pair: &model.TradingPair{Base: model.XLM, Quote: model.BTC},
wantPricePrecision: 8,
wantVolPrecision: 8,
}, {
exchangeName: "bitstamp",
pair: &model.TradingPair{Base: model.XLM, Quote: model.USD},
wantPricePrecision: 5,
wantVolPrecision: 8,
},
}
for _, kase := range testCases {
epf := getEsParamFactory(kase.exchangeName)
t.Run(kase.exchangeName, func(t *testing.T) {
testCcxtExchange, e := makeCcxtExchange(kase.exchangeName, nil, []api.ExchangeAPIKey{emptyAPIKey},
[]api.ExchangeParam{emptyParams}, []api.ExchangeHeader{}, false, epf)
require.NoError(t, e)
result := testCcxtExchange.GetOrderConstraints(kase.pair)
assert.Equal(t, kase.wantPricePrecision, result.PricePrecision)
assert.Equal(t, kase.wantVolPrecision, result.VolumePrecision)
})
}
}