forked from ccxt/ccxt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ccxt.js
15276 lines (14329 loc) · 529 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";
/*
MIT License
Copyright (c) 2017 Igor Kroitor
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
(function () {
//-----------------------------------------------------------------------------
// dependencies
const CryptoJS = require ('crypto-js')
, qs = require ('qs') // querystring
// , ws = require ('ws') // websocket
//-----------------------------------------------------------------------------
// this is updated by vss.js when building
const version = '1.4.91'
//-----------------------------------------------------------------------------
// platform detection
const isNode = (typeof window === 'undefined')
, isCommonJS = (typeof module !== 'undefined') && (typeof require !== '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 ExchangeError extends CCXTError {
constructor (message) {
super (message)
this.constructor = ExchangeError
this.__proto__ = ExchangeError.prototype
this.message = message
}
}
class NotSupported extends ExchangeError {
constructor (message) {
super (message)
this.constructor = NotSupported
this.__proto__ = NotSupported.prototype
this.message = message
}
}
class AuthenticationError extends ExchangeError {
constructor (message) {
super (message)
this.constructor = AuthenticationError
this.__proto__ = AuthenticationError.prototype
this.message = message
}
}
class InsufficientFunds extends ExchangeError {
constructor (message) {
super (message)
this.constructor = InsufficientFunds
this.__proto__ = InsufficientFunds.prototype
this.message = message
}
}
class NetworkError extends CCXTError {
constructor (message) {
super (message)
this.constructor = NetworkError
this.__proto__ = NetworkError.prototype
this.message = message
}
}
class DDoSProtection extends NetworkError {
constructor (message) {
super (message)
this.constructor = DDoSProtection
this.__proto__ = DDoSProtection.prototype
this.message = message
}
}
class RequestTimeout extends NetworkError {
constructor (message) {
super (message)
this.constructor = RequestTimeout
this.__proto__ = RequestTimeout.prototype
this.message = message
}
}
class ExchangeNotAvailable extends NetworkError {
constructor (message) {
super (message)
this.constructor = ExchangeNotAvailable
this.__proto__ = ExchangeNotAvailable.prototype
this.message = message
}
}
//-----------------------------------------------------------------------------
// utility helpers
const sleep = ms => new Promise (resolve => setTimeout (resolve, ms));
const decimal = float => parseFloat (float).toString ()
const timeout = (ms, promise) =>
Promise.race ([
promise,
sleep (ms).then (() => { throw new RequestTimeout ('request timed out') })
])
const capitalize = string => string.length ? (string.charAt (0).toUpperCase () + string.slice (1)) : string
const keysort = object => {
const result = {}
Object.keys (object).sort ().forEach (key => result[key] = object[key])
return result
}
const extend = (...args) => {
const result = {}
for (let i = 0; i < args.length; i++)
if (typeof args[i] === 'object')
Object.keys (args[i]).forEach (key =>
(result[key] = args[i][key]))
return result
}
const omit = function (object) {
const result = extend (object)
for (let 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
}
const indexBy = (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
}
const sortBy = (array, key, descending = false) => {
descending = descending ? -1 : 1
return array.sort ((a, b) => ((a[key] < b[key]) ? -descending : ((a[key] > b[key]) ? descending : 0)))
}
const flatten = (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
}
const unique = array => array.filter ((value, index, self) => (self.indexOf (value) == index))
const pluck = (array, key) => array
.filter (element => (typeof element[key] != 'undefined'))
.map (element => element[key])
const urlencode = object => qs.stringify (object)
const sum = (...args) => {
const result = args.filter (arg => typeof arg != 'undefined')
return (result.length > 0) ?
result.reduce ((sum, value) => sum + value, 0) : undefined
}
const ordered = x => x // a stub to keep assoc keys in order, in JS it does nothing, it's mostly for Python
//-----------------------------------------------------------------------------
// a cross-platform Fetch API
const nodeFetch = isNode && module.require ('node-fetch') // using module.require to prevent Webpack / React Native from trying to include it
, windowFetch = (typeof window !== 'undefined' && window.fetch) // native Fetch API (in newer browsers)
, xhrFetch = (url, options, verbose = false) => // a quick ad-hoc polyfill (for older browsers)
new Promise ((resolve, reject) => {
if (verbose)
console.log (url, options)
const xhr = new XMLHttpRequest ()
const 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)
})
const fetch = nodeFetch || windowFetch || xhrFetch
//-----------------------------------------------------------------------------
// string ←→ binary ←→ base64 conversion routines
const stringToBinary = str => {
const arr = new Uint8Array (str.length)
for (let i = 0; i < str.length; i++) { arr[i] = str.charCodeAt(i); }
return CryptoJS.lib.WordArray.create (arr)
}
const stringToBase64 = string => CryptoJS.enc.Latin1.parse (string).toString (CryptoJS.enc.Base64)
, utf16ToBase64 = string => CryptoJS.enc.Utf16 .parse (string).toString (CryptoJS.enc.Base64)
, base64ToBinary = string => CryptoJS.enc.Base64.parse (string)
, base64ToString = string => CryptoJS.enc.Base64.parse (string).toString (CryptoJS.enc.Utf8)
, binaryToString = string => string
const binaryConcat = (...args) => args.reduce ((a, b) => a.concat (b))
// url-safe-base64 without equals signs, with + replaced by - and slashes replaced by underscores
const urlencodeBase64 = base64string => base64string.replace (/[=]+$/, '')
.replace (/\+/g, '-')
.replace (/\//g, '_')
//-----------------------------------------------------------------------------
// cryptography
const hash = (request, hash = 'md5', digest = 'hex') => {
const result = CryptoJS[hash.toUpperCase ()] (request)
return (digest == 'binary') ? result : result.toString (CryptoJS.enc[capitalize (digest)])
}
const hmac = (request, secret, hash = 'sha256', digest = 'hex') => {
const encoding = (digest == 'binary') ? 'Latin1' : capitalize (digest)
return CryptoJS['Hmac' + hash.toUpperCase ()] (request, secret).toString (CryptoJS.enc[capitalize (encoding)])
}
//-----------------------------------------------------------------------------
// a JSON Web Token authentication method
const jwt = (request, secret, alg = 'HS256', hash = 'sha256') => {
const encodedHeader = urlencodeBase64 (stringToBase64 (JSON.stringify ({ 'alg': alg, 'typ': 'JWT' })))
, encodedData = urlencodeBase64 (stringToBase64 (JSON.stringify (request)))
, token = [ encodedHeader, encodedData ].join ('.')
, signature = urlencodeBase64 (utf16ToBase64 (hmac (token, secret, hash, 'utf16')))
return [ token, signature ].join ('.')
}
//-----------------------------------------------------------------------------
// const WebSocket = require('ws')
// const ws = new WebSocket (this.urls['websocket'])
// ws.on ('open', function open () {
// console.log ('connected')
// // ws.send (Date.now ())
// })
// ws.on ('close', function close () {
// console.log ('disconnected')
// });
// ws.on ('message', function incoming (data) {
// // console.log (`Roundtrip time: ${Date.now() - data} ms`);
// setTimeout (function timeout () {
// ws.send (Date.now ())
// }, 500)
// })
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// the base class
const Exchange = function (config) {
this.hash = hash
this.hmac = hmac
this.jwt = jwt // JSON Web Token
this.binaryConcat = binaryConcat
this.stringToBinary = stringToBinary
this.stringToBase64 = stringToBase64
this.base64ToBinary = base64ToBinary
this.base64ToString = base64ToString
this.binaryToString = binaryToString
this.utf16ToBase64 = utf16ToBase64
this.urlencode = urlencode
this.encodeURIComponent = encodeURIComponent
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.decimal = decimal
this.capitalize = capitalize
this.json = JSON.stringify
this.sum = sum
this.ordered = ordered
this.encode = string => string
this.decode = string => string
if (isNode)
this.nodeVersion = process.version.match (/\d+\.\d+.\d+/) [0]
this.init = function () {
this.orders = {}
this.trades = {}
if (this.api)
this.defineRESTAPI (this.api, 'request');
if (this.markets)
this.setMarkets (this.markets);
}
this.defineRESTAPI = function (api, methodName, options = {}) {
Object.keys (api).forEach (type => {
Object.keys (api[type]).forEach (httpMethod => {
let urls = api[type][httpMethod]
for (let i = 0; i < urls.length; i++) {
let url = urls[i].trim ()
let splitPath = url.split (/[^a-zA-Z0-9]/)
let uppercaseMethod = httpMethod.toUpperCase ()
let lowercaseMethod = httpMethod.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
if ('suffixes' in options) {
if ('camelcase' in options['suffixes'])
camelcase += options['suffixes']['camelcase']
if ('underscore' in options.suffixes)
underscore += options['suffixes']['underscore']
}
if ('underscore_suffix' in options)
underscore += options.underscoreSuffix;
if ('camelcase_suffix' in options)
camelcase += options.camelcaseSuffix;
let partial = params => this[methodName] (url, type, uppercaseMethod, params)
this[camelcase] = partial
this[underscore] = partial
}
})
})
},
// this.initializeStreamingAPI = function () {
// this.ws = new WebSocket (this.urls['websocket'])
// ws.on ('open', function open () {
// console.log ('connected')
// // ws.send (Date.now ())
// })
// ws.on ('close', function close () {
// console.log ('disconnected')
// })
// ws.on ('message', function incoming (data) {
// // console.log (`Roundtrip time: ${Date.now() - data} ms`);
// setTimeout (function timeout () {
// ws.send (Date.now ())
// }, 500)
// })
// },
this.fetch = function (url, method = 'GET', headers = undefined, body = undefined) {
if (isNode && this.userAgent)
if (typeof this.userAgent == 'string')
headers = extend ({ 'User-Agent': this.userAgent }, headers)
else if ((typeof this.userAgent == 'object') && ('User-Agent' in this.userAgent))
headers = extend (this.userAgent, 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, method, url, "\nRequest:\n", options)
return timeout (this.timeout, fetch (url, options)
.catch (e => {
if (isNode) {
throw new ExchangeNotAvailable ([ 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 (this.verbose)
console.log (this.id, method, url, text ? ("\nResponse:\n" + text) : '')
if ((response.status >= 200) && (response.status <= 300))
return text
let error = undefined
let details = text
if ([ 429 ].indexOf (response.status) >= 0) {
error = DDoSProtection
} else if ([ 404, 409, 500, 501, 502, 521, 522, 525 ].indexOf (response.status) >= 0) {
error = ExchangeNotAvailable
} else if ([ 400, 403, 405, 503 ].indexOf (response.status) >= 0) {
let ddosProtection = text.match (/cloudflare|incapsula/i)
if (ddosProtection) {
error = DDoSProtection
} else {
error = ExchangeNotAvailable
details = text + ' (possible reasons: ' + [
'invalid API keys',
'bad or old nonce',
'exchange is down or offline',
'on maintenance',
'DDoS protection',
'rate-limiting',
].join (', ') + ')'
}
} else if ([ 408, 504 ].indexOf (response.status) >= 0) {
error = RequestTimeout
} else if ([ 401, 422, 511 ].indexOf (response.status) >= 0) {
error = AuthenticationError
} else {
error = 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) {
try {
return JSON.parse (body)
} catch (e) {
let maintenance = body.match (/offline|busy|retry|wait|unavailable|maintain|maintenance|maintenancing/i)
let ddosProtection = body.match (/cloudflare|incapsula|overload/i)
if (e instanceof SyntaxError) {
let error = ExchangeNotAvailable
let details = 'not accessible from this location at the moment'
if (maintenance)
details = 'offline, on maintenance or unreachable from this location at the moment'
if (ddosProtection)
error = DDoSProtection
throw new error ([ this.id, method, url, details ].join (' '))
}
if (this.verbose)
console.log (this.id, method, url, 'error', e, "response body:\n'" + body + "'")
throw e
}
}
this.set_markets =
this.setMarkets = function (markets) {
let values = Object.values (markets)
this.markets = indexBy (values, 'symbol')
this.marketsById = indexBy (markets, 'id')
this.markets_by_id = this.marketsById
this.symbols = Object.keys (this.markets)
let base = this.pluck (values.filter (market => 'base' in market), 'base')
let quote = this.pluck (values.filter (market => 'quote' in market), 'quote')
this.currencies = this.unique (base.concat (quote))
return this.markets
}
this.load_markets =
this.loadMarkets = function (reload = false) {
if (!reload && this.markets) {
if (!this.marketsById) {
return new Promise ((resolve, reject) => resolve (this.setMarkets (this.markets)))
}
return new Promise ((resolve, reject) => resolve (this.markets))
}
return this.fetchMarkets ().then (markets => {
return this.setMarkets (markets)
})
}
this.fetch_tickers = function () {
return this.fetchTickers ()
}
this.fetchTickers = function () {
throw new NotSupported (this.id + ' API does not allow to fetch all tickers at once with a single call to fetch_tickers () for now')
}
this.fetch_markets = function () {
return this.fetchMarkets ()
}
this.fetchMarkets = function () {
return new Promise ((resolve, reject) => resolve (this.markets))
}
this.commonCurrencyCode = function (currency) {
if (!this.substituteCommonCurrencyCodes)
return currency
if (currency == 'XBT')
return 'BTC'
if (currency == 'BCC')
return 'BCH'
if (currency == 'DRK')
return 'DASH'
return currency
}
this.market = function (market) {
return (((typeof market === 'string') &&
(typeof this.markets != 'undefined') &&
(typeof this.markets[market] != 'undefined')) ?
this.markets[market] :
market)
}
this.market_id =
this.marketId = function (market) {
return this.market (market).id || market
}
this.symbol = function (market) {
return this.market (market).symbol || market
}
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.url = function (path, params = {}) {
let result = this.implodeParams (path, params);
let query = this.omit (params, this.extractParams (path))
if (Object.keys (query).length)
result += '?' + this.urlencode (query)
return result
}
this.parse_trades =
this.parseTrades = function (trades, market = undefined) {
let result = []
for (let t = 0; t < trades.length; t++) {
result.push (this.parseTrade (trades[t], market))
}
return result
}
this.parse_orders =
this.parseOrders = function (order, market = undefined) {
let result = []
for (let t = 0; t < order.length; t++) {
result.push (this.parseOrder (order[t], market))
}
return result
}
this.parse_ohlcv =
this.parseOHLCV = function (ohlcv, market = undefined, timeframe = 60, since = undefined, limit = undefined) {
return ohlcv
}
this.parse_ohlcvs =
this.parseOHLCVs = function (ohlcvs, market = undefined, timeframe = 60, since = undefined, limit = undefined) {
let result = []
for (let t = 0; t < ohlcvs.length; t++) {
result.push (this.parseOHLCV (ohlcvs[t], market, timeframe, since, limit))
}
return result
}
this.create_limit_buy_order =
this.createLimitBuyOrder = function (market, amount, price, params = {}) {
return this.createOrder (market, 'limit', 'buy', amount, price, params)
}
this.create_limit_sell_order =
this.createLimitSellOrder = function (market, amount, price, params = {}) {
return this.createOrder (market, 'limit', 'sell', amount, price, params)
}
this.create_market_buy_order =
this.createMarketBuyOrder = function (market, amount, params = {}) {
return this.createOrder (market, 'market', 'buy', amount, undefined, params)
}
this.create_market_sell_order =
this.createMarketSellOrder = function (market, amount, params = {}) {
return this.createOrder (market, 'market', 'sell', amount, undefined, 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.userAgent = false
this.twofa = false // two-factor authentication
this.substituteCommonCurrencyCodes = true
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
}
if (isNode)
this.userAgent = {
'User-Agent': 'ccxt/' + version +
' (+https://github.com/kroitor/ccxt)' +
' Node.js/' + this.nodeVersion + ' (JavaScript)'
}
// prepended to URL, like https://proxy.com/https://exchange.com/api...
this.proxy = ''
this.hasFetchTickers = false
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': 1500,
'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 fetchMarkets () {
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 markets = await this_.privateGetMarketList ({
'category': category.toLowerCase (),
});
for (let p = 0; p < markets['response'].length; p++) {
let market = markets['response'][p];
let id = market['symbol'];
let symbol = undefined;
let base = undefined;
let quote = undefined;
if ((category == 'FOREX') || (category == 'CRYPTO')) {
symbol = market['name'];
let parts = symbol.split ('/');
base = parts[0];
quote = parts[1];
} else {
base = id;
quote = 'USD';
symbol = base + '/' + quote;
}
base = this_.commonCurrencyCode (base);
quote = this_.commonCurrencyCode (quote);
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
});
}
}
return result;
},
async fetchBalance () {
await this.loadMarkets ();
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 (market, params = {}) {
await this.loadMarkets ();
let response = await this.privateGetMarketQuotes (this.extend ({
'symbols': this.marketId (market),
}, params));
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 fetchTrades (market) {
throw new ExchangeError (this.id + ' fetchTrades () method not implemented yet');
},
async fetchTicker (market) {
await this.loadMarkets ();
let result = await this.privateGetMarketBars ({
'symbol': this.marketId (market),
'resolution': 60,
'limit': 1,
});
let orderbook = await this.fetchOrderBook (market);
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,
};
},
async createOrder (market, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
let order = {
'symbol': this.marketId (market),
'margin': amount,
'direction': (side == 'sell') ? 'short' : 'long',
'leverage': 1,
'type': side,
};
if (type == 'limit')
order['price'] = price;
else
order['type'] += '_market';
let result = await this.privateGetOrderCreate (this.extend (order, params));
return {
'info': result,
'id': result['response']['order_id'],
};
},
async cancelOrder (id) {
await this.loadMarkets ();
return this.privatePostOrderCancel ({ 'order_id': id });
},
async request (path, api = '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);
let response = await this.fetch (url, method);
if ('warning' in response)
if (response['warning'])
throw new ExchangeError (this.id + ' Warning: ' + response['warning_message']);
if ('error' in response)
if (response['error'])
throw new ExchangeError (this.id + ' Error: ' + response['error_code'] + response['error_message']);
return response;
},
}
//-----------------------------------------------------------------------------
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',
],
},
},
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'] = parseFloat (balance['available'][currency]);
if (currency in balance['on_hold'])
account['used'] = parseFloat (balance['on_hold'][currency]);
account['total'] = this.sum (account['free'], account['used']);
result[currency] = account;
}
return result;
},
async fetchOrderBook (market, params = {}) {
let response = await this.publicGetOrderBook (this.extend ({
'currency': this.marketId (market),
}, params));
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];