forked from jaggedsoft/php-binance-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
php-binance-api.php
executable file
·2408 lines (2209 loc) · 80.9 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;
// 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 $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 $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 $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
*
* @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;
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'] : "";
}
/**
* 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'] : "";
}
}
/**
* 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);
}
/**
* 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]);
}
/**
* 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);
}
/**
* 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
*
* $allHistory = $api->history();
* $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
* @return array with error message or array of orderDetails array
* @throws \Exception
*/
public function history(string $symbol, int $limit = 500, int $fromTradeId = -1)
{
$parameters = [
"symbol" => $symbol,
"limit" => $limit,
];
if ($fromTradeId > 0) {
$parameters["fromId"] = $fromTradeId;
}
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("v1/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("v1/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("v1/exchangeInfo");
$this->exchangeInfo = $arr;
$this->exchangeInfo['symbols'] = null;
foreach($arr['symbols'] as $key => $value){
$this->exchangeInfo['symbols'][$value['symbol']] = $value;
}
}
return $this->exchangeInfo;
}
public function assetDetail()
{
$params["wapi"] = true;
return $this->httpRequest("v3/assetDetail.html", 'GET', $params, true);
}
/**
* 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,
];
return $this->httpRequest("v3/tradeFee.html", 'GET', $params, true);
}
/**
* withdraw requests a asset be withdrawn from binance to another wallet
*
* $asset = "BTC";
* $address = "1C5gqLRs96Xq4V2ZZAR1347yUCpHie7sa";
* $amount = 0.2;
* $response = $api->withdraw($asset, $address, $amount);
*
* $address = "44tLjmXrQNrWJ5NBsEj2R77ZBEgDa3fEe9GLpSf2FRmhexPvfYDUAB7EXX1Hdb3aMQ9FLqdJ56yaAhiXoRsceGJCRS3Jxkn";
* $addressTag = "0e5e38a01058dbf64e53a4333a5acf98e0d5feb8e523d32e3186c664a9c762c1";
* $amount = 0.1;
* $response = $api->withdraw($asset, $address, $amount, $addressTag);
*
* @param $asset string the currency such as BTC
* @param $address string the addressed to whihc the asset should be deposited
* @param $amount double the amount of the asset to transfer
* @param $addressTag string adtional transactionid required by some assets
* @return array with error message or array transaction
* @throws \Exception
*/
public function withdraw(string $asset, string $address, $amount, $addressTag = null, $addressName = "", bool $transactionFeeFlag = false,$network = null)
{
$options = [
"asset" => $asset,
"address" => $address,
"amount" => $amount,
"transactionFeeFlag" => $transactionFeeFlag,
"wapi" => true,
];
if (is_null($addressName) === false && empty($addressName) === false) {
$options['name'] = str_replace(' ', '%20', $addressName);
}
if (is_null($addressTag) === false && empty($addressTag) === false) {
$options['addressTag'] = $addressTag;
}
if (is_null($network) === false && empty($network) === false) {
$options['network'] = $network;
}
return $this->httpRequest("v3/withdraw.html", "POST", $options, true);
}
/**
* depositAddress get the deposit address for an asset
*
* $depositAddress = $api->depositAddress("VEN");
*
* @param $asset string the currency such as BTC
* @return array with error message or array deposit address information
* @throws \Exception
*/
public function depositAddress(string $asset)
{
$params = [
"wapi" => true,
"asset" => $asset,
];
return $this->httpRequest("v3/depositAddress.html", "GET", $params, true);
}
/**
* depositAddress get the deposit history for an asset
*
* $depositHistory = $api->depositHistory();
*
* $depositHistory = $api->depositHistory( "BTC" );
*
* @param $asset string empty or the currency such as BTC
* @param $params array optional startTime, endTime, status parameters
* @return array with error message or array deposit history information
* @throws \Exception
*/
public function depositHistory(string $asset = null, array $params = [])
{
$params["wapi"] = true;
if (is_null($asset) === false) {
$params['asset'] = $asset;
}
return $this->httpRequest("v3/depositHistory.html", "GET", $params, true);
}
/**
* withdrawHistory get the withdrawal history for an asset
*
* $withdrawHistory = $api->withdrawHistory();
*
* $withdrawHistory = $api->withdrawHistory( "BTC" );
*
* @param $asset string empty or the currency such as BTC
* @param $params array optional startTime, endTime, status parameters
* @return array with error message or array deposit history information
* @throws \Exception
*/
public function withdrawHistory(string $asset = null, array $params = [])
{
$params["wapi"] = true;
if (is_null($asset) === false) {
$params['asset'] = $asset;
}
return $this->httpRequest("v3/withdrawHistory.html", "GET", $params, true);
}
/**
* withdrawFee get the withdrawal fee for an asset
*
* $withdrawFee = $api->withdrawFee( "BTC" );
*
* @param $asset string currency such as BTC
* @return array with error message or array containing withdrawFee
* @throws \Exception
*/
public function withdrawFee(string $asset)
{
$params = [
"wapi" => true,
];
$response = $this->httpRequest("v3/assetDetail.html", "GET", $params, true);
if (isset($response['success'], $response['assetDetail'], $response['assetDetail'][$asset]) && $response['success']) {
return $response['assetDetail'][$asset];
}
}
/**
* prices get all the current prices
*
* $ticker = $api->prices();
*
* @return array with error message or array of all the currencies prices
* @throws \Exception
*/
public function prices()
{
return $this->priceData($this->httpRequest("v3/ticker/price"));
}
/**
* price get the latest price of a symbol
*
* $price = $api->price( "ETHBTC" );
*
* @return array with error message or array with symbol price
* @throws \Exception
*/
public function price(string $symbol)
{
$ticker = $this->httpRequest("v3/ticker/price", "GET", ["symbol" => $symbol]);
return $ticker['price'];
}
/**
* bookPrices get all bid/asks prices
*
* $ticker = $api->bookPrices();
*
* @return array with error message or array of all the book prices
* @throws \Exception
*/
public function bookPrices()
{
return $this->bookPriceData($this->httpRequest("v3/ticker/bookTicker"));
}
/**
* account get all information about the api account
*
* $account = $api->account();
*
* @return array with error message or array of all the account information
* @throws \Exception
*/
public function account()
{
return $this->httpRequest("v3/account", "GET", [], true);
}
/**
* prevDay get 24hr ticker price change statistics for symbols
*
* $prevDay = $api->prevDay("BNBBTC");
*
* @param $symbol (optional) symbol to get the previous day change for
* @return array with error message or array of prevDay change
* @throws \Exception
*/
public function prevDay(string $symbol = null)
{
$additionalData = [];
if (is_null($symbol) === false) {
$additionalData = [
'symbol' => $symbol,
];
}
return $this->httpRequest("v1/ticker/24hr", "GET", $additionalData);
}
/**
* aggTrades get Market History / Aggregate Trades
*
* $trades = $api->aggTrades("BNBBTC");
*
* @param $symbol string the symbol to get the trade information for
* @return array with error message or array of market history
* @throws \Exception
*/
public function aggTrades(string $symbol)
{
return $this->tradesData($this->httpRequest("v1/aggTrades", "GET", [
"symbol" => $symbol,
]));
}
/**
* depth get Market depth
*
* $depth = $api->depth("ETHBTC");
*
* @param $symbol string the symbol to get the depth information for
* @param $limit int set limition for number of market depth data
* @return array with error message or array of market depth
* @throws \Exception
*/
public function depth(string $symbol, int $limit = 100)
{
if (is_int($limit) === false) {
$limit = 100;
}
if (isset($symbol) === false || is_string($symbol) === false) {
// WPCS: XSS OK.
echo "asset: expected bool false, " . gettype($symbol) . " given" . PHP_EOL;
}
$json = $this->httpRequest("v1/depth", "GET", [
"symbol" => $symbol,
"limit" => $limit,
]);
if (isset($this->info[$symbol]) === false) {
$this->info[$symbol] = [];
}
$this->info[$symbol]['firstUpdate'] = $json['lastUpdateId'];
return $this->depthData($symbol, $json);
}
/**
* balances get balances for the account assets
*
* $balances = $api->balances($ticker);
*
* @param bool $priceData array of the symbols balances are required for
* @return array with error message or array of balances
* @throws \Exception
*/
public function balances($priceData = false)
{
if (is_array($priceData) === false) {
$priceData = false;
}
$account = $this->httpRequest("v3/account", "GET", [], true);
if (is_array($account) === false) {
echo "Error: unable to fetch your account details" . PHP_EOL;
}
if (isset($account['balances']) === false || empty($account['balances'])) {
echo "Error: your balances were empty or unset" . PHP_EOL;
return [];
}
return $this->balanceData($account, $priceData);
}
/**
* getProxyUriString get Uniform Resource Identifier string assocaited with proxy config
*
* $balances = $api->getProxyUriString();
*
* @return string uri
*/
public function getProxyUriString()
{
$uri = isset($this->proxyConf['proto']) ? $this->proxyConf['proto'] : "http";
// https://curl.haxx.se/libcurl/c/CURLOPT_PROXY.html
$supportedProtocols = array(
'http',
'https',
'socks4',
'socks4a',
'socks5',
'socks5h',
);
if (in_array($uri, $supportedProtocols) === false) {
// WPCS: XSS OK.
echo "Unknown proxy protocol '" . $this->proxyConf['proto'] . "', supported protocols are " . implode(", ", $supportedProtocols) . PHP_EOL;
}
$uri .= "://";
$uri .= isset($this->proxyConf['address']) ? $this->proxyConf['address'] : "localhost";
if (isset($this->proxyConf['address']) === false) {
// WPCS: XSS OK.
echo "warning: proxy address not set defaulting to localhost" . PHP_EOL;
}
$uri .= ":";
$uri .= isset($this->proxyConf['port']) ? $this->proxyConf['port'] : "1080";
if (isset($this->proxyConf['address']) === false) {
// WPCS: XSS OK.
echo "warning: proxy port not set defaulting to 1080" . PHP_EOL;
}
return $uri;
}
/**
* setProxy set proxy config by passing in an array of the proxy configuration
*
* $proxyConf = [
* 'proto' => 'tcp',
* 'address' => '192.168.1.1',
* 'port' => '8080',
* 'user' => 'dude',
* 'pass' => 'd00d'
* ];
*
* $api->setProxy( $proxyconf );
*
* @return null
*/
public function setProxy(array $proxyconf)
{
$this->proxyConf = $proxyconf;
}
/**
* httpRequest curl wrapper for all http api requests.
* You can't call this function directly, use the helper functions
*
* @see buy()
* @see sell()
* @see marketBuy()
* @see marketSell() $this->httpRequest( "https://api.binance.com/api/v1/ticker/24hr");
*
* @param $url string the endpoint to query, typically includes query string
* @param $method string this should be typically GET, POST or DELETE
* @param $params array addtional options for the request
* @param $signed bool true or false sign the request with api secret
* @return array containing the response
* @throws \Exception
*/
protected function httpRequest(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->base;
$ts = (microtime(true) * 1000) + $this->info['timeOffset'];
$params['timestamp'] = number_format($ts, 0, '.', '');
if (isset($params['wapi'])) {
unset($params['wapi']);
$base = $this->wapi;
}
if (isset($params['sapi'])) {
unset($params['sapi']);
$base = $this->sapi;
}
$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->base . $url . '?' . $query);
}
// no params so just the base url
else {
curl_setopt($curl, CURLOPT_URL, $this->base . $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") {