-
Notifications
You must be signed in to change notification settings - Fork 10
/
php-binance-api.php
3115 lines (2830 loc) · 106 KB
/
php-binance-api.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
/*
* ============================================================
* @package php-binance-api
* @link https://github.com/jaggedsoft/php-binance-api
* ============================================================
* @copyright 2017-2018
* @author Jon Eyrick
* @license MIT License
* ============================================================
* A curl HTTP REST wrapper for the binance currency exchange
*/
namespace Binance;
use Exception;
// PHP version check
if (version_compare(phpversion(), '7.0', '<=')) {
fwrite(STDERR, "Hi, PHP " . phpversion() . " support will be removed very soon as part of continued development.\n");
fwrite(STDERR, "Please consider upgrading.\n");
}
/**
* Main Binance class
*
* Eg. Usage:
* require 'vendor/autoload.php';
* $api = new Binance\\API();
*/
class API
{
protected $base = 'https://api.binance.com/api/'; // /< REST endpoint for the currency exchange
protected $baseTestnet = 'https://testnet.binance.vision/api/'; // /< Testnet REST endpoint for the currency exchange
protected $wapi = 'https://api.binance.com/wapi/'; // /< REST endpoint for the withdrawals
protected $sapi = 'https://api.binance.com/sapi/'; // /< REST endpoint for the supporting network API
protected $stream = 'wss://stream.binance.com:9443/ws/'; // /< Endpoint for establishing websocket connections
protected $streamTestnet = 'wss://testnet.binance.vision/ws/'; // /< Testnet endpoint for establishing websocket connections
protected $api_key; // /< API key that you created in the binance website member area
protected $api_secret; // /< API secret that was given to you when you created the api key
protected $useTestnet = false; // /< Enable/disable testnet (https://testnet.binance.vision/)
protected $depthCache = []; // /< Websockets depth cache
protected $depthQueue = []; // /< Websockets depth queue
protected $chartQueue = []; // /< Websockets chart queue
protected $charts = []; // /< Websockets chart data
protected $curlOpts = []; // /< User defined curl coptions
protected $info = [
"timeOffset" => 0,
]; // /< Additional connection options
protected $proxyConf = null; // /< Used for story the proxy configuration
protected $caOverride = false; // /< set this if you donnot wish to use CA bundle auto download feature
protected $transfered = 0; // /< This stores the amount of bytes transfered
protected $requestCount = 0; // /< This stores the amount of API requests
protected $httpDebug = false; // /< If you enable this, curl will output debugging information
protected $subscriptions = []; // /< View all websocket subscriptions
protected $btc_value = 0.00; // /< value of available assets
protected $btc_total = 0.00;
// /< value of available onOrder assets
protected $exchangeInfo = null;
protected $lastRequest = [];
protected $xMbxUsedWeight = 0;
protected $xMbxUsedWeight1m = 0;
/**
* Constructor for the class,
* send as many argument as you want.
*
* No arguments - use file setup
* 1 argument - file to load config from
* 2 arguments - api key and api secret
* 3 arguments - api key, api secret and use testnet flag
*
* @return null
*/
public function __construct()
{
$param = func_get_args();
switch (count($param)) {
case 0:
$this->setupApiConfigFromFile();
$this->setupProxyConfigFromFile();
$this->setupCurlOptsFromFile();
break;
case 1:
$this->setupApiConfigFromFile($param[0]);
$this->setupProxyConfigFromFile($param[0]);
$this->setupCurlOptsFromFile($param[0]);
break;
case 2:
$this->api_key = $param[0];
$this->api_secret = $param[1];
break;
case 3:
$this->api_key = $param[0];
$this->api_secret = $param[1];
$this->useTestnet = (bool)$param[2];
break;
default:
echo 'Please see valid constructors here: https://github.com/jaggedsoft/php-binance-api/blob/master/examples/constructor.php';
}
}
/**
* magic get for protected and protected members
*
* @param $file string the name of the property to return
* @return null
*/
public function __get(string $member)
{
if (property_exists($this, $member)) {
return $this->$member;
}
return null;
}
/**
* magic set for protected and protected members
*
* @param $member string the name of the member property
* @param $value the value of the member property
*/
public function __set(string $member, $value)
{
$this->$member = $value;
}
/**
* If no paramaters are supplied in the constructor, this function will attempt
* to load the api_key and api_secret from the users home directory in the file
* ~/jaggedsoft/php-binance-api.json
*
* @param $file string file location
* @return null
*/
protected function setupApiConfigFromFile(string $file = null)
{
$file = is_null($file) ? getenv("HOME") . "/.config/jaggedsoft/php-binance-api.json" : $file;
if (empty($this->api_key) === false || empty($this->api_secret) === false) {
return;
}
if (file_exists($file) === false) {
echo "Unable to load config from: " . $file . PHP_EOL;
echo "Detected no API KEY or SECRET, all signed requests will fail" . PHP_EOL;
return;
}
$contents = json_decode(file_get_contents($file), true);
$this->api_key = isset($contents['api-key']) ? $contents['api-key'] : "";
$this->api_secret = isset($contents['api-secret']) ? $contents['api-secret'] : "";
$this->useTestnet = isset($contents['use-testnet']) ? (bool)$contents['use-testnet'] : false;
}
/**
* If no paramaters are supplied in the constructor, this function will attempt
* to load the acurlopts from the users home directory in the file
* ~/jaggedsoft/php-binance-api.json
*
* @param $file string file location
* @return null
*/
protected function setupCurlOptsFromFile(string $file = null)
{
$file = is_null($file) ? getenv("HOME") . "/.config/jaggedsoft/php-binance-api.json" : $file;
if (count($this->curlOpts) > 0) {
return;
}
if (file_exists($file) === false) {
echo "Unable to load config from: " . $file . PHP_EOL;
echo "No curl options will be set" . PHP_EOL;
return;
}
$contents = json_decode(file_get_contents($file), true);
$this->curlOpts = isset($contents['curlOpts']) && is_array($contents['curlOpts']) ? $contents['curlOpts'] : [];
}
/**
* If no paramaters are supplied in the constructor for the proxy confguration,
* this function will attempt to load the proxy info from the users home directory
* ~/jaggedsoft/php-binance-api.json
*
* @return null
*/
protected function setupProxyConfigFromFile(string $file = null)
{
$file = is_null($file) ? getenv("HOME") . "/.config/jaggedsoft/php-binance-api.json" : $file;
if (is_null($this->proxyConf) === false) {
return;
}
if (file_exists($file) === false) {
echo "Unable to load config from: " . $file . PHP_EOL;
echo "No proxies will be used " . PHP_EOL;
return;
}
$contents = json_decode(file_get_contents($file), true);
if (isset($contents['proto']) === false) {
return;
}
if (isset($contents['address']) === false) {
return;
}
if (isset($contents['port']) === false) {
return;
}
$this->proxyConf['proto'] = $contents['proto'];
$this->proxyConf['address'] = $contents['address'];
$this->proxyConf['port'] = $contents['port'];
if (isset($contents['user'])) {
$this->proxyConf['user'] = isset($contents['user']) ? $contents['user'] : "";
}
if (isset($contents['pass'])) {
$this->proxyConf['pass'] = isset($contents['pass']) ? $contents['pass'] : "";
}
}
/* THIS IS CODE I'VE ADDED TO USE THE VARIOUS BINANCE APIS THAT THE ORIGINAL LIBRARY / CODE DOESN'T COVER */
protected $dapi = 'https://dapi.binance.com/dapi/'; // /< REST endpoint for the futures - coin M system
private function httpRequest_delivery(string $url, string $method = "GET", array $params = [], bool $signed = false)
{
if (function_exists('curl_init') === false) {
throw new \Exception("Sorry cURL is not installed!");
}
if ($this->caOverride === false) {
if (file_exists(getcwd() . '/ca.pem') === false) {
$this->downloadCurlCaBundle();
}
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_VERBOSE, $this->httpDebug);
$query = http_build_query($params, '', '&');
// signed with params
if ($signed === true) {
if (empty($this->api_key)) {
throw new \Exception("signedRequest error: API Key not set!");
}
if (empty($this->api_secret)) {
throw new \Exception("signedRequest error: API Secret not set!");
}
$base = $this->dapi;
$ts = (microtime(true) * 1000) + $this->info['timeOffset'];
$params['timestamp'] = number_format($ts, 0, '.', '');
if (isset($params['dapi'])) {
unset($params['dapi']);
$base = $this->dapi;
}
$query = http_build_query($params, '', '&');
$signature = hash_hmac('sha256', $query, $this->api_secret);
if ($method === "POST") {
$endpoint = $base . $url;
$params['signature'] = $signature; // signature needs to be inside BODY
$query = http_build_query($params, '', '&'); // rebuilding query
} else {
$endpoint = $base . $url . '?' . $query . '&signature=' . $signature;
}
curl_setopt($curl, CURLOPT_URL, $endpoint);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'X-MBX-APIKEY: ' . $this->api_key,
));
}
// params so buildquery string and append to url
else if (count($params) > 0) {
curl_setopt($curl, CURLOPT_URL, $this->dapi . $url . '?' . $query);
}
// no params so just the base url
else {
curl_setopt($curl, CURLOPT_URL, $this->dapi . $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'X-MBX-APIKEY: ' . $this->api_key,
));
}
curl_setopt($curl, CURLOPT_USERAGENT, "User-Agent: Mozilla/4.0 (compatible; PHP Binance API)");
// Post and postfields
if ($method === "POST") {
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $query);
}
// Delete Method
if ($method === "DELETE") {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
}
// PUT Method
if ($method === "PUT") {
curl_setopt($curl, CURLOPT_PUT, true);
}
// proxy settings
if (is_array($this->proxyConf)) {
curl_setopt($curl, CURLOPT_PROXY, $this->getProxyUriString());
if (isset($this->proxyConf['user']) && isset($this->proxyConf['pass'])) {
curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->proxyConf['user'] . ':' . $this->proxyConf['pass']);
}
}
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 60);
// set user defined curl opts last for overriding
foreach ($this->curlOpts as $key => $value) {
curl_setopt($curl, constant($key), $value);
}
if ($this->caOverride === false) {
if (file_exists(getcwd() . '/ca.pem') === false) {
$this->downloadCurlCaBundle();
}
}
$output = curl_exec($curl);
// Check if any error occurred
if (curl_errno($curl) > 0) {
// should always output error, not only on httpdebug
// not outputing errors, hides it from users and ends up with tickets on github
echo 'Curl error: ' . curl_error($curl) . "\n";
return [];
}
$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$header = substr($output, 0, $header_size);
$output = substr($output, $header_size);
curl_close($curl);
$json = json_decode($output, true);
/*
$this->query_logs[] = [
'url' => $url,
'method' => $method,
'params' => $params,
'header' => $header,
'json' => $json
];
*/
if(isset($json['msg'])){
// should always output error, not only on httpdebug
// not outputing errors, hides it from users and ends up with tickets on github
echo "signedRequest error: {$output}" . PHP_EOL;
}
$this->transfered += strlen($output);
$this->requestCount++;
return $json;
}
// https://binance-docs.github.io/apidocs/delivery/en/#position-information-user_data
public function delivery_position_information() {
return $this->httpRequest_delivery("v1/positionRisk", "GET", [], true);
}
// https://binance-docs.github.io/apidocs/delivery/en/#account-information-user_data
public function delivery_account_information() {
return $this->httpRequest_delivery("v1/account", "GET", [], true);
}
public function delivery_symbol_order_book_ticker($symbol) {
$additionalData = [];
if (is_null($symbol) === false) {
$additionalData = [
'symbol' => $symbol,
];
}
return $this->httpRequest_delivery("v1/ticker/bookTicker", "GET", $additionalData);
}
// https://binance-docs.github.io/apidocs/futures/en/#current-all-open-orders-user_data
public function delivery_current_all_open_orders($symbol) {
$params = [
"symbol" => $symbol
];
return $this->httpRequest_delivery("v1/openOrders", "GET", $params, true);
}
// https://binance-docs.github.io/apidocs/delivery/en/#new-order-trade
public function delivery_create_order(string $side, string $symbol, $quantity, $price, string $type = "LIMIT", array $flags = [], bool $test = false) {
$opt = [
"symbol" => $symbol,
"side" => $side,
"type" => $type,
"quantity" => $quantity,
"recvWindow" => 60000,
];
// someone has preformated there 8 decimal point double already
// dont do anything, leave them do whatever they want
if (gettype($price) !== "string") {
// for every other type, lets format it appropriately
$price = number_format($price, 8, '.', '');
}
if (is_numeric($quantity) === false) {
// WPCS: XSS OK.
echo "warning: quantity expected numeric got " . gettype($quantity) . PHP_EOL;
}
if (is_string($price) === false) {
// WPCS: XSS OK.
echo "warning: price expected string got " . gettype($price) . PHP_EOL;
}
if ($type === "STOP_LOSS_LIMIT" || $type === "TAKE_PROFIT_LIMIT") {
$opt["price"] = $price;
$opt["timeInForce"] = "GTC";
}
if ($type === "LIMIT") {
$opt["price"] = $price;
$opt["timeInForce"] = "GTX";
}
if ($type === "STOP") {
$opt["price"] = $price;
}
if (isset($flags['stopPrice'])) {
$opt['stopPrice'] = $flags['stopPrice'];
}
if (isset($flags['icebergQty'])) {
$opt['icebergQty'] = $flags['icebergQty'];
}
if (isset($flags['newOrderRespType'])) {
$opt['newOrderRespType'] = $flags['newOrderRespType'];
}
if (isset($flags['newClientOrderId'])) {
$opt['newClientOrderId'] = $flags['newClientOrderId'];
}
if (isset($flags['reduceOnly'])) {
$opt['reduceOnly'] = $flags['reduceOnly'];
}
if (isset($flags['activationPrice'])) {
$opt['activationPrice'] = $flags['activationPrice'];
}
if (isset($flags['callbackRate'])) {
$opt['callbackRate'] = $flags['callbackRate'];
}
if (isset($flags['workingType'])) {
$opt['workingType'] = $flags['workingType'];
}
/*
print_r($qstring);
die();
*/
$qstring = ($test === false) ? "v1/order" : "v1/order/test";
return $this->httpRequest_delivery($qstring, "POST", $opt, true);
}
// https://binance-docs.github.io/apidocs/futures/en/#cancel-all-open-orders-trade
public function delivery_cancel_all_open_orders(string $symbol) {
$params = [
"symbol" => $symbol
];
return $this->httpRequest_delivery("v1/allOpenOrders", "DELETE", $params, true);
}
// end of my additions
/**
* buy attempts to create a currency order
* each currency supports a number of order types, such as
* -LIMIT
* -MARKET
* -STOP_LOSS
* -STOP_LOSS_LIMIT
* -TAKE_PROFIT
* -TAKE_PROFIT_LIMIT
* -LIMIT_MAKER
*
* You should check the @see exchangeInfo for each currency to determine
* what types of orders can be placed against specific pairs
*
* $quantity = 1;
* $price = 0.0005;
* $order = $api->buy("BNBBTC", $quantity, $price);
*
* @param $symbol string the currency symbol
* @param $quantity string the quantity required
* @param $price string price per unit you want to spend
* @param $type string type of order
* @param $flags array addtional options for order type
* @return array with error message or the order details
*/
public function buy(string $symbol, $quantity, $price, string $type = "LIMIT", array $flags = [])
{
return $this->order("BUY", $symbol, $quantity, $price, $type, $flags);
}
/**
* buyTest attempts to create a TEST currency order
*
* @see buy()
*
* @param $symbol string the currency symbol
* @param $quantity string the quantity required
* @param $price string price per unit you want to spend
* @param $type string config
* @param $flags array config
* @return array with error message or empty or the order details
*/
public function buyTest(string $symbol, $quantity, $price, string $type = "LIMIT", array $flags = [])
{
return $this->order("BUY", $symbol, $quantity, $price, $type, $flags, true);
}
/**
* sell attempts to create a currency order
* each currency supports a number of order types, such as
* -LIMIT
* -MARKET
* -STOP_LOSS
* -STOP_LOSS_LIMIT
* -TAKE_PROFIT
* -TAKE_PROFIT_LIMIT
* -LIMIT_MAKER
*
* You should check the @see exchangeInfo for each currency to determine
* what types of orders can be placed against specific pairs
*
* $quantity = 1;
* $price = 0.0005;
* $order = $api->sell("BNBBTC", $quantity, $price);
*
* @param $symbol string the currency symbol
* @param $quantity string the quantity required
* @param $price string price per unit you want to spend
* @param $type string type of order
* @param $flags array addtional options for order type
* @return array with error message or the order details
*/
public function sell(string $symbol, $quantity, $price, string $type = "LIMIT", array $flags = [])
{
return $this->order("SELL", $symbol, $quantity, $price, $type, $flags);
}
/**
* sellTest attempts to create a TEST currency order
*
* @see sell()
*
* @param $symbol string the currency symbol
* @param $quantity string the quantity required
* @param $price string price per unit you want to spend
* @param $type array config
* @param $flags array config
* @return array with error message or empty or the order details
*/
public function sellTest(string $symbol, $quantity, $price, string $type = "LIMIT", array $flags = [])
{
return $this->order("SELL", $symbol, $quantity, $price, $type, $flags, true);
}
/**
* marketQuoteBuy attempts to create a currency order at given market price
*
* $quantity = 1;
* $order = $api->marketQuoteBuy("BNBBTC", $quantity);
*
* @param $symbol string the currency symbol
* @param $quantity string the quantity of the quote to use
* @param $flags array additional options for order type
* @return array with error message or the order details
*/
public function marketQuoteBuy(string $symbol, $quantity, array $flags = [])
{
$flags['isQuoteOrder'] = true;
return $this->order("BUY", $symbol, $quantity, 0, "MARKET", $flags);
}
/**
* marketQuoteBuyTest attempts to create a TEST currency order at given market price
*
* @see marketBuy()
*
* @param $symbol string the currency symbol
* @param $quantity string the quantity of the quote to use
* @param $flags array additional options for order type
* @return array with error message or the order details
*/
public function marketQuoteBuyTest(string $symbol, $quantity, array $flags = [])
{
$flags['isQuoteOrder'] = true;
return $this->order("BUY", $symbol, $quantity, 0, "MARKET", $flags, true);
}
/**
* marketBuy attempts to create a currency order at given market price
*
* $quantity = 1;
* $order = $api->marketBuy("BNBBTC", $quantity);
*
* @param $symbol string the currency symbol
* @param $quantity string the quantity required
* @param $flags array addtional options for order type
* @return array with error message or the order details
*/
public function marketBuy(string $symbol, $quantity, array $flags = [])
{
return $this->order("BUY", $symbol, $quantity, 0, "MARKET", $flags);
}
/**
* marketBuyTest attempts to create a TEST currency order at given market price
*
* @see marketBuy()
*
* @param $symbol string the currency symbol
* @param $quantity string the quantity required
* @param $flags array addtional options for order type
* @return array with error message or the order details
*/
public function marketBuyTest(string $symbol, $quantity, array $flags = [])
{
return $this->order("BUY", $symbol, $quantity, 0, "MARKET", $flags, true);
}
/**
* numberOfDecimals() returns the signifcant digits level based on the minimum order amount.
*
* $dec = numberOfDecimals(0.00001); // Returns 5
*
* @param $val float the minimum order amount for the pair
* @return integer (signifcant digits) based on the minimum order amount
*/
public function numberOfDecimals($val = 0.00000001)
{
$val = sprintf("%.14f", $val);
$parts = explode('.', $val);
$parts[1] = rtrim($parts[1], "0");
return strlen($parts[1]);
}
/**
* marketQuoteSell attempts to create a currency order at given market price
*
* $quantity = 1;
* $order = $api->marketQuoteSell("BNBBTC", $quantity);
*
* @param $symbol string the currency symbol
* @param $quantity string the quantity of the quote you want to obtain
* @param $flags array additional options for order type
* @return array with error message or the order details
*/
public function marketQuoteSell(string $symbol, $quantity, array $flags = [])
{
$flags['isQuoteOrder'] = true;
$c = $this->numberOfDecimals($this->exchangeInfo()['symbols'][$symbol]['filters'][2]['minQty']);
$quantity = $this->floorDecimal($quantity, $c);
return $this->order("SELL", $symbol, $quantity, 0, "MARKET", $flags);
}
/**
* marketQuoteSellTest attempts to create a TEST currency order at given market price
*
* @see marketSellTest()
*
* @param $symbol string the currency symbol
* @param $quantity string the quantity of the quote you want to obtain
* @param $flags array additional options for order type
* @return array with error message or the order details
*/
public function marketQuoteSellTest(string $symbol, $quantity, array $flags = [])
{
$flags['isQuoteOrder'] = true;
return $this->order("SELL", $symbol, $quantity, 0, "MARKET", $flags, true);
}
/**
* marketSell attempts to create a currency order at given market price
*
* $quantity = 1;
* $order = $api->marketSell("BNBBTC", $quantity);
*
* @param $symbol string the currency symbol
* @param $quantity string the quantity required
* @param $flags array addtional options for order type
* @return array with error message or the order details
*/
public function marketSell(string $symbol, $quantity, array $flags = [])
{
$c = $this->numberOfDecimals($this->exchangeInfo()['symbols'][$symbol]['filters'][2]['minQty']);
$quantity = $this->floorDecimal($quantity, $c);
return $this->order("SELL", $symbol, $quantity, 0, "MARKET", $flags);
}
/**
* marketSellTest attempts to create a TEST currency order at given market price
*
* @see marketSellTest()
*
* @param $symbol string the currency symbol
* @param $quantity string the quantity required
* @param $flags array addtional options for order type
* @return array with error message or the order details
*/
public function marketSellTest(string $symbol, $quantity, array $flags = [])
{
return $this->order("SELL", $symbol, $quantity, 0, "MARKET", $flags, true);
}
/**
* cancel attempts to cancel a currency order
*
* $orderid = "123456789";
* $order = $api->cancel("BNBBTC", $orderid);
*
* @param $symbol string the currency symbol
* @param $orderid string the orderid to cancel
* @param $flags array of optional options like ["side"=>"sell"]
* @return array with error message or the order details
* @throws \Exception
*/
public function cancel(string $symbol, $orderid, $flags = [])
{
$params = [
"symbol" => $symbol,
"orderId" => $orderid,
];
return $this->httpRequest("v3/order", "DELETE", array_merge($params, $flags), true);
}
/**
* orderStatus attempts to get orders status
*
* $orderid = "123456789";
* $order = $api->orderStatus("BNBBTC", $orderid);
*
* @param $symbol string the currency symbol
* @param $orderid string the orderid to cancel
* @return array with error message or the order details
* @throws \Exception
*/
public function orderStatus(string $symbol, $orderid)
{
return $this->httpRequest("v3/order", "GET", [
"symbol" => $symbol,
"orderId" => $orderid,
], true);
}
/**
* openOrders attempts to get open orders for all currencies or a specific currency
*
* $allOpenOrders = $api->openOrders();
* $allBNBOrders = $api->openOrders( "BNBBTC" );
*
* @param $symbol string the currency symbol
* @return array with error message or the order details
* @throws \Exception
*/
public function openOrders(string $symbol = null)
{
$params = [];
if (is_null($symbol) != true) {
$params = [
"symbol" => $symbol,
];
}
return $this->httpRequest("v3/openOrders", "GET", $params, true);
}
/**
* Cancel all open orders method
* $api->cancelOpenOrders( "BNBBTC" );
* @param $symbol string the currency symbol
* @return array with error message or the order details
* @throws \Exception
*/
public function cancelOpenOrders(string $symbol = null)
{
$params = [];
if (is_null($symbol) != true) {
$params = [
"symbol" => $symbol,
];
}
return $this->httpRequest("v3/openOrders", "DELETE", $params, true);
}
/**
* orders attempts to get the orders for all or a specific currency
*
* $allBNBOrders = $api->orders( "BNBBTC" );
*
* @param $symbol string the currency symbol
* @param $limit int the amount of orders returned
* @param $fromOrderId string return the orders from this order onwards
* @param $params array optional startTime, endTime parameters
* @return array with error message or array of orderDetails array
* @throws \Exception
*/
public function orders(string $symbol, int $limit = 500, int $fromOrderId = 0, array $params = [])
{
$params["symbol"] = $symbol;
$params["limit"] = $limit;
if ($fromOrderId) {
$params["orderId"] = $fromOrderId;
}
return $this->httpRequest("v3/allOrders", "GET", $params, true);
}
/**
* history Get the complete account trade history for all or a specific currency
*
* $BNBHistory = $api->history("BNBBTC");
* $limitBNBHistory = $api->history("BNBBTC",5);
* $limitBNBHistoryFromId = $api->history("BNBBTC",5,3);
*
* @param $symbol string the currency symbol
* @param $limit int the amount of orders returned
* @param $fromTradeId int (optional) return the orders from this order onwards. negative for all
* @param $startTime int (optional) return the orders from this time onwards. null to ignore
* @param $endTime int (optional) return the orders from this time backwards. null to ignore
* @return array with error message or array of orderDetails array
* @throws \Exception
*/
public function history(string $symbol, int $limit = 500, int $fromTradeId = -1, int $startTime = null, int $endTime = null)
{
$parameters = [
"symbol" => $symbol,
"limit" => $limit,
];
if ($fromTradeId > 0) {
$parameters["fromId"] = $fromTradeId;
}
if (isset($startTime)) {
$parameters["startTime"] = $startTime;
}
if (isset($endTime)) {
$parameters["endTime"] = $endTime;
}
return $this->httpRequest("v3/myTrades", "GET", $parameters, true);
}
/**
* useServerTime adds the 'useServerTime'=>true to the API request to avoid time errors
*
* $api->useServerTime();
*
* @return null
* @throws \Exception
*/
public function useServerTime()
{
$request = $this->httpRequest("v3/time");
if (isset($request['serverTime'])) {
$this->info['timeOffset'] = $request['serverTime'] - (microtime(true) * 1000);
}
}
/**
* time Gets the server time
*
* $time = $api->time();
*
* @return array with error message or array with server time key
* @throws \Exception
*/
public function time()
{
return $this->httpRequest("v3/time");
}
/**
* exchangeInfo Gets the complete exchange info, including limits, currency options etc.
*
* $info = $api->exchangeInfo();
*
* @return array with error message or exchange info array
* @throws \Exception
*/
public function exchangeInfo()
{
if (!$this->exchangeInfo) {
$arr = $this->httpRequest("v3/exchangeInfo");
$this->exchangeInfo = $arr;
$this->exchangeInfo['symbols'] = null;
foreach ($arr['symbols'] as $key => $value) {
$this->exchangeInfo['symbols'][$value['symbol']] = $value;
}
}
return $this->exchangeInfo;
}
/**
* assetDetail - Fetch details of assets supported on Binance
*
* @link https://binance-docs.github.io/apidocs/spot/en/#asset-detail-user_data
*
* @property int $weight 1
*
* @return array containing the response
*/
public function assetDetail()
{
$params["sapi"] = true;
$arr = $this->httpRequest("v1/asset/assetDetail", 'GET', $params, true);
// wrap into another array for backwards compatibility with the old wapi one
if (!empty($arr['BTC']['withdrawFee'])) {
return array(
'success' => 1,
'assetDetail' => $arr,
);
} else {
return array(
'success' => 0,
'assetDetail' => array(),
);
}
}
/**
* userAssetDribbletLog - Log of the conversion of the dust assets to BNB
* @deprecated
*/
public function userAssetDribbletLog()
{
$params["wapi"] = true;
trigger_error('Deprecated - function will disappear on 2021-08-01 from Binance. Please switch to $api->dustLog().', E_USER_DEPRECATED);
return $this->httpRequest("v3/userAssetDribbletLog.html", 'GET', $params, true);
}
/**
* dustLog - Log of the conversion of the dust assets to BNB
*
* @link https://binance-docs.github.io/apidocs/spot/en/#dustlog-user_data
*
* @property int $weight 1
*
* @param long $startTime (optional) Start time, e.g. 1617580799000
* @param long $endTime (optional) End time, e.g. 1617580799000. Endtime is mandatory if startTime is set.
*
* @return array containing the response
* @throws \Exception
*/
public function dustLog($startTime = NULL, $endTime = NULL)
{
$params["sapi"] = true;
if (!empty($startTime) && !empty($endTime)) {
$params['startTime'] = $startTime;
$params['endTime'] = $endTime;
}
return $this->httpRequest("v1/asset/dribblet", 'GET', $params, true);
}
/**
* @deprecated
*
* Fetch current(daily) trade fee of symbol, values in percentage.
* for more info visit binance official api document
*
* $symbol = "BNBBTC"; or any other symbol or even a set of symbols in an array
* @param string $symbol
* @return mixed
*/
public function tradeFee(string $symbol)
{
$params = [
"symbol" => $symbol,
"wapi" => true,
];
trigger_error('Function tradeFee is deprecated and will be removed from Binance on Aug 1, 2021. Please use $api->commissionFee', E_USER_DEPRECATED);