-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathccxt.js
11249 lines (10498 loc) · 378 KB
/
ccxt.js
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
(function () {
//-----------------------------------------------------------------------------
var version = '1.1.56'
var isNode = (typeof window === 'undefined')
//-----------------------------------------------------------------------------
class CCXTError extends Error {
constructor (message) {
super (message)
// a workaround to make `instanceof CCXTError` work in ES5
this.constructor = CCXTError
this.__proto__ = CCXTError.prototype
this.message = message
}
}
class DDoSProtectionError extends CCXTError {
constructor (message) {
super (message)
this.constructor = DDoSProtectionError
this.__proto__ = DDoSProtectionError.prototype
this.message = message
}
}
class TimeoutError extends CCXTError {
constructor (message) {
super (message)
this.constructor = TimeoutError
this.__proto__ = TimeoutError.prototype
this.message = message
}
}
class AuthenticationError extends CCXTError {
constructor (message) {
super (message)
this.constructor = AuthenticationError
this.__proto__ = AuthenticationError.prototype
this.message = message
}
}
class NotAvailableError extends CCXTError {
constructor (message) {
super (message)
this.constructor = NotAvailableError
this.__proto__ = NotAvailableError.prototype
this.message = message
}
}
class MarketNotAvailableError extends NotAvailableError {
constructor (message) {
super (message)
this.constructor = MarketNotAvailableError
this.__proto__ = MarketNotAvailableError.prototype
this.message = message
}
}
class EndpointNotAvailableError extends NotAvailableError {
constructor (message) {
super (message)
this.constructor = EndpointNotAvailableError
this.__proto__ = EndpointNotAvailableError.prototype
this.message = message
}
}
class OrderBookNotAvailableError extends NotAvailableError {
constructor (message) {
super (message)
this.constructor = OrderBookNotAvailableError
this.__proto__ = OrderBookNotAvailableError.prototype
this.message = message
}
}
class TickerNotAvailableError extends NotAvailableError {
constructor (message) {
super (message)
this.constructor = TickerNotAvailableError
this.__proto__ = TickerNotAvailableError.prototype
this.message = message
}
}
//-----------------------------------------------------------------------------
// utility helpers
let sleep = ms => new Promise (resolve => setTimeout (resolve, ms));
var timeout = (ms, promise) =>
Promise.race ([
promise,
sleep (ms).then (() => { throw new TimeoutError ('request timed out') })
])
var capitalize = function (string) {
return string.length ? (string.charAt (0).toUpperCase () + string.slice (1)) : string
}
var keysort = function (object) {
const result = {}
Object.keys (object).sort ().forEach (key => result[key] = object[key])
return result
}
var extend = function () {
const result = {}
for (var i = 0; i < arguments.length; i++)
if (typeof arguments[i] === 'object')
Object.keys (arguments[i]).forEach (key =>
(result[key] = arguments[i][key]))
return result
}
var omit = function (object) {
var result = extend (object)
for (var i = 1; i < arguments.length; i++)
if (typeof arguments[i] === 'string')
delete result[arguments[i]]
else if (Array.isArray (arguments[i]))
for (var k = 0; k < arguments[i].length; k++)
delete result[arguments[i][k]]
return result
}
var indexBy = function (array, key) {
const result = {}
for (var i = 0; i < array.length; i++) {
let element = array[i]
if (typeof element[key] != 'undefined') {
result[element[key]] = element
}
}
return result
}
var sortBy = function (array, key, descending = false) {
descending = descending ? -1 : 1
return array.sort ((a, b) => ((a[key] < b[key]) ? -descending : ((a[key] > b[key]) ? descending : 0)))
}
var flatten = function (array, result = []) {
for (let i = 0, length = array.length; i < length; i++) {
const value = array[i]
if (Array.isArray (value)) {
flatten (value, result)
} else {
result.push (value)
}
}
return result
}
var unique = function (array) {
return array.filter ((value, index, self) => (self.indexOf (value) == index))
}
var pluck = function (array, key) {
return (array
.filter (element => (typeof element[key] != 'undefined'))
.map (element => element[key]))
}
var urlencode = function (object) {
return Object.keys (object).map (key =>
encodeURIComponent (key) + '=' + encodeURIComponent (object[key])).join ('&')
}
var sum = function (... args) {
let result = args.filter (arg => typeof arg != 'undefined')
return (result.length > 1) ?
result.reduce ((sum, value) => sum + value, 0) :
undefined
}
//-----------------------------------------------------------------------------
// platform-specific code (Node.js / Web Browsers)
if (isNode) {
var CryptoJS = require ('crypto-js')
var fetch = require ('node-fetch')
} else {
// a quick fetch polyfill
var fetch = function (url, options, verbose = false) {
return new Promise ((resolve, reject) => {
if (verbose)
console.log (url, options)
var xhr = new XMLHttpRequest ()
var method = options.method || 'GET'
xhr.open (method, url, true)
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
if (xhr.status == 200)
resolve (xhr.responseText)
else { // [403, 404, ...].indexOf (xhr.status) >= 0
throw new Error (method, url, xhr.status, xhr.responseText)
}
}
}
if (typeof options.headers != 'undefined')
for (var header in options.headers)
xhr.setRequestHeader (header, options.headers[header])
xhr.send (options.body)
})
}
}
//-----------------------------------------------------------------------------
// string ←→ binary ←→ base64 conversion routines
var stringToBinary = function (string) {
return CryptoJS.enc.Latin1.parse (string)
}
var stringToBase64 = function (string) {
return CryptoJS.enc.Latin1.parse (string).toString (CryptoJS.enc.Base64)
}
var utf16ToBase64 = function (string) {
return CryptoJS.enc.Utf16.parse (string).toString (CryptoJS.enc.Base64)
}
var base64ToBinary = function (string) {
return CryptoJS.enc.Base64.parse (string)
}
var base64ToString = function (string) {
return CryptoJS.enc.Base64.parse (string).toString (CryptoJS.enc.Utf8)
}
// url-safe-base64 without equals signs, with + replaced by - and slashes replaced by underscores
var urlencodeBase64 = function (base64string) {
return base64string.replace (/[=]+$/, '').replace (/\+/g, '-').replace (/\//g, '_')
}
//-----------------------------------------------------------------------------
// cryptography
var hash = function (request, hash = 'md5', digest = 'hex') {
var encoding = (digest === 'binary') ? 'Latin1' : capitalize (digest)
return CryptoJS[hash.toUpperCase ()] (request).toString (CryptoJS.enc[encoding])
}
var hmac = function (request, secret, hash = 'sha256', digest = 'hex') {
var encoding = (digest === 'binary') ? 'Latin1' : capitalize (digest)
return CryptoJS['Hmac' + hash.toUpperCase ()] (request, secret).toString (CryptoJS.enc[capitalize (encoding)])
}
//-----------------------------------------------------------------------------
// a JSON Web Token authentication method
var jwt = function (request, secret, alg = 'HS256', hash = 'sha256') {
var encodedHeader = urlencodeBase64 (stringToBase64 (JSON.stringify ({ 'alg': alg, 'typ': 'JWT' })))
var encodedData = urlencodeBase64 (stringToBase64 (JSON.stringify (request)))
var token = [ encodedHeader, encodedData ].join ('.')
var signature = urlencodeBase64 (utf16ToBase64 (hmac (token, secret, hash, 'utf16')))
return [ token, signature ].join ('.')
}
//-----------------------------------------------------------------------------
// the base class
var Market = function (config) {
this.hash = hash
this.hmac = hmac
this.jwt = jwt // JSON Web Token
this.stringToBinary = stringToBinary
this.stringToBase64 = stringToBase64
this.base64ToBinary = base64ToBinary
this.base64ToString = base64ToString
this.utf16ToBase64 = utf16ToBase64
this.urlencode = urlencode
this.omit = omit
this.pluck = pluck
this.unique = unique
this.extend = extend
this.flatten = flatten
this.indexBy = indexBy
this.sortBy = sortBy
this.keysort = keysort
this.capitalize = capitalize
this.json = JSON.stringify
this.sum = sum
this.encode = string => string
this.decode = string => string
this.init = function () {
if (isNode)
this.nodeVersion = process.version.match (/\d+\.\d+.\d+/) [0]
if (this.api)
Object.keys (this.api).forEach (type => {
Object.keys (this.api[type]).forEach (method => {
var urls = this.api[type][method]
for (var i = 0; i < urls.length; i++) {
let url = urls[i].trim ()
let splitPath = url.split (/[^a-zA-Z0-9]/)
let uppercaseMethod = method.toUpperCase ()
let lowercaseMethod = method.toLowerCase ()
let camelcaseMethod = capitalize (lowercaseMethod)
let camelcaseSuffix = splitPath.map (capitalize).join ('')
let underscoreSuffix = splitPath.map (x => x.trim ().toLowerCase ()).filter (x => x.length > 0).join ('_')
if (camelcaseSuffix.indexOf (camelcaseMethod) === 0)
camelcaseSuffix = camelcaseSuffix.slice (camelcaseMethod.length)
if (underscoreSuffix.indexOf (lowercaseMethod) === 0)
underscoreSuffix = underscoreSuffix.slice (lowercaseMethod.length)
let camelcase = type + camelcaseMethod + capitalize (camelcaseSuffix)
let underscore = type + '_' + lowercaseMethod + '_' + underscoreSuffix
let f = (params => this.request (url, type, uppercaseMethod, params))
this[camelcase] = f
this[underscore] = f
}
})
})
}
this.fetch = function (url, method = 'GET', headers = undefined, body = undefined) {
if (isNode) {
headers = extend ({
'User-Agent': 'ccxt/' + version +
' (+https://github.com/kroitor/ccxt)' +
' Node.js/' + this.nodeVersion + ' (JavaScript)'
}, headers)
}
if (this.proxy.length)
headers = extend ({ 'Origin': '*' }, headers)
let options = { 'method': method, 'headers': headers, 'body': body }
url = this.proxy + url
if (this.verbose)
console.log (this.id, url, options)
return timeout (this.timeout, fetch (url, options)
.catch (e => {
if (isNode) {
throw new MarketNotAvailableError ([ this.id, method, url, e.type, e.message ].join (' '))
}
throw e // rethrow all unknown errors
})
.then (response => {
if (typeof response == 'string')
return response
return response.text ().then (text => {
if (response.status == 200)
return text
let error = undefined
let details = undefined
if ([ 429 ].indexOf (response.status) >= 0) {
error = DDoSProtectionError
} else if ([ 500, 501, 502, 404 ].indexOf (response.status) >= 0) {
error = MarketNotAvailableError
} else if ([ 400, 403, 405, 503 ].indexOf (response.status) >= 0) {
let ddosProtection = text.match (/cloudflare|incapsula/i)
if (ddosProtection) {
error = DDoSProtectionError
} else {
error = MarketNotAvailableError
details = 'Possible reasons: ' + [
'invalid API keys',
'market down or offline',
'on maintenance',
'DDoS protection',
'rate-limiting in effect',
].join (', ')
}
} else if ([ 408, 504 ].indexOf (response.status) >= 0) {
error = TimeoutError
} else if ([ 401, 422, 511 ].indexOf (response.status) >= 0) {
error = AuthenticationError
} else {
error = Error
details = 'Unknown Error'
}
throw new error ([ this.id, method, url, response.status, response.statusText, details ].join (' '))
})
}).then (response => this.handleResponse (url, method, headers, response)))
}
this.handleResponse = function (url, method = 'GET', headers = undefined, body = undefined) {
if (body.match (/offline|unavailable|maintain|maintenanc(?:e|ing)/i))
throw new MarketNotAvailableError (this.id + ' is offline, on maintenance or unreachable from this location at the moment')
if (body.match (/cloudflare|incapsula|overload/i))
throw new DDoSProtectionError (this.id + ' is not accessible from this location at the moment')
try {
return JSON.parse (body)
} catch (e) {
if (this.verbose)
console.log (this.id, 'error', e, 'response body: \'' + body + '\'')
throw e
}
}
this.set_products =
this.setProducts = function (products) {
let values = Object.values (products)
this.products = indexBy (values, 'symbol')
this.productsById = indexBy (products, 'id')
this.products_by_id = this.productsById
this.symbols = Object.keys (this.products)
let base = this.pluck (values.filter (product => 'base' in product), 'base')
let quote = this.pluck (values.filter (product => 'quote' in product), 'quote')
this.currencies = this.unique (base.concat (quote))
return this.products
}
this.load_products =
this.loadProducts = function (reload = false) {
if (!reload && this.products) {
if (!this.productsById) {
return this.setProducts (this.products)
}
return new Promise ((resolve, reject) => resolve (this.products))
}
return this.fetchProducts ().then (products => {
return this.setProducts (products)
})
}
this.fetch_products =
this.fetchProducts = function () {
return new Promise ((resolve, reject) => resolve (this.products))
}
this.commonCurrencyCode = function (currency) {
return (currency === 'XBT') ? 'BTC' : currency
}
this.product = function (product) {
return (((typeof product === 'string') &&
(typeof this.products != 'undefined') &&
(typeof this.products[product] != 'undefined')) ?
this.products[product] :
product)
}
this.product_id =
this.productId = function (product) {
return this.product (product).id || product
}
this.symbol = function (product) {
return this.product (product).symbol || product
}
this.extract_params =
this.extractParams = function (string) {
var re = /{([a-zA-Z0-9_]+?)}/g
var matches = []
let match
while (match = re.exec (string))
matches.push (match[1])
return matches
}
this.implode_params =
this.implodeParams = function (string, params) {
for (var property in params)
string = string.replace ('{' + property + '}', params[property])
return string
}
this.create_limit_buy_order =
this.createLimitBuyOrder = function (product, amount, price, params = {}) {
return this.createOrder (product, 'limit', 'buy', amount, price, params)
}
this.create_limit_sell_order =
this.createLimitSellOrder = function (product, amount, price, params = {}) {
return this.createOrder (product, 'limit', 'sell', amount, price, params)
}
this.create_market_buy_order =
this.createMarketBuyOrder = function (product, amount, params = {}) {
return this.createOrder (product, 'market', 'buy', amount, params)
}
this.create_market_sell_order =
this.createMarketSellOrder = function (product, amount, params = {}) {
return this.createOrder (product, 'market', 'sell', amount, params)
}
this.iso8601 = timestamp => new Date (timestamp).toISOString ()
this.parse8601 = Date.parse
this.seconds = () => Math.floor (this.milliseconds () / 1000)
this.microseconds = () => Math.floor (this.milliseconds () * 1000)
this.milliseconds = Date.now
this.nonce = this.seconds
this.id = undefined
this.rateLimit = 2000 // milliseconds = seconds * 1000
this.timeout = 10000 // milliseconds = seconds * 1000
this.verbose = false
this.yyyymmddhhmmss = timestamp => {
let date = new Date (timestamp)
let yyyy = date.getUTCFullYear ()
let MM = date.getUTCMonth ()
let dd = date.getUTCDay ()
let hh = date.getUTCHours ()
let mm = date.getUTCMinutes ()
let ss = date.getUTCSeconds ()
MM = MM < 10 ? ('0' + MM) : MM
dd = dd < 10 ? ('0' + dd) : dd
hh = hh < 10 ? ('0' + hh) : hh
mm = mm < 10 ? ('0' + mm) : mm
ss = ss < 10 ? ('0' + ss) : ss
return yyyy + '-' + MM + '-' + dd + ' ' + hh + ':' + mm + ':' + ss
}
// prepended to URL, like https://proxy.com/https://exchange.com/api...
this.proxy = ''
for (var property in config)
this[property] = config[property]
this.fetch_balance = this.fetchBalance
this.fetch_order_book = this.fetchOrderBook
this.fetch_ticker = this.fetchTicker
this.fetch_trades = this.fetchTrades
this.init ()
}
//=============================================================================
var _1broker = {
'id': '_1broker',
'name': '1Broker',
'countries': 'US',
'rateLimit': 2000,
'version': 'v2',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766021-420bd9fc-5ecb-11e7-8ed6-56d0081efed2.jpg',
'api': 'https://1broker.com/api',
'www': 'https://1broker.com',
'doc': 'https://1broker.com/?c=en/content/api-documentation',
},
'api': {
'private': {
'get': [
'market/bars',
'market/categories',
'market/details',
'market/list',
'market/quotes',
'market/ticks',
'order/cancel',
'order/create',
'order/open',
'position/close',
'position/close_cancel',
'position/edit',
'position/history',
'position/open',
'position/shared/get',
'social/profile_statistics',
'social/profile_trades',
'user/bitcoin_deposit_address',
'user/details',
'user/overview',
'user/quota_status',
'user/transaction_log',
],
},
},
async fetchCategories () {
let categories = await this.privateGetMarketCategories ();
return categories['response'];
},
async fetchProducts () {
let this_ = this; // workaround for Babel bug (not passing `this` to _recursive() call)
let categories = await this.fetchCategories ();
let result = [];
for (let c = 0; c < categories.length; c++) {
let category = categories[c];
let products = await this_.privateGetMarketList ({
'category': category.toLowerCase (),
});
for (let p = 0; p < products['response'].length; p++) {
let product = products['response'][p];
let id = product['symbol'];
let symbol = undefined;
let base = undefined;
let quote = undefined;
if ((category == 'FOREX') || (category == 'CRYPTO')) {
symbol = product['name'];
let parts = symbol.split ('/');
base = parts[0];
quote = parts[1];
} else {
base = id;
quote = 'USD';
symbol = base + '/' + quote;
}
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': product,
});
}
}
return result;
},
async fetchBalance () {
let balance = await this.privateGetUserOverview ();
let response = balance['response'];
let result = { 'info': response };
for (let c = 0; c < this.currencies.length; c++) {
let currency = this.currencies[c];
result[currency] = {
'free': undefined,
'used': undefined,
'total': undefined,
};
}
result['BTC']['free'] = parseFloat (response['balance']);
result['BTC']['total'] = result['BTC']['free'];
return result;
},
async fetchOrderBook (product) {
let response = await this.privateGetMarketQuotes ({
'symbols': this.productId (product),
});
let orderbook = response['response'][0];
let timestamp = this.parse8601 (orderbook['updated']);
let bidPrice = parseFloat (orderbook['bid']);
let askPrice = parseFloat (orderbook['ask']);
let bid = [ bidPrice, undefined ];
let ask = [ askPrice, undefined ];
return {
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'bids': [ bid ],
'asks': [ ask ],
};
},
async fetchTicker (product) {
let result = await this.privateGetMarketBars ({
'symbol': this.productId (product),
'resolution': 60,
'limit': 1,
});
let orderbook = await this.fetchOrderBook (product);
let ticker = result['response'][0];
let timestamp = this.parse8601 (ticker['date']);
return {
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': parseFloat (ticker['h']),
'low': parseFloat (ticker['l']),
'bid': orderbook['bids'][0][0],
'ask': orderbook['asks'][0][0],
'vwap': undefined,
'open': parseFloat (ticker['o']),
'close': parseFloat (ticker['c']),
'first': undefined,
'last': undefined,
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': undefined,
'quoteVolume': undefined,
};
},
createOrder (product, type, side, amount, price = undefined, params = {}) {
let order = {
'symbol': this.productId (product),
'margin': amount,
'direction': (side == 'sell') ? 'short' : 'long',
'leverage': 1,
'type': side,
};
if (type == 'limit')
order['price'] = price;
else
order['type'] += '_market';
return this.privateGetOrderCreate (this.extend (order, params));
},
cancelOrder (id) {
return this.privatePostOrderCancel ({ 'order_id': id });
},
request (path, type = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
if (!this.apiKey)
throw new AuthenticationError (this.id + ' requires apiKey for all requests');
let url = this.urls['api'] + '/' + this.version + '/' + path + '.php';
let query = this.extend ({ 'token': this.apiKey }, params);
url += '?' + this.urlencode (query);
return this.fetch (url, method);
},
}
//-----------------------------------------------------------------------------
var cryptocapital = {
'id': 'cryptocapital',
'name': 'Crypto Capital',
'comment': 'Crypto Capital API',
'countries': 'PA', // Panama
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27993158-7a13f140-64ac-11e7-89cc-a3b441f0b0f8.jpg',
'www': 'https://cryptocapital.co',
'doc': 'https://github.com/cryptocap',
},
'api': {
'public': {
'get': [
'stats',
'historical-prices',
'order-book',
'transactions',
],
},
'private': {
'post': [
'balances-and-info',
'open-orders',
'user-transactions',
'btc-deposit-address/get',
'btc-deposit-address/new',
'deposits/get',
'withdrawals/get',
'orders/new',
'orders/edit',
'orders/cancel',
'orders/status',
'withdrawals/new',
],
},
},
'products': {
},
async fetchBalance () {
let response = await this.privatePostBalancesAndInfo ();
let balance = response['balances-and-info'];
let result = { 'info': balance };
for (let c = 0; c < this.currencies.length; c++) {
let currency = this.currencies[c];
let account = {
'free': undefined,
'used': undefined,
'total': undefined,
};
if (currency in balance['available'])
account['free'] = balance['available'][currency];
if (currency in balance['on_hold'])
account['used'] = balance['on_hold'][currency];
account['total'] = this.sum (account['free'], account['used']);
result[currency] = account;
}
return result;
},
async fetchOrderBook (product) {
let response = await this.publicGetOrderBook ({
'currency': this.productId (product),
});
let orderbook = response['order-book'];
let timestamp = this.milliseconds ();
let result = {
'bids': [],
'asks': [],
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
};
let sides = { 'bids': 'bid', 'asks': 'ask' };
let keys = Object.keys (sides);
for (let k = 0; k < keys.length; k++) {
let key = keys[k];
let side = sides[key];
let orders = orderbook[side];
for (let i = 0; i < orders.length; i++) {
let order = orders[i];
let timestamp = parseInt (order['timestamp']) * 1000;
let price = parseFloat (order['price']);
let amount = parseFloat (order['order_amount']);
result[key].push ([ price, amount, timestamp ]);
}
}
return result;
},
async fetchTicker (product) {
let response = await this.publicGetStats ({
'currency': this.productId (product),
});
let ticker = response['stats'];
let timestamp = this.milliseconds ();
return {
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': parseFloat (ticker['max']),
'low': parseFloat (ticker['min']),
'bid': parseFloat (ticker['bid']),
'ask': parseFloat (ticker['ask']),
'vwap': undefined,
'open': parseFloat (ticker['open']),
'close': undefined,
'first': undefined,
'last': parseFloat (ticker['last_price']),
'change': parseFloat (ticker['daily_change']),
'percentage': undefined,
'average': undefined,
'baseVolume': undefined,
'quoteVolume': parseFloat (ticker['total_btc_traded']),
};
},
fetchTrades (product) {
return this.publicGetTransactions ({
'currency': this.productId (product),
});
},
createOrder (product, type, side, amount, price = undefined, params = {}) {
let order = {
'side': side,
'type': type,
'currency': this.productId (product),
'amount': amount,
};
if (type == 'limit')
order['limit_price'] = price;
return this.privatePostOrdersNew (this.extend (order, params));
},
cancelOrder (id) {
return this.privatePostOrdersCancel ({ 'id': id });
},
request (path, type = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
if (this.id == 'cryptocapital')
throw new Error (this.id + ' is an abstract base API for _1btcxe');
let url = this.urls['api'] + '/' + path;
if (type == 'public') {
if (Object.keys (params).length)
url += '?' + this.urlencode (params);
} else {
let query = this.extend ({
'api_key': this.apiKey,
'nonce': this.nonce (),
}, params);
let request = this.json (query);
query['signature'] = this.hmac (this.encode (request), this.encode (this.secret));
body = this.json (query);
headers = { 'Content-Type': 'application/json' };
}
return this.fetch (url, method, headers, body);
},
}
//-----------------------------------------------------------------------------
var _1btcxe = extend (cryptocapital, {
'id': '_1btcxe',
'name': '1BTCXE',
'countries': 'PA', // Panama
'comment': 'Crypto Capital API',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766049-2b294408-5ecc-11e7-85cc-adaff013dc1a.jpg',
'api': 'https://1btcxe.com/api',
'www': 'https://1btcxe.com',
'doc': 'https://1btcxe.com/api-docs.php',
},
'products': {
'BTC/USD': { 'id': 'USD', 'symbol': 'BTC/USD', 'base': 'BTC', 'quote': 'USD', },
'BTC/EUR': { 'id': 'EUR', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR', },
'BTC/CNY': { 'id': 'CNY', 'symbol': 'BTC/CNY', 'base': 'BTC', 'quote': 'CNY', },
'BTC/RUB': { 'id': 'RUB', 'symbol': 'BTC/RUB', 'base': 'BTC', 'quote': 'RUB', },
'BTC/CHF': { 'id': 'CHF', 'symbol': 'BTC/CHF', 'base': 'BTC', 'quote': 'CHF', },
'BTC/JPY': { 'id': 'JPY', 'symbol': 'BTC/JPY', 'base': 'BTC', 'quote': 'JPY', },
'BTC/GBP': { 'id': 'GBP', 'symbol': 'BTC/GBP', 'base': 'BTC', 'quote': 'GBP', },
'BTC/CAD': { 'id': 'CAD', 'symbol': 'BTC/CAD', 'base': 'BTC', 'quote': 'CAD', },
'BTC/AUD': { 'id': 'AUD', 'symbol': 'BTC/AUD', 'base': 'BTC', 'quote': 'AUD', },
'BTC/AED': { 'id': 'AED', 'symbol': 'BTC/AED', 'base': 'BTC', 'quote': 'AED', },
'BTC/BGN': { 'id': 'BGN', 'symbol': 'BTC/BGN', 'base': 'BTC', 'quote': 'BGN', },
'BTC/CZK': { 'id': 'CZK', 'symbol': 'BTC/CZK', 'base': 'BTC', 'quote': 'CZK', },
'BTC/DKK': { 'id': 'DKK', 'symbol': 'BTC/DKK', 'base': 'BTC', 'quote': 'DKK', },
'BTC/HKD': { 'id': 'HKD', 'symbol': 'BTC/HKD', 'base': 'BTC', 'quote': 'HKD', },
'BTC/HRK': { 'id': 'HRK', 'symbol': 'BTC/HRK', 'base': 'BTC', 'quote': 'HRK', },
'BTC/HUF': { 'id': 'HUF', 'symbol': 'BTC/HUF', 'base': 'BTC', 'quote': 'HUF', },
'BTC/ILS': { 'id': 'ILS', 'symbol': 'BTC/ILS', 'base': 'BTC', 'quote': 'ILS', },
'BTC/INR': { 'id': 'INR', 'symbol': 'BTC/INR', 'base': 'BTC', 'quote': 'INR', },
'BTC/MUR': { 'id': 'MUR', 'symbol': 'BTC/MUR', 'base': 'BTC', 'quote': 'MUR', },
'BTC/MXN': { 'id': 'MXN', 'symbol': 'BTC/MXN', 'base': 'BTC', 'quote': 'MXN', },
'BTC/NOK': { 'id': 'NOK', 'symbol': 'BTC/NOK', 'base': 'BTC', 'quote': 'NOK', },
'BTC/NZD': { 'id': 'NZD', 'symbol': 'BTC/NZD', 'base': 'BTC', 'quote': 'NZD', },
'BTC/PLN': { 'id': 'PLN', 'symbol': 'BTC/PLN', 'base': 'BTC', 'quote': 'PLN', },
'BTC/RON': { 'id': 'RON', 'symbol': 'BTC/RON', 'base': 'BTC', 'quote': 'RON', },
'BTC/SEK': { 'id': 'SEK', 'symbol': 'BTC/SEK', 'base': 'BTC', 'quote': 'SEK', },
'BTC/SGD': { 'id': 'SGD', 'symbol': 'BTC/SGD', 'base': 'BTC', 'quote': 'SGD', },
'BTC/THB': { 'id': 'THB', 'symbol': 'BTC/THB', 'base': 'BTC', 'quote': 'THB', },
'BTC/TRY': { 'id': 'TRY', 'symbol': 'BTC/TRY', 'base': 'BTC', 'quote': 'TRY', },
'BTC/ZAR': { 'id': 'ZAR', 'symbol': 'BTC/ZAR', 'base': 'BTC', 'quote': 'ZAR', },
},
})
//-----------------------------------------------------------------------------
var anxpro = {
'id': 'anxpro',
'name': 'ANXPro',
'countries': [ 'JP', 'SG', 'HK', 'NZ', ],
'version': '2',
'rateLimit': 2000,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27765983-fd8595da-5ec9-11e7-82e3-adb3ab8c2612.jpg',
'api': 'https://anxpro.com/api',
'www': 'https://anxpro.com',
'doc': 'https://anxpro.com/pages/api',
},
'api': {
'public': {
'get': [
'{currency_pair}/money/ticker',
'{currency_pair}/money/depth/full',
'{currency_pair}/money/trade/fetch', // disabled by ANXPro
],
},
'private': {
'post': [
'{currency_pair}/money/order/add',
'{currency_pair}/money/order/cancel',
'{currency_pair}/money/order/quote',
'{currency_pair}/money/order/result',
'{currency_pair}/money/orders',
'money/{currency}/address',
'money/{currency}/send_simple',
'money/info',
'money/trade/list',
'money/wallet/history',
],
},
},
'products': {
'BTC/USD': { 'id': 'BTCUSD', 'symbol': 'BTC/USD', 'base': 'BTC', 'quote': 'USD' },
'BTC/HKD': { 'id': 'BTCHKD', 'symbol': 'BTC/HKD', 'base': 'BTC', 'quote': 'HKD' },
'BTC/EUR': { 'id': 'BTCEUR', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR' },
'BTC/CAD': { 'id': 'BTCCAD', 'symbol': 'BTC/CAD', 'base': 'BTC', 'quote': 'CAD' },
'BTC/AUD': { 'id': 'BTCAUD', 'symbol': 'BTC/AUD', 'base': 'BTC', 'quote': 'AUD' },
'BTC/SGD': { 'id': 'BTCSGD', 'symbol': 'BTC/SGD', 'base': 'BTC', 'quote': 'SGD' },
'BTC/JPY': { 'id': 'BTCJPY', 'symbol': 'BTC/JPY', 'base': 'BTC', 'quote': 'JPY' },
'BTC/GBP': { 'id': 'BTCGBP', 'symbol': 'BTC/GBP', 'base': 'BTC', 'quote': 'GBP' },
'BTC/NZD': { 'id': 'BTCNZD', 'symbol': 'BTC/NZD', 'base': 'BTC', 'quote': 'NZD' },
'LTC/BTC': { 'id': 'LTCBTC', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC' },
'DOGE/BTC': { 'id': 'DOGEBTC', 'symbol': 'DOGE/BTC', 'base': 'DOGE', 'quote': 'BTC' },
'STR/BTC': { 'id': 'STRBTC', 'symbol': 'STR/BTC', 'base': 'STR', 'quote': 'BTC' },
'XRP/BTC': { 'id': 'XRPBTC', 'symbol': 'XRP/BTC', 'base': 'XRP', 'quote': 'BTC' },
},
async fetchBalance () {
let response = await this.privatePostMoneyInfo ();
let balance = response['data'];
let currencies = Object.keys (balance['Wallets']);
let result = { 'info': balance };
for (let c = 0; c < currencies.length; c++) {