forked from ccxt/ccxt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExchange.php
4846 lines (4377 loc) · 200 KB
/
Exchange.php
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
<?php
/*
MIT License
Copyright (c) 2017 CCXT
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.
*/
//-----------------------------------------------------------------------------
namespace ccxt;
use kornrunner\Keccak;
use Elliptic\EC;
use Elliptic\EdDSA;
use BN\BN;
use Exception;
$version = '3.0.104';
// rounding mode
const TRUNCATE = 0;
const ROUND = 1;
const ROUND_UP = 2;
const ROUND_DOWN = 3;
// digits counting mode
const DECIMAL_PLACES = 0;
const SIGNIFICANT_DIGITS = 1;
const TICK_SIZE = 2;
// padding mode
const NO_PADDING = 0;
const PAD_WITH_ZERO = 1;
class Exchange {
const VERSION = '3.0.104';
private static $base58_alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
private static $base58_encoder = null;
private static $base58_decoder = null;
public $defined_rest_api = array();
public $curl = null;
public $curl_options = array(); // overrideable by user, empty by default
public $curl_reset = true;
public $curl_close = false;
public $id = null;
public $validateServerSsl = true;
public $validateClientSsl = false;
public $curlopt_interface = null;
public $timeout = 10000; // in milliseconds
public $proxy = '';
public $origin = '*'; // CORS origin
public $headers = array();
public $hostname = null; // in case of inaccessibility of the "main" domain
public $options = array(); // exchange-specific options if any
public $skipJsonOnStatusCodes = false; // TODO: reserved, rewrite the curl routine to parse JSON body anyway
public $quoteJsonNumbers = true; // treat numbers in json as quoted precise strings
public $name = null;
public $countries = null;
public $version = null;
public $certified = false; // if certified by the CCXT dev team
public $pro = false; // if it is integrated with CCXT Pro for WebSocket support
public $alias = false; // whether this exchange is an alias to another exchange
public $urls = array();
public $api = array();
public $comment = null;
public $markets = null;
public $symbols = null;
public $codes = null;
public $ids = null;
public $currencies = array();
public $base_currencies = null;
public $quote_currencies = null;
public $balance = array();
public $orderbooks = array();
public $tickers = array();
public $fees = array('trading' => array(), 'funding' => array());
public $precision = array();
public $orders = null;
public $myTrades = null;
public $trades = array();
public $transactions = array();
public $positions = array();
public $ohlcvs = array();
public $exceptions = array();
public $accounts = array();
public $status = array('status' => 'ok', 'updated' => null, 'eta' => null, 'url' => null);
public $limits = array(
'cost' => array(
'min' => null,
'max' => null,
),
'price' => array(
'min' => null,
'max' => null,
),
'amount' => array(
'min' => null,
'max' => null,
),
'leverage' => array(
'min' => null,
'max' => null,
),
);
public $httpExceptions = array(
'422' => 'ExchangeError',
'418' => 'DDoSProtection',
'429' => 'RateLimitExceeded',
'404' => 'ExchangeNotAvailable',
'409' => 'ExchangeNotAvailable',
'410' => 'ExchangeNotAvailable',
'451' => 'ExchangeNotAvailable',
'500' => 'ExchangeNotAvailable',
'501' => 'ExchangeNotAvailable',
'502' => 'ExchangeNotAvailable',
'520' => 'ExchangeNotAvailable',
'521' => 'ExchangeNotAvailable',
'522' => 'ExchangeNotAvailable',
'525' => 'ExchangeNotAvailable',
'526' => 'ExchangeNotAvailable',
'400' => 'ExchangeNotAvailable',
'403' => 'ExchangeNotAvailable',
'405' => 'ExchangeNotAvailable',
'503' => 'ExchangeNotAvailable',
'530' => 'ExchangeNotAvailable',
'408' => 'RequestTimeout',
'504' => 'RequestTimeout',
'401' => 'AuthenticationError',
'407' => 'AuthenticationError',
'511' => 'AuthenticationError',
);
public $verbose = false;
public $apiKey = '';
public $secret = '';
public $password = '';
public $login = '';
public $uid = '';
public $privateKey = '';
public $walletAddress = '';
public $token = ''; // reserved for HTTP auth in some cases
public $twofa = null;
public $markets_by_id = null;
public $currencies_by_id = null;
public $userAgent = null; // 'ccxt/' . $this::VERSION . ' (+https://github.com/ccxt/ccxt) PHP/' . PHP_VERSION;
public $userAgents = array(
'chrome' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36',
'chrome39' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',
'chrome100' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36',
);
public $minFundingAddressLength = 1; // used in check_address
public $substituteCommonCurrencyCodes = true;
// whether fees should be summed by currency code
public $reduceFees = true;
public $timeframes = null;
public $requiredCredentials = array(
'apiKey' => true,
'secret' => true,
'uid' => false,
'login' => false,
'password' => false,
'twofa' => false, // 2-factor authentication (one-time password key)
'privateKey' => false,
'walletAddress' => false,
'token' => false, // reserved for HTTP auth in some cases
);
// API methods metainfo
public $has = array(
'publicAPI' => true,
'privateAPI' => true,
'CORS' => null,
'spot' => null,
'margin' => null,
'swap' => null,
'future' => null,
'option' => null,
'addMargin' => null,
'cancelAllOrders' => null,
'cancelOrder' => true,
'cancelOrders' => null,
'createDepositAddress' => null,
'createLimitOrder' => true,
'createMarketOrder' => true,
'createOrder' => true,
'createPostOnlyOrder' => null,
'createReduceOnlyOrder' => null,
'createStopOrder' => null,
'editOrder' => 'emulated',
'fetchAccounts' => null,
'fetchBalance' => true,
'fetchBidsAsks' => null,
'fetchBorrowInterest' => null,
'fetchBorrowRate' => null,
'fetchBorrowRateHistory' => null,
'fetchBorrowRatesPerSymbol' => null,
'fetchBorrowRates' => null,
'fetchCanceledOrders' => null,
'fetchClosedOrder' => null,
'fetchClosedOrders' => null,
'fetchCurrencies' => 'emulated',
'fetchDeposit' => null,
'fetchDepositAddress' => null,
'fetchDepositAddresses' => null,
'fetchDepositAddressesByNetwork' => null,
'fetchDeposits' => null,
'fetchFundingFee' => null,
'fetchFundingFees' => null,
'fetchFundingHistory' => null,
'fetchFundingRate' => null,
'fetchFundingRateHistory' => null,
'fetchFundingRates' => null,
'fetchIndexOHLCV' => null,
'fetchL2OrderBook' => true,
'fetchLedger' => null,
'fetchLedgerEntry' => null,
'fetchLeverageTiers' => null,
'fetchMarketLeverageTiers' => null,
'fetchMarkets' => true,
'fetchMarkOHLCV' => null,
'fetchMyTrades' => null,
'fetchOHLCV' => 'emulated',
'fetchOpenOrder' => null,
'fetchOpenOrders' => null,
'fetchOrder' => null,
'fetchOrderBook' => true,
'fetchOrderBooks' => null,
'fetchOrders' => null,
'fetchOrderTrades' => null,
'fetchPermissions' => null,
'fetchPosition' => null,
'fetchPositions' => null,
'fetchPositionsRisk' => null,
'fetchPremiumIndexOHLCV' => null,
'fetchStatus' => 'emulated',
'fetchTicker' => true,
'fetchTickers' => null,
'fetchTime' => null,
'fetchTrades' => true,
'fetchTradingFee' => null,
'fetchTradingFees' => null,
'fetchTradingLimits' => null,
'fetchTransactions' => null,
'fetchTransfers' => null,
'fetchWithdrawal' => null,
'fetchWithdrawals' => null,
'reduceMargin' => null,
'setLeverage' => null,
'setMargin' => null,
'setMarginMode' => null,
'setPositionMode' => null,
'signIn' => null,
'transfer' => null,
'withdraw' => null,
);
public $precisionMode = DECIMAL_PLACES;
public $paddingMode = NO_PADDING;
public $number = 'floatval';
public $handleContentTypeApplicationZip = false;
public $lastRestRequestTimestamp = 0;
public $lastRestPollTimestamp = 0;
public $restRequestQueue = null;
public $restPollerLoopIsRunning = false;
public $enableRateLimit = true;
public $enableLastJsonResponse = true;
public $enableLastHttpResponse = true;
public $enableLastResponseHeaders = true;
public $last_http_response = null;
public $last_json_response = null;
public $last_response_headers = null;
public $requiresWeb3 = false;
public $requiresEddsa = false;
public $rateLimit = 2000;
public $commonCurrencies = array(
'XBT' => 'BTC',
'BCC' => 'BCH',
'BCHABC' => 'BCH',
'BCHSV' => 'BSV',
);
public $urlencode_glue = '&'; // ini_get('arg_separator.output'); // can be overrided by exchange constructor params
public $urlencode_glue_warning = true;
public $tokenBucket = null; /* array(
'delay' => 0.001,
'capacity' => 1.0,
'cost' => 1.0,
'maxCapacity' => 1000,
'refillRate' => ($this->rateLimit > 0) ? 1.0 / $this->rateLimit : PHP_INT_MAX,
); */
public $baseCurrencies = null;
public $quoteCurrencies = null;
public static $exchanges = array(
'ace',
'alpaca',
'ascendex',
'bequant',
'bigone',
'binance',
'binancecoinm',
'binanceus',
'binanceusdm',
'bit2c',
'bitbank',
'bitbay',
'bitbns',
'bitcoincom',
'bitfinex',
'bitfinex2',
'bitflyer',
'bitforex',
'bitget',
'bithumb',
'bitmart',
'bitmex',
'bitopro',
'bitpanda',
'bitrue',
'bitso',
'bitstamp',
'bitstamp1',
'bittrex',
'bitvavo',
'bkex',
'bl3p',
'blockchaincom',
'btcalpha',
'btcbox',
'btcex',
'btcmarkets',
'btctradeua',
'btcturk',
'bybit',
'cex',
'coinbase',
'coinbaseprime',
'coinbasepro',
'coincheck',
'coinex',
'coinfalcon',
'coinmate',
'coinone',
'coinsph',
'coinspot',
'cryptocom',
'currencycom',
'delta',
'deribit',
'digifinex',
'exmo',
'fmfwio',
'gate',
'gateio',
'gemini',
'hitbtc',
'hitbtc3',
'hollaex',
'huobi',
'huobijp',
'huobipro',
'idex',
'independentreserve',
'indodax',
'kraken',
'krakenfutures',
'kucoin',
'kucoinfutures',
'kuna',
'latoken',
'lbank',
'lbank2',
'luno',
'lykke',
'mercado',
'mexc',
'mexc3',
'ndax',
'novadax',
'oceanex',
'okcoin',
'okex',
'okex5',
'okx',
'paymium',
'phemex',
'poloniex',
'poloniexfutures',
'probit',
'stex',
'tidex',
'timex',
'tokocrypto',
'upbit',
'wavesexchange',
'wazirx',
'whitebit',
'woo',
'xt',
'yobit',
'zaif',
'zonda',
);
public static function split($string, $delimiters = array(' ')) {
return explode($delimiters[0], str_replace($delimiters, $delimiters[0], $string));
}
public static function strip($string) {
return trim($string);
}
public static function decimal($number) {
return '' + $number;
}
public static function valid_string($string) {
return isset($string) && $string !== '';
}
public static function valid_object_value($object, $key) {
return isset($object[$key]) && $object[$key] !== '' && is_scalar($object[$key]);
}
public static function safe_float($object, $key, $default_value = null) {
return (isset($object[$key]) && is_numeric($object[$key])) ? floatval($object[$key]) : $default_value;
}
public static function safe_string($object, $key, $default_value = null) {
return static::valid_object_value($object, $key) ? strval($object[$key]) : $default_value;
}
public static function safe_string_lower($object, $key, $default_value = null) {
if (static::valid_object_value($object, $key)) {
return strtolower(strval($object[$key]));
} else if ($default_value === null) {
return $default_value;
} else {
return strtolower($default_value);
}
}
public static function safe_string_upper($object, $key, $default_value = null) {
if (static::valid_object_value($object, $key)) {
return strtoupper(strval($object[$key]));
} else if ($default_value === null) {
return $default_value;
} else {
return strtoupper($default_value);
}
return static::valid_object_value($object, $key) ? strtoupper(strval($object[$key])) : $default_value;
}
public static function safe_integer($object, $key, $default_value = null) {
return (isset($object[$key]) && is_numeric($object[$key])) ? intval($object[$key]) : $default_value;
}
public static function safe_integer_product($object, $key, $factor, $default_value = null) {
return (isset($object[$key]) && is_numeric($object[$key])) ? (intval($object[$key] * $factor)) : $default_value;
}
public static function safe_timestamp($object, $key, $default_value = null) {
return static::safe_integer_product($object, $key, 1000, $default_value);
}
public static function safe_value($object, $key, $default_value = null) {
return isset($object[$key]) ? $object[$key] : $default_value;
}
// we're not using safe_floats with a list argument as we're trying to save some cycles here
// we're not using safe_float_3 either because those cases are too rare to deserve their own optimization
public static function safe_float_2($object, $key1, $key2, $default_value = null) {
$value = static::safe_float($object, $key1);
return isset($value) ? $value : static::safe_float($object, $key2, $default_value);
}
public static function safe_string_2($object, $key1, $key2, $default_value = null) {
$value = static::safe_string($object, $key1);
return static::valid_string($value) ? $value : static::safe_string($object, $key2, $default_value);
}
public static function safe_string_lower_2($object, $key1, $key2, $default_value = null) {
$value = static::safe_string_lower($object, $key1);
return static::valid_string($value) ? $value : static::safe_string_lower($object, $key2, $default_value);
}
public static function safe_string_upper_2($object, $key1, $key2, $default_value = null) {
$value = static::safe_string_upper($object, $key1);
return static::valid_string($value) ? $value : static::safe_string_upper($object, $key2, $default_value);
}
public static function safe_integer_2($object, $key1, $key2, $default_value = null) {
$value = static::safe_integer($object, $key1);
return isset($value) ? $value : static::safe_integer($object, $key2, $default_value);
}
public static function safe_integer_product_2($object, $key1, $key2, $factor, $default_value = null) {
$value = static::safe_integer_product($object, $key1, $factor);
return isset($value) ? $value : static::safe_integer_product($object, $key2, $factor, $default_value);
}
public static function safe_timestamp_2($object, $key1, $key2, $default_value = null) {
return static::safe_integer_product_2($object, $key1, $key2, 1000, $default_value);
}
public static function safe_value_2($object, $key1, $key2, $default_value = null) {
$value = static::safe_value($object, $key1);
return isset($value) ? $value : static::safe_value($object, $key2, $default_value);
}
// safe_method_n family
public static function safe_float_n($object, $array, $default_value = null) {
$value = static::get_object_value_from_key_array($object, $array);
return (isset($value) && is_numeric($value)) ? floatval($value) : $default_value;
}
public static function safe_string_n($object, $array, $default_value = null) {
$value = static::get_object_value_from_key_array($object, $array);
return (static::valid_string($value) && is_scalar($value)) ? strval($value) : $default_value;
}
public static function safe_string_lower_n($object, $array, $default_value = null) {
$value = static::get_object_value_from_key_array($object, $array);
if (static::valid_string($value) && is_scalar($value)) {
return strtolower(strval($value));
} else if ($default_value === null) {
return $default_value;
} else {
return strtolower($default_value);
}
}
public static function safe_string_upper_n($object, $array, $default_value = null) {
$value = static::get_object_value_from_key_array($object, $array);
if (static::valid_string($value) && is_scalar($value)) {
return strtoupper(strval($value));
} else if ($default_value === null) {
return $default_value;
} else {
return strtoupper($default_value);
}
}
public static function safe_integer_n($object, $array, $default_value = null) {
$value = static::get_object_value_from_key_array($object, $array);
return (isset($value) && is_numeric($value)) ? intval($value) : $default_value;
}
public static function safe_integer_product_n($object, $array, $factor, $default_value = null) {
$value = static::get_object_value_from_key_array($object, $array);
return (isset($value) && is_numeric($value)) ? (intval($value * $factor)) : $default_value;
}
public static function safe_timestamp_n($object, $array, $default_value = null) {
return static::safe_integer_product_n($object, $array, 1000, $default_value);
}
public static function safe_value_n($object, $array, $default_value = null) {
$value = static::get_object_value_from_key_array($object, $array);
return isset($value) ? $value : $default_value;
}
public static function get_object_value_from_key_array($object, $array) {
foreach($array as $key) {
if (isset($object[$key]) && $object[$key] !== '') {
return $object[$key];
}
}
return null;
}
public static function truncate($number, $precision = 0) {
$decimal_precision = pow(10, $precision);
return floor(floatval($number * $decimal_precision)) / $decimal_precision;
}
public static function truncate_to_string($number, $precision = 0) {
if ($precision > 0) {
$string = sprintf('%.' . ($precision + 1) . 'F', floatval($number));
list($integer, $decimal) = explode('.', $string);
$decimal = trim('.' . substr($decimal, 0, $precision), '0');
if (strlen($decimal) < 2) {
$decimal = '.0';
}
return $integer . $decimal;
}
return sprintf('%d', floatval($number));
}
public static function uuid16($length = 16) {
return bin2hex(random_bytes(intval($length / 2)));
}
public static function uuid22($length = 22) {
return bin2hex(random_bytes(intval($length / 2)));
}
public static function uuid() {
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
// 32 bits for "time_low"
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
// 16 bits for "time_mid"
mt_rand(0, 0xffff),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand(0, 0x0fff) | 0x4000,
// 16 bits, 8 bits for "clk_seq_hi_res", 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand(0, 0x3fff) | 0x8000,
// 48 bits for "node"
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
public static function uuidv1() {
$biasSeconds = 12219292800; // seconds from 15th Oct 1572 to Jan 1st 1970
$bias = $biasSeconds * 10000000; // in hundreds of nanoseconds
$time = static::microseconds() * 10 + $bias;
$timeHex = dechex($time);
$arranged = substr($timeHex, 7, 8) . substr($timeHex, 3, 4) . '1' . substr($timeHex, 0, 3);
$clockId = '9696';
$macAddress = 'ffffffffffff';
return $arranged . $clockId . $macAddress;
}
public static function parse_timeframe($timeframe) {
$amount = substr($timeframe, 0, -1);
$unit = substr($timeframe, -1);
$scale = 1;
if ($unit === 'y') {
$scale = 60 * 60 * 24 * 365;
} elseif ($unit === 'M') {
$scale = 60 * 60 * 24 * 30;
} elseif ($unit === 'w') {
$scale = 60 * 60 * 24 * 7;
} elseif ($unit === 'd') {
$scale = 60 * 60 * 24;
} elseif ($unit === 'h') {
$scale = 60 * 60;
} elseif ($unit === 'm') {
$scale = 60;
} elseif ($unit === 's') {
$scale = 1;
} else {
throw new NotSupported('timeframe unit ' . $unit . ' is not supported');
}
return $amount * $scale;
}
public static function round_timeframe($timeframe, $timestamp, $direction=ROUND_DOWN) {
$ms = static::parse_timeframe($timeframe) * 1000;
// Get offset based on timeframe in milliseconds
$offset = $timestamp % $ms;
return $timestamp - $offset + (($direction === ROUND_UP) ? $ms : 0);
}
// given a sorted arrays of trades (recent first) and a timeframe builds an array of OHLCV candles
public static function build_ohlcv($trades, $timeframe = '1m', $since = PHP_INT_MIN, $limits = PHP_INT_MAX) {
if (empty($trades) || !is_array($trades)) {
return array();
}
if (!is_numeric($since)) {
$since = PHP_INT_MIN;
}
if (!is_numeric($limits)) {
$limits = PHP_INT_MAX;
}
$ms = static::parse_timeframe($timeframe) * 1000;
$ohlcvs = array();
list(/* $timestamp */, /* $open */, $high, $low, $close, $volume) = array(0, 1, 2, 3, 4, 5);
for ($i = 0; $i < min(count($trades), $limits); $i++) {
$trade = $trades[$i];
if ($trade['timestamp'] < $since) {
continue;
}
$openingTime = floor($trade['timestamp'] / $ms) * $ms; // shift to the edge of m/h/d (but not M)
$j = count($ohlcvs);
if (($j == 0) || ($openingTime >= $ohlcvs[$j - 1][0] + $ms)) {
// moved to a new timeframe -> create a new candle from opening trade
$ohlcvs[] = array(
$openingTime,
$trade['price'],
$trade['price'],
$trade['price'],
$trade['price'],
$trade['amount'],
);
} else {
// still processing the same timeframe -> update opening trade
$ohlcvs[$j - 1][$high] = max($ohlcvs[$j - 1][$high], $trade['price']);
$ohlcvs[$j - 1][$low] = min($ohlcvs[$j - 1][$low], $trade['price']);
$ohlcvs[$j - 1][$close] = $trade['price'];
$ohlcvs[$j - 1][$volume] += $trade['amount'];
}
}
return $ohlcvs;
}
public static function capitalize($string) {
return mb_strtoupper(mb_substr($string, 0, 1)) . mb_substr($string, 1);
}
public static function is_associative($array) {
return is_array($array) && (count(array_filter(array_keys($array), 'is_string')) > 0);
}
public static function omit($array, $keys) {
if (static::is_associative($array)) {
$result = $array;
if (is_array($keys)) {
foreach ($keys as $key) {
unset($result[$key]);
}
} else {
unset($result[$keys]);
}
return $result;
}
return $array;
}
public static function unique($array) {
return array_unique($array);
}
public static function pluck($array, $key) {
$result = array();
foreach ($array as $element) {
if (isset($key, $element)) {
$result[] = $element[$key];
}
}
return $result;
}
public function filter_by($array, $key, $value = null) {
$result = array();
foreach ($array as $element) {
if (isset($key, $element) && ($element[$key] == $value)) {
$result[] = $element;
}
}
return $result;
}
public static function group_by($array, $key) {
$result = array();
foreach ($array as $element) {
if (isset($element[$key]) && !is_null($element[$key])) {
if (!isset($result[$element[$key]])) {
$result[$element[$key]] = array();
}
$result[$element[$key]][] = $element;
}
}
return $result;
}
public static function index_by($array, $key) {
$result = array();
foreach ($array as $element) {
if (isset($element[$key])) {
$result[$element[$key]] = $element;
}
}
return $result;
}
public static function sort_by($arrayOfArrays, $key, $descending = false) {
$descending = $descending ? -1 : 1;
usort($arrayOfArrays, function ($a, $b) use ($key, $descending) {
if ($a[$key] == $b[$key]) {
return 0;
}
return $a[$key] < $b[$key] ? -$descending : $descending;
});
return $arrayOfArrays;
}
public static function sort_by_2($arrayOfArrays, $key1, $key2, $descending = false) {
$descending = $descending ? -1 : 1;
usort($arrayOfArrays, function ($a, $b) use ($key1, $key2, $descending) {
if ($a[$key1] == $b[$key1]) {
if ($a[$key2] == $b[$key2]) {
return 0;
}
return $a[$key2] < $b[$key2] ? -$descending : $descending;
}
return $a[$key1] < $b[$key1] ? -$descending : $descending;
});
return $arrayOfArrays;
}
public static function flatten($array) {
return array_reduce($array, function ($acc, $item) {
return array_merge($acc, is_array($item) ? static::flatten($item) : array($item));
}, array());
}
public static function array_concat() {
return call_user_func_array('array_merge', array_filter(func_get_args(), 'is_array'));
}
public static function in_array($needle, $haystack) {
return in_array($needle, $haystack);
}
public static function to_array($object) {
if ($object instanceof \JsonSerializable) {
$object = $object->jsonSerialize();
}
return array_values($object);
}
public static function is_empty($object) {
return empty($object);
}
public static function keysort($array) {
$result = $array;
ksort($result);
return $result;
}
public static function extract_params($string) {
if (preg_match_all('/{([\w-]+)}/u', $string, $matches)) {
return $matches[1];
}
}
public static function implode_params($string, $params) {
if (static::is_associative($params)) {
foreach ($params as $key => $value) {
if (gettype($value) !== 'array') {
$string = implode($value, mb_split('{' . preg_quote($key) . '}', $string));
}
}
}
return $string;
}
public static function deep_extend() {
//
// extend associative dictionaries only, replace everything else
//
$out = null;
$args = func_get_args();
foreach ($args as $arg) {
if (static::is_associative($arg) || (is_array($arg) && (count($arg) === 0))) {
if (!static::is_associative($out)) {
$out = array();
}
foreach ($arg as $k => $v) {
$out[$k] = static::deep_extend(isset($out[$k]) ? $out[$k] : array(), $v);
}
} else {
$out = $arg;
}
}
return $out;
}
public static function sum() {
return array_sum(array_filter(func_get_args(), function ($x) {
return isset($x) ? $x : 0;
}));
}
public static function ordered($array) { // for Python OrderedDicts, does nothing in PHP and JS
return $array;
}
public function aggregate($bidasks) {
$result = array();
foreach ($bidasks as $bidask) {
if ($bidask[1] > 0) {
$price = (string) $bidask[0];
$result[$price] = array_key_exists($price, $result) ? $result[$price] : 0;
$result[$price] += $bidask[1];
}
}
$output = array();
foreach ($result as $key => $value) {
$output[] = array(floatval($key), floatval($value));
}
return $output;
}
public static function urlencodeBase64($string) {
return preg_replace(array('#[=]+$#u', '#\+#u', '#\\/#'), array('', '-', '_'), \base64_encode($string));
}
public function urlencode($array) {
foreach ($array as $key => $value) {
if (is_bool($value)) {
$array[$key] = var_export($value, true);
}
}
return http_build_query($array, '', $this->urlencode_glue);
}
public function urlencode_nested($array) {
// we don't have to implement this method in PHP
// https://github.com/ccxt/ccxt/issues/12872
// https://github.com/ccxt/ccxt/issues/12900
return $this->urlencode($array);
}
public function urlencode_with_array_repeat($array) {
return preg_replace('/%5B\d*%5D/', '', $this->urlencode($array));
}
public function rawencode($array) {
return urldecode($this->urlencode($array));
}
public static function encode_uri_component($string) {
return urlencode($string);
}
public static function url($path, $params = array()) {
$result = static::implode_params($path, $params);
$query = static::omit($params, static::extract_params($path));
if ($query) {
$result .= '?' . static::urlencode($query);
}
return $result;
}
public static function seconds() {
return time();
}
public static function milliseconds() {
if (PHP_INT_SIZE == 4) {
return static::milliseconds32();
} else {
return static::milliseconds64();
}
}
public static function milliseconds32() {
list($msec, $sec) = explode(' ', microtime());
// raspbian 32-bit integer workaround
// https://github.com/ccxt/ccxt/issues/5978
// return (int) ($sec . substr($msec, 2, 3));
return $sec . substr($msec, 2, 3);
}
public static function milliseconds64() {