forked from stellar-deprecated/kelp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ccxtExchange.go
443 lines (379 loc) · 14 KB
/
ccxtExchange.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
package plugins
import (
"fmt"
"log"
"sort"
"strconv"
"time"
"github.com/stellar/kelp/api"
"github.com/stellar/kelp/model"
"github.com/stellar/kelp/support/sdk"
"github.com/stellar/kelp/support/utils"
)
const ccxtBalancePrecision = 10
// ensure that ccxtExchange conforms to the Exchange interface
var _ api.Exchange = ccxtExchange{}
// ccxtExchange is the implementation for the CCXT REST library that supports many exchanges (https://github.com/franz-see/ccxt-rest, https://github.com/ccxt/ccxt/)
type ccxtExchange struct {
assetConverter *model.AssetConverter
delimiter string
ocOverridesHandler *OrderConstraintsOverridesHandler
api *sdk.Ccxt
simMode bool
}
// makeCcxtExchange is a factory method to make an exchange using the CCXT interface
func makeCcxtExchange(
exchangeName string,
orderConstraintOverrides map[model.TradingPair]model.OrderConstraints,
apiKeys []api.ExchangeAPIKey,
exchangeParams []api.ExchangeParam,
headers []api.ExchangeHeader,
simMode bool,
) (api.Exchange, error) {
if len(apiKeys) == 0 {
return nil, fmt.Errorf("need at least 1 ExchangeAPIKey, even if it is an empty key")
}
if len(apiKeys) != 1 {
return nil, fmt.Errorf("need exactly 1 ExchangeAPIKey")
}
c, e := sdk.MakeInitializedCcxtExchange(exchangeName, apiKeys[0], exchangeParams, headers)
if e != nil {
return nil, fmt.Errorf("error making a ccxt exchange: %s", e)
}
ocOverridesHandler := MakeEmptyOrderConstraintsOverridesHandler()
if orderConstraintOverrides != nil {
ocOverridesHandler = MakeOrderConstraintsOverridesHandler(orderConstraintOverrides)
}
return ccxtExchange{
assetConverter: model.CcxtAssetConverter,
delimiter: "/",
ocOverridesHandler: ocOverridesHandler,
api: c,
simMode: simMode,
}, nil
}
// GetTickerPrice impl.
func (c ccxtExchange) GetTickerPrice(pairs []model.TradingPair) (map[model.TradingPair]api.Ticker, error) {
pairsMap, e := model.TradingPairs2Strings(c.assetConverter, c.delimiter, pairs)
if e != nil {
return nil, e
}
priceResult := map[model.TradingPair]api.Ticker{}
for _, p := range pairs {
tickerMap, e := c.api.FetchTicker(pairsMap[p])
if e != nil {
return nil, fmt.Errorf("error while fetching ticker price for trading pair %s: %s", pairsMap[p], e)
}
askPrice, e := utils.CheckFetchFloat(tickerMap, "ask")
if e != nil {
return nil, fmt.Errorf("unable to correctly fetch value from tickerMap: %s", e)
}
bidPrice, e := utils.CheckFetchFloat(tickerMap, "bid")
if e != nil {
return nil, fmt.Errorf("unable to correctly fetch value from tickerMap: %s", e)
}
priceResult[p] = api.Ticker{
AskPrice: model.NumberFromFloat(askPrice, c.GetOrderConstraints(&p).PricePrecision),
BidPrice: model.NumberFromFloat(bidPrice, c.GetOrderConstraints(&p).PricePrecision),
}
}
return priceResult, nil
}
// GetAssetConverter impl
func (c ccxtExchange) GetAssetConverter() *model.AssetConverter {
return c.assetConverter
}
// GetOrderConstraints impl
func (c ccxtExchange) GetOrderConstraints(pair *model.TradingPair) *model.OrderConstraints {
pairString, e := pair.ToString(c.assetConverter, c.delimiter)
if e != nil {
// this should never really panic because we would have converted this trading pair to a string previously
panic(e)
}
// load from CCXT's cache
ccxtMarket := c.api.GetMarket(pairString)
if ccxtMarket == nil {
panic(fmt.Errorf("CCXT does not have precision and limit data for the passed in market: %s", pairString))
}
oc := model.MakeOrderConstraintsWithCost(ccxtMarket.Precision.Price, ccxtMarket.Precision.Amount, ccxtMarket.Limits.Amount.Min, ccxtMarket.Limits.Cost.Min)
return c.ocOverridesHandler.Apply(pair, oc)
}
// OverrideOrderConstraints impl, can partially override values for specific pairs
func (c ccxtExchange) OverrideOrderConstraints(pair *model.TradingPair, override *model.OrderConstraintsOverride) {
c.ocOverridesHandler.Upsert(pair, override)
}
// GetAccountBalances impl
func (c ccxtExchange) GetAccountBalances(assetList []interface{}) (map[interface{}]model.Number, error) {
balanceResponse, e := c.api.FetchBalance()
if e != nil {
return nil, e
}
m := map[interface{}]model.Number{}
for _, elem := range assetList {
var asset model.Asset
if v, ok := elem.(model.Asset); ok {
asset = v
} else {
return nil, fmt.Errorf("invalid type of asset passed in, only model.Asset accepted")
}
ccxtAssetString, e := c.GetAssetConverter().ToString(asset)
if e != nil {
return nil, e
}
if ccxtBalance, ok := balanceResponse[ccxtAssetString]; ok {
m[asset] = *model.NumberFromFloat(ccxtBalance.Total, ccxtBalancePrecision)
} else {
m[asset] = *model.NumberConstants.Zero
}
}
return m, nil
}
// GetOrderBook impl
func (c ccxtExchange) GetOrderBook(pair *model.TradingPair, maxCount int32) (*model.OrderBook, error) {
pairString, e := pair.ToString(c.assetConverter, c.delimiter)
if e != nil {
return nil, fmt.Errorf("error converting pair to string: %s", e)
}
limit := int(maxCount)
ob, e := c.api.FetchOrderBook(pairString, &limit)
if e != nil {
return nil, fmt.Errorf("error while fetching orderbook for trading pair '%s': %s", pairString, e)
}
if _, ok := ob["asks"]; !ok {
return nil, fmt.Errorf("orderbook did not contain the 'asks' field: %v", ob)
}
if _, ok := ob["bids"]; !ok {
return nil, fmt.Errorf("orderbook did not contain the 'bids' field: %v", ob)
}
asks := c.readOrders(ob["asks"], pair, model.OrderActionSell)
bids := c.readOrders(ob["bids"], pair, model.OrderActionBuy)
return model.MakeOrderBook(pair, asks, bids), nil
}
func (c ccxtExchange) readOrders(orders []sdk.CcxtOrder, pair *model.TradingPair, orderAction model.OrderAction) []model.Order {
pricePrecision := c.GetOrderConstraints(pair).PricePrecision
volumePrecision := c.GetOrderConstraints(pair).VolumePrecision
result := []model.Order{}
for _, o := range orders {
result = append(result, model.Order{
Pair: pair,
OrderAction: orderAction,
OrderType: model.OrderTypeLimit,
Price: model.NumberFromFloat(o.Price, pricePrecision),
Volume: model.NumberFromFloat(o.Amount, volumePrecision),
Timestamp: nil,
})
}
return result
}
// GetTradeHistory impl
func (c ccxtExchange) GetTradeHistory(pair model.TradingPair, maybeCursorStart interface{}, maybeCursorEnd interface{}) (*api.TradeHistoryResult, error) {
pairString, e := pair.ToString(c.assetConverter, c.delimiter)
if e != nil {
return nil, fmt.Errorf("error converting pair to string: %s", e)
}
// TODO fix limit logic to check result so we get full history instead of just 50 trades
const limit = 50
tradesRaw, e := c.api.FetchMyTrades(pairString, limit, maybeCursorStart)
if e != nil {
return nil, fmt.Errorf("error while fetching trade history for trading pair '%s': %s", pairString, e)
}
trades := []model.Trade{}
for _, raw := range tradesRaw {
var t *model.Trade
t, e = c.readTrade(&pair, pairString, raw)
if e != nil {
return nil, fmt.Errorf("error while reading trade: %s", e)
}
trades = append(trades, *t)
}
sort.Sort(model.TradesByTsID(trades))
cursor := maybeCursorStart
if len(trades) > 0 {
lastCursor := trades[len(trades)-1].Order.Timestamp.AsInt64()
// add 1 to lastCursor so we don't repeat the same cursor on the next run
cursor = strconv.FormatInt(lastCursor+1, 10)
}
return &api.TradeHistoryResult{
Cursor: cursor,
Trades: trades,
}, nil
}
// GetLatestTradeCursor impl.
func (c ccxtExchange) GetLatestTradeCursor() (interface{}, error) {
timeNowMillis := time.Now().UnixNano() / int64(time.Millisecond)
latestTradeCursor := fmt.Sprintf("%d", timeNowMillis)
return latestTradeCursor, nil
}
// GetTrades impl
func (c ccxtExchange) GetTrades(pair *model.TradingPair, maybeCursor interface{}) (*api.TradesResult, error) {
pairString, e := pair.ToString(c.assetConverter, c.delimiter)
if e != nil {
return nil, fmt.Errorf("error converting pair to string: %s", e)
}
// TODO use cursor when fetching trades
tradesRaw, e := c.api.FetchTrades(pairString)
if e != nil {
return nil, fmt.Errorf("error while fetching trades for trading pair '%s': %s", pairString, e)
}
trades := []model.Trade{}
for _, raw := range tradesRaw {
var t *model.Trade
t, e = c.readTrade(pair, pairString, raw)
if e != nil {
return nil, fmt.Errorf("error while reading trade: %s", e)
}
trades = append(trades, *t)
}
sort.Sort(model.TradesByTsID(trades))
cursor := maybeCursor
if len(trades) > 0 {
lastCursor := trades[len(trades)-1].Order.Timestamp.AsInt64()
// add 1 to lastCursor so we don't repeat the same cursor on the next run
cursor = strconv.FormatInt(lastCursor+1, 10)
}
return &api.TradesResult{
Cursor: cursor,
Trades: trades,
}, nil
}
func (c ccxtExchange) readTrade(pair *model.TradingPair, pairString string, rawTrade sdk.CcxtTrade) (*model.Trade, error) {
if rawTrade.Symbol != pairString {
return nil, fmt.Errorf("expected '%s' for 'symbol' field, got: %s", pairString, rawTrade.Symbol)
}
pricePrecision := c.GetOrderConstraints(pair).PricePrecision
volumePrecision := c.GetOrderConstraints(pair).VolumePrecision
// use bigger precision for fee and cost since they are logically derived from amount and price
feecCostPrecision := pricePrecision
if volumePrecision > pricePrecision {
feecCostPrecision = volumePrecision
}
trade := model.Trade{
Order: model.Order{
Pair: pair,
Price: model.NumberFromFloat(rawTrade.Price, pricePrecision),
Volume: model.NumberFromFloat(rawTrade.Amount, volumePrecision),
OrderType: model.OrderTypeLimit,
Timestamp: model.MakeTimestamp(rawTrade.Timestamp),
},
TransactionID: model.MakeTransactionID(rawTrade.ID),
Fee: model.NumberFromFloat(rawTrade.Fee.Cost, feecCostPrecision),
}
if rawTrade.Side == "sell" {
trade.OrderAction = model.OrderActionSell
} else if rawTrade.Side == "buy" {
trade.OrderAction = model.OrderActionBuy
} else {
return nil, fmt.Errorf("unrecognized value for 'side' field: %s", rawTrade.Side)
}
if rawTrade.Cost != 0.0 {
trade.Cost = model.NumberFromFloat(rawTrade.Cost, feecCostPrecision)
}
return &trade, nil
}
// GetOpenOrders impl
func (c ccxtExchange) GetOpenOrders(pairs []*model.TradingPair) (map[model.TradingPair][]model.OpenOrder, error) {
pairStrings := []string{}
string2Pair := map[string]model.TradingPair{}
for _, pair := range pairs {
pairString, e := pair.ToString(c.assetConverter, c.delimiter)
if e != nil {
return nil, fmt.Errorf("error converting pairs to strings: %s", e)
}
pairStrings = append(pairStrings, pairString)
string2Pair[pairString] = *pair
}
openOrdersMap, e := c.api.FetchOpenOrders(pairStrings)
if e != nil {
return nil, fmt.Errorf("error while fetching open orders for trading pairs '%v': %s", pairStrings, e)
}
result := map[model.TradingPair][]model.OpenOrder{}
for asset, ccxtOrderList := range openOrdersMap {
pair, ok := string2Pair[asset]
if !ok {
return nil, fmt.Errorf("symbol %s returned from FetchOpenOrders was not in the original list of trading pairs: %v", asset, pairStrings)
}
openOrderList := []model.OpenOrder{}
for _, o := range ccxtOrderList {
openOrder, e := c.convertOpenOrderFromCcxt(&pair, o)
if e != nil {
return nil, fmt.Errorf("cannot convertOpenOrderFromCcxt: %s", e)
}
openOrderList = append(openOrderList, *openOrder)
}
result[pair] = openOrderList
}
return result, nil
}
func (c ccxtExchange) convertOpenOrderFromCcxt(pair *model.TradingPair, o sdk.CcxtOpenOrder) (*model.OpenOrder, error) {
if o.Type != "limit" {
return nil, fmt.Errorf("we currently only support limit order types")
}
orderAction := model.OrderActionSell
if o.Side == "buy" {
orderAction = model.OrderActionBuy
}
ts := model.MakeTimestamp(o.Timestamp)
return &model.OpenOrder{
Order: model.Order{
Pair: pair,
OrderAction: orderAction,
OrderType: model.OrderTypeLimit,
Price: model.NumberFromFloat(o.Price, c.GetOrderConstraints(pair).PricePrecision),
Volume: model.NumberFromFloat(o.Amount, c.GetOrderConstraints(pair).VolumePrecision),
Timestamp: ts,
},
ID: o.ID,
StartTime: ts,
ExpireTime: nil,
VolumeExecuted: model.NumberFromFloat(o.Filled, c.GetOrderConstraints(pair).VolumePrecision),
}, nil
}
// AddOrder impl
func (c ccxtExchange) AddOrder(order *model.Order) (*model.TransactionID, error) {
pairString, e := order.Pair.ToString(c.assetConverter, c.delimiter)
if e != nil {
return nil, fmt.Errorf("error converting pair to string: %s", e)
}
side := "sell"
if order.OrderAction.IsBuy() {
side = "buy"
}
log.Printf("ccxt is submitting order: pair=%s, orderAction=%s, orderType=%s, volume=%s, price=%s\n",
pairString, order.OrderAction.String(), order.OrderType.String(), order.Volume.AsString(), order.Price.AsString())
ccxtOpenOrder, e := c.api.CreateLimitOrder(pairString, side, order.Volume.AsFloat(), order.Price.AsFloat())
if e != nil {
return nil, fmt.Errorf("error while creating limit order %s: %s", *order, e)
}
return model.MakeTransactionID(ccxtOpenOrder.ID), nil
}
// CancelOrder impl
func (c ccxtExchange) CancelOrder(txID *model.TransactionID, pair model.TradingPair) (model.CancelOrderResult, error) {
log.Printf("ccxt is canceling order: ID=%s, tradingPair: %s\n", txID.String(), pair.String())
resp, e := c.api.CancelOrder(txID.String(), pair.String())
if e != nil {
return model.CancelResultFailed, e
}
if resp == nil {
return model.CancelResultFailed, fmt.Errorf("response from CancelOrder was nil")
}
return model.CancelResultCancelSuccessful, nil
}
// PrepareDeposit impl
func (c ccxtExchange) PrepareDeposit(asset model.Asset, amount *model.Number) (*api.PrepareDepositResult, error) {
// TODO implement
return nil, nil
}
// GetWithdrawInfo impl
func (c ccxtExchange) GetWithdrawInfo(asset model.Asset, amountToWithdraw *model.Number, address string) (*api.WithdrawInfo, error) {
// TODO implement
return nil, nil
}
// WithdrawFunds impl
func (c ccxtExchange) WithdrawFunds(
asset model.Asset,
amountToWithdraw *model.Number,
address string,
) (*api.WithdrawFunds, error) {
// TODO implement
return nil, nil
}