-
Notifications
You must be signed in to change notification settings - Fork 7
/
exchange.go
494 lines (441 loc) · 16.6 KB
/
exchange.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
package exchange
import (
"errors"
"log"
"time"
"github.com/mattkanwisher/cryptofiend/common"
"github.com/mattkanwisher/cryptofiend/config"
"github.com/mattkanwisher/cryptofiend/currency/pair"
"github.com/mattkanwisher/cryptofiend/exchanges/nonce"
"github.com/mattkanwisher/cryptofiend/exchanges/orderbook"
"github.com/mattkanwisher/cryptofiend/exchanges/ticker"
)
const (
warningBase64DecryptSecretKeyFailed = "WARNING -- Exchange %s unable to base64 decode secret key.. Disabling Authenticated API support."
// WarningAuthenticatedRequestWithoutCredentialsSet error message for authenticated request without credentials set
WarningAuthenticatedRequestWithoutCredentialsSet = "WARNING -- Exchange %s authenticated HTTP request called but not supported due to unset/default API keys."
// ErrExchangeNotFound is a constant for an error message
ErrExchangeNotFound = "Exchange not found in dataset."
// ErrExchangeOrderNotFound is one of the possible errors returned by IBotExchangeEx.GetOrder()
ErrOrderNotFound = "Exchange order not found."
)
var warningHTTPRequestRateLimited = errors.New("HTTP request was rate limited.")
var insufficentFundsForOrder = errors.New("insufficent funds for order")
// WarningHTTPRequestRateLimited() returns an error that indicates that a method of the
// IBotExchangeEx interface was rate limited.
func WarningHTTPRequestRateLimited() error {
return warningHTTPRequestRateLimited
}
// ErrInsufficentFundsForOrder returns an error that indicates that aren't sufficient
// funds available to place a new order on the exchange.
func ErrInsufficentFundsForOrder() error {
return insufficentFundsForOrder
}
// AccountInfo is a Generic type to hold each exchange's holdings in
// all enabled currencies
type AccountInfo struct {
ExchangeName string
Currencies []AccountCurrencyInfo
}
// AccountCurrencyInfo is a sub type to store currency name and value
type AccountCurrencyInfo struct {
CurrencyName string
TotalValue float64 // Hold + Available
Hold float64 // Amount on hold (used for currently open orders)
Available float64 // Amount actually available for placing orders
}
type OrderType string
type OrderSide string
const (
OrderSideBuy OrderSide = "buy"
OrderSideSell OrderSide = "sell"
)
const (
OrderTypeExchangeLimit OrderType = "exchange limit"
OrderTypeMarginLimit = "margin limit"
)
type OrderStatus string
const (
OrderStatusActive OrderStatus = "active"
OrderStatusFilled OrderStatus = "filled"
OrderStatusAborted OrderStatus = "aborted"
OrderStatusUnknown OrderStatus = "unknown"
)
type Order struct {
CurrencyPair pair.CurrencyPair
Type OrderType
Side OrderSide
Amount float64 //original amount requested
FilledAmount float64
RemainingAmount float64
Rate float64
CreatedAt int64 // timestamp
// LastUpdate int64 // timestamp
Status OrderStatus
OrderID string // Order ID generated by the exchange
InternalOrderID string // Order ID generated by the trading system (or bot)
}
type CurrencyPairInfo struct {
Currency pair.CurrencyPair
FirstCurrencyName string
SecondCurrencyName string
}
// Base stores the individual exchange information
type Base struct {
Name string
Enabled bool
Verbose bool
Websocket bool
RESTPollingDelay time.Duration
AuthenticatedAPISupport bool
APISecret, APIKey, ClientID string
Nonce nonce.Nonce
TakerFee, MakerFee, Fee float64
BaseCurrencies []string
AvailablePairs []string
EnabledPairs []string
AssetTypes []string
WebsocketURL string
APIUrl string
RequestCurrencyPairFormat config.CurrencyPairFormatConfig
ConfigCurrencyPairFormat config.CurrencyPairFormatConfig
Orderbooks orderbook.Orderbooks
}
// IBotExchange enforces standard functions for all exchanges supported in
// GoCryptoTrader
type IBotExchange interface {
Setup(exch config.ExchangeConfig)
Start()
SetDefaults()
GetName() string
IsEnabled() bool
GetTickerPrice(currency pair.CurrencyPair, assetType string) (ticker.Price, error)
UpdateTicker(currency pair.CurrencyPair, assetType string) (ticker.Price, error)
GetOrderbookEx(currency pair.CurrencyPair, assetType string) (orderbook.Base, error)
GetOrderbookSimple(currency pair.CurrencyPair, assetType string) (orderbook.Base, error)
UpdateOrderbook(currency pair.CurrencyPair, assetType string) (orderbook.Base, error)
GetEnabledCurrencies() []pair.CurrencyPair
GetExchangeAccountInfo() (AccountInfo, error)
GetAuthenticatedAPISupport() bool
}
// Extended bot interface for new methods
type IBotExchangeEx interface {
IBotExchange
Run()
// NewOrder creates a new order on the exchange.
// Returns the ID of the new exchange order, or an empty string if the order was filled
// immediately but no ID was generated.
NewOrder(symbol pair.CurrencyPair, amount, price float64, side OrderSide, orderType OrderType) (string, error)
// CancelOrder will attempt to cancel the active order matching the given ID.
// The currency pair may be required for some exchanges.
CancelOrder(OrderID string, currencyPair pair.CurrencyPair) error
// GetOrder returns information about a previously placed order (which may be active or inactive).
// The currency pair may be required for some exchanges.
GetOrder(orderID string, currencyPair pair.CurrencyPair) (*Order, error)
// GetOrders returns information about currently active orders.
// The pairs parameter should contain the currency pairs for which active orders should be retrieved,
// if this is parameter is nil or empty then all active orders will be retrieved.
GetOrders(pairs []pair.CurrencyPair) ([]*Order, error)
// GetLimits returns price/amount limits for the exchange.
GetLimits() ILimits
// Returns currency pairs that can be used by the exchange account associated with this bot.
// Use FormatExchangeCurrency to get the right key.
GetCurrencyPairs() map[pair.CurrencyItem]*CurrencyPairInfo
}
// SetAssetTypes checks the exchange asset types (whether it supports SPOT,
// Binary or Futures) and sets it to a default setting if it doesn't exist
func (e *Base) SetAssetTypes() error {
cfg := config.GetConfig()
exch, err := cfg.GetExchangeConfig(e.Name)
if err != nil {
return err
}
update := false
if exch.AssetTypes == "" {
exch.AssetTypes = common.JoinStrings(e.AssetTypes, ",")
update = true
} else {
e.AssetTypes = common.SplitStrings(exch.AssetTypes, ",")
}
if update {
return cfg.UpdateExchangeConfig(exch)
}
return nil
}
// GetExchangeAssetTypes returns the asset types the exchange supports (SPOT,
// binary, futures)
func GetExchangeAssetTypes(exchName string) ([]string, error) {
cfg := config.GetConfig()
exch, err := cfg.GetExchangeConfig(exchName)
if err != nil {
return nil, err
}
return common.SplitStrings(exch.AssetTypes, ","), nil
}
// SetCurrencyPairFormat checks the exchange request and config currency pair
// formats and sets it to a default setting if it doesn't exist
func (e *Base) SetCurrencyPairFormat() error {
cfg := config.GetConfig()
exch, err := cfg.GetExchangeConfig(e.Name)
if err != nil {
return err
}
update := false
if exch.RequestCurrencyPairFormat == nil {
exch.RequestCurrencyPairFormat = &config.CurrencyPairFormatConfig{
Delimiter: e.RequestCurrencyPairFormat.Delimiter,
Uppercase: e.RequestCurrencyPairFormat.Uppercase,
Separator: e.RequestCurrencyPairFormat.Separator,
Index: e.RequestCurrencyPairFormat.Index,
}
update = true
} else {
e.RequestCurrencyPairFormat = *exch.RequestCurrencyPairFormat
}
if exch.ConfigCurrencyPairFormat == nil {
exch.ConfigCurrencyPairFormat = &config.CurrencyPairFormatConfig{
Delimiter: e.ConfigCurrencyPairFormat.Delimiter,
Uppercase: e.ConfigCurrencyPairFormat.Uppercase,
Separator: e.ConfigCurrencyPairFormat.Separator,
Index: e.ConfigCurrencyPairFormat.Index,
}
update = true
} else {
e.ConfigCurrencyPairFormat = *exch.ConfigCurrencyPairFormat
}
if update {
return cfg.UpdateExchangeConfig(exch)
}
return nil
}
// GetAuthenticatedAPISupport returns whether the exchange supports
// authenticated API requests
func (e *Base) GetAuthenticatedAPISupport() bool {
return e.AuthenticatedAPISupport
}
// GetName is a method that returns the name of the exchange base
func (e *Base) GetName() string {
return e.Name
}
// Common exchange setup method so we can stop duplicating so much code
func (e *Base) CommonSetup(exch config.ExchangeConfig) {
e.BaseCurrencies = common.SplitStrings(exch.BaseCurrencies, ",")
e.AvailablePairs = common.SplitStrings(exch.AvailablePairs, ",")
e.EnabledPairs = common.SplitStrings(exch.EnabledPairs, ",")
}
// GetEnabledCurrencies is a method that returns the enabled currency pairs of
// the exchange base
func (e *Base) GetEnabledCurrencies() []pair.CurrencyPair {
var pairs []pair.CurrencyPair
for x := range e.EnabledPairs {
var currencyPair pair.CurrencyPair
if e.RequestCurrencyPairFormat.Delimiter != "" {
if e.ConfigCurrencyPairFormat.Delimiter != "" {
if e.ConfigCurrencyPairFormat.Delimiter == e.RequestCurrencyPairFormat.Delimiter {
currencyPair = pair.NewCurrencyPairDelimiter(e.EnabledPairs[x],
e.RequestCurrencyPairFormat.Delimiter)
} else {
currencyPair = pair.NewCurrencyPairDelimiter(e.EnabledPairs[x],
e.ConfigCurrencyPairFormat.Delimiter)
currencyPair.Delimiter = "-"
}
} else {
if e.ConfigCurrencyPairFormat.Index != "" {
currencyPair = pair.NewCurrencyPairFromIndex(e.EnabledPairs[x],
e.ConfigCurrencyPairFormat.Index)
} else {
currencyPair = pair.NewCurrencyPair(e.EnabledPairs[x][0:3],
e.EnabledPairs[x][3:])
}
}
} else {
if e.ConfigCurrencyPairFormat.Delimiter != "" {
currencyPair = pair.NewCurrencyPairDelimiter(e.EnabledPairs[x],
e.ConfigCurrencyPairFormat.Delimiter)
} else {
if e.ConfigCurrencyPairFormat.Index != "" {
currencyPair = pair.NewCurrencyPairFromIndex(e.EnabledPairs[x],
e.ConfigCurrencyPairFormat.Index)
} else {
currencyPair = pair.NewCurrencyPair(e.EnabledPairs[x][0:3],
e.EnabledPairs[x][3:])
}
}
}
pairs = append(pairs, currencyPair)
}
return pairs
}
// GetAvailableCurrencies is a method that returns the available currency pairs
// of the exchange base
func (e *Base) GetAvailableCurrencies() []pair.CurrencyPair {
var pairs []pair.CurrencyPair
for x := range e.AvailablePairs {
var currencyPair pair.CurrencyPair
if e.RequestCurrencyPairFormat.Delimiter != "" {
if e.ConfigCurrencyPairFormat.Delimiter != "" {
if e.ConfigCurrencyPairFormat.Delimiter == e.RequestCurrencyPairFormat.Delimiter {
currencyPair = pair.NewCurrencyPairDelimiter(e.AvailablePairs[x],
e.RequestCurrencyPairFormat.Delimiter)
} else {
currencyPair = pair.NewCurrencyPairDelimiter(e.AvailablePairs[x],
e.ConfigCurrencyPairFormat.Delimiter)
currencyPair.Delimiter = "-"
}
} else {
if e.ConfigCurrencyPairFormat.Index != "" {
currencyPair = pair.NewCurrencyPairFromIndex(e.AvailablePairs[x],
e.ConfigCurrencyPairFormat.Index)
} else {
currencyPair = pair.NewCurrencyPair(e.AvailablePairs[x][0:3],
e.AvailablePairs[x][3:])
}
}
} else {
if e.ConfigCurrencyPairFormat.Delimiter != "" {
currencyPair = pair.NewCurrencyPairDelimiter(e.AvailablePairs[x],
e.ConfigCurrencyPairFormat.Delimiter)
} else {
if e.ConfigCurrencyPairFormat.Index != "" {
currencyPair = pair.NewCurrencyPairFromIndex(e.AvailablePairs[x],
e.ConfigCurrencyPairFormat.Index)
} else {
currencyPair = pair.NewCurrencyPair(e.AvailablePairs[x][0:3],
e.AvailablePairs[x][3:])
}
}
}
pairs = append(pairs, currencyPair)
}
return pairs
}
// GetExchangeFormatCurrencySeperator returns whether or not a specific
// exchange contains a separator used for API requests
func GetExchangeFormatCurrencySeperator(exchName string) bool {
cfg := config.GetConfig()
exch, err := cfg.GetExchangeConfig(exchName)
if err != nil {
return false
}
if exch.RequestCurrencyPairFormat.Separator != "" {
return true
}
return false
}
// GetAndFormatExchangeCurrencies returns a pair.CurrencyItem string containing
// the exchanges formatted currency pairs
func GetAndFormatExchangeCurrencies(exchName string, pairs []pair.CurrencyPair) (pair.CurrencyItem, error) {
var currencyItems pair.CurrencyItem
cfg := config.GetConfig()
exch, err := cfg.GetExchangeConfig(exchName)
if err != nil {
return currencyItems, err
}
for x := range pairs {
currencyItems += FormatExchangeCurrency(exchName, pairs[x])
if x == len(pairs)-1 {
continue
}
currencyItems += pair.CurrencyItem(exch.RequestCurrencyPairFormat.Separator)
}
return currencyItems, nil
}
// FormatExchangeCurrency is a method that formats and returns a currency pair
// based on the user currency display preferences
func FormatExchangeCurrency(exchName string, p pair.CurrencyPair) pair.CurrencyItem {
cfg := config.GetConfig()
exch, _ := cfg.GetExchangeConfig(exchName)
return p.Display(exch.RequestCurrencyPairFormat.Delimiter,
exch.RequestCurrencyPairFormat.Uppercase)
}
func FormatExchangeCurrencyPair(exchName string, p pair.CurrencyPair) pair.CurrencyPair {
cfg := config.GetConfig()
exch, _ := cfg.GetExchangeConfig(exchName)
return p.FormatPair(exch.RequestCurrencyPairFormat.Delimiter,
exch.RequestCurrencyPairFormat.Uppercase)
}
func (e *Base) FormatExchangeCurrencyPair(p pair.CurrencyPair) pair.CurrencyPair {
return p.FormatPair(e.RequestCurrencyPairFormat.Delimiter,
e.RequestCurrencyPairFormat.Uppercase)
}
// FormatCurrency is a method that formats and returns a currency pair
// based on the user currency display preferences
func FormatCurrency(p pair.CurrencyPair) pair.CurrencyItem {
cfg := config.GetConfig()
return p.Display(cfg.CurrencyPairFormat.Delimiter,
cfg.CurrencyPairFormat.Uppercase)
}
// SetEnabled is a method that sets if the exchange is enabled
func (e *Base) SetEnabled(enabled bool) {
e.Enabled = enabled
}
// IsEnabled is a method that returns if the current exchange is enabled
func (e *Base) IsEnabled() bool {
return e.Enabled
}
// SetAPIKeys is a method that sets the current API keys for the exchange
func (e *Base) SetAPIKeys(APIKey, APISecret, ClientID string, b64Decode bool) {
if !e.AuthenticatedAPISupport {
return
}
e.APIKey = APIKey
e.ClientID = ClientID
if b64Decode {
result, err := common.Base64Decode(APISecret)
if err != nil {
e.AuthenticatedAPISupport = false
log.Printf(warningBase64DecryptSecretKeyFailed, e.Name)
}
e.APISecret = string(result)
} else {
e.APISecret = APISecret
}
}
// UpdateEnabledCurrencies is a method that sets new pairs to the current
// exchange. Setting force to true upgrades the enabled currencies
func (e *Base) UpdateEnabledCurrencies(exchangeProducts []string, force bool) error {
exchangeProducts = common.SplitStrings(common.StringToUpper(common.JoinStrings(exchangeProducts, ",")), ",")
diff := common.StringSliceDifference(e.EnabledPairs, exchangeProducts)
if force || len(diff) > 0 {
cfg := config.GetConfig()
exch, err := cfg.GetExchangeConfig(e.Name)
if err != nil {
return err
}
if force {
log.Printf("%s forced update of enabled pairs.", e.Name)
} else {
log.Printf("%s Updating available pairs. Difference: %s.\n", e.Name, diff)
}
exch.EnabledPairs = common.JoinStrings(exchangeProducts, ",")
e.EnabledPairs = exchangeProducts
return cfg.UpdateExchangeConfig(exch)
}
return nil
}
// UpdateAvailableCurrencies is a method that sets new pairs to the current
// exchange. Setting force to true upgrades the available currencies
func (e *Base) UpdateAvailableCurrencies(exchangeProducts []string, force bool) error {
exchangeProducts = common.SplitStrings(common.StringToUpper(common.JoinStrings(exchangeProducts, ",")), ",")
diff := common.StringSliceDifference(e.AvailablePairs, exchangeProducts)
if force || len(diff) > 0 {
cfg := config.GetConfig()
exch, err := cfg.GetExchangeConfig(e.Name)
if err != nil {
return err
}
if force {
log.Printf("%s forced update of available pairs.", e.Name)
} else {
log.Printf("%s Updating available pairs. Difference: %s.\n", e.Name, diff)
}
exch.AvailablePairs = common.JoinStrings(exchangeProducts, ",")
e.AvailablePairs = exchangeProducts
return cfg.UpdateExchangeConfig(exch)
}
return nil
}
// GetOrderbookSimple returns orderbook base on the currency pair, does not update exchange
func (e *Base) GetOrderbookSimple(p pair.CurrencyPair, assetType string) (orderbook.Base, error) {
return e.Orderbooks.GetOrderbook(e.GetName(), p, assetType)
}