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:
<?php
namespace Larislackers\BinanceApi;
use GuzzleHttp\Client;
use Larislackers\BinanceApi\Enums\ConnectionDetails;
use Larislackers\BinanceApi\Exception\BinanceApiException;
use Larislackers\BinanceApi\Exception\LarislackersException;
use Ratchet\Client\WebSocket;
use Ratchet\RFC6455\Messaging\MessageInterface;
/**
* Wrapper container for Binance API.
*
* @package Larislackers\BinanceApi
*/
class BinanceApiContainer
{
/**
* API key.
*
* @var string
*/
private $_apiKey;
/**
* API secret.
*
* @var string
*/
private $_apiSecret;
/**
* BinanceApiContainer constructor.
*
* @param string $apiKey The API key from Binance.
* @param string $apiSecret The API secret from Binance.
*/
public function __construct($apiKey, $apiSecret)
{
$this->_apiKey = $apiKey;
$this->_apiSecret = $apiSecret;
}
/**
* Gets the API key.
*
* @return string
*/
public function getApiKey()
{
return $this->_apiKey;
}
/**
* Gets the API secret.
*
* @return string
*/
public function getApiSecret()
{
return $this->_apiSecret;
}
/**
* Test connectivity to the Rest API.
*
* @return \Psr\Http\Message\ResponseInterface
*
* @link https://www.binance.com/restapipub.html#test-connectivity
*/
public function ping()
{
return $this->_makeApiRequest('GET', 'ping');
}
/**
* Test connectivity to the Rest API and get the current server time.
*
* @return \Psr\Http\Message\ResponseInterface
*
* @link https://www.binance.com/restapipub.html#check-server-time
*/
public function getServerTime()
{
return $this->_makeApiRequest('GET', 'time');
}
/**
* Returns the order book for the market.
*
* @param array $params The data to send.
* @option string "symbol" The symbol to search for. (required)
* @option int "limit" The number of results returned from the query. (max value 100)
*
* @return \Psr\Http\Message\ResponseInterface
*
* @link https://www.binance.com/restapipub.html#order-book
*/
public function getOrderBook($params)
{
return $this->_makeApiRequest('GET', 'depth', 'NONE', $params);
}
/**
* Returns compressed, aggregate trades.
* Trades that fill at the time, from the same order, with the same price will have the quantity aggregated.
*
* @param array $params The data to send.
* @option string "symbol" The symbol to search for. (required)
* @option int "fromId" ID to get aggregate trades from INCLUSIVE.
* @option int "startTime" Timestamp in milliseconds to get aggregate trades from INCLUSIVE.
* @option int "endTime" Timestamp in milliseconds to get aggregate trades until INCLUSIVE.
* @option int "limit" The number of results returned from the query. (max value 500)
*
* @return \Psr\Http\Message\ResponseInterface
* @throws \Exception
*
* @link https://www.binance.com/restapipub.html#compressedaggregate-trades-list
*/
public function getAggTrades($params)
{
return $this->_makeApiRequest('GET', 'aggTrades', 'NONE', $params);
}
/**
* Returns kline/candlesticks bars for a symbol.
* Klines are uniquely identified by their open time.
*
* @param array $params The data to send.
* @option string "symbol" The symbol to search for. (required)
* @option string "interval" Kline intervals enum. (required)
* @option int "startTime" Timestamp in milliseconds to get aggregate trades from INCLUSIVE.
* @option int "endTime" Timestamp in milliseconds to get aggregate trades until INCLUSIVE.
* @option int "limit" The number of results returned from the query. (max value 500)
*
* @return \Psr\Http\Message\ResponseInterface
*
* @link https://www.binance.com/restapipub.html#klinecandlesticks
*/
public function getKlines($params)
{
return $this->_makeApiRequest('GET', 'klines', 'NONE', $params);
}
/**
* Returns 24 hour price change statistics.
*
* @param array $params The data to send.
* @option string "symbol" The symbol to search for. (required)
*
* @return \Psr\Http\Message\ResponseInterface
*
* @link https://www.binance.com/restapipub.html#24hr-ticker-price-change-statistics
*/
public function getTwentyFourTickerPrice($params)
{
return $this->_makeApiRequest('GET', 'ticker/24hr', 'NONE', $params);
}
/**
* Returns latest price for all symbols.
*
* @return \Psr\Http\Message\ResponseInterface
*
* @link https://www.binance.com/restapipub.html#symbols-price-ticker
*/
public function getTickers()
{
return $this->_makeApiRequest('GET', 'ticker/allPrices');
}
/**
* Returns price/qty on the order book for all symbols.
*
* @return \Psr\Http\Message\ResponseInterface
*
* @link https://www.binance.com/restapipub.html#symbols-order-book-ticker
*/
public function getBookTickers()
{
return $this->_makeApiRequest('GET', 'ticker/allBookTickers');
}
/**
* Send in a new order.
*
* @param array $params The data to send.
* @option string "symbol" The symbol to search for. (required)
* @option string "side" Order side enum. (required)
* @option string "type" Order type enum. (required)
* @option string "timeInForce" Time in force enum. (required)
* @option double "quantity" Desired quantity. (required)
* @option double "price" Asking price. (required)
* @option string "newClientOrderId" A unique id for the order. Automatically generated by default.
* @option double "stopPrice" Used with STOP orders.
* @option double "icebergQty" Used with icebergOrders.
* @option int "timestamp" A UNIX timestamp. (required)
*
* @return \Psr\Http\Message\ResponseInterface
*
* @link https://www.binance.com/restapipub.html#new-order--signed
*/
public function postOrder($params)
{
return $this->_makeApiRequest('POST', 'order', 'SIGNED', $params);
}
/**
* Test new order creation and signature/recvWindow long.
* Creates and validates a new order but does not send it into the matching engine.
*
* @param array $params The data to send.
* @option string "symbol" The symbol to search for. (required)
* @option string "side" Order side enum. (required)
* @option string "type" Order type enum. (required)
* @option string "timeInForce" Time in force enum. (required)
* @option double "quantity" Desired quantity. (required)
* @option double "price" Asking price. (required)
* @option string "newClientOrderId" A unique id for the order. Automatically generated by default.
* @option double "stopPrice" Used with STOP orders.
* @option double "icebergQty" Used with icebergOrders.
* @option int "timestamp" A UNIX timestamp. (required)
* @option int "recvWindow" The number of milliseconds after timestamp the request is valid for.
*
* @return \Psr\Http\Message\ResponseInterface
*
* @link https://www.binance.com/restapipub.html#test-new-order-signed
*/
public function postOrderTest($params)
{
return $this->_makeApiRequest('POST', 'order/test', 'SIGNED', $params);
}
/**
* Check an order's status.
*
* @param array $params The data to send.
* @option string "symbol" The symbol to search for. (required)
* @option int "orderId" The order ID.
* @option string "origClientOrderId" The original client order ID.
* @option int "timestamp" A UNIX timestamp. (required)
* @option int "recvWindow" The number of milliseconds after timestamp the request is valid for.
*
* @return \Psr\Http\Message\ResponseInterface
* @throws \Exception
*
* @link https://www.binance.com/restapipub.html#query-order-signed
*/
public function getOrder($params)
{
return $this->_makeApiRequest('GET', 'order', 'SIGNED', $params);
}
/**
* Cancel an active order.
*
* @param array $params The data to send.
* @option string "symbol" The symbol to search for. (required)
* @option int "orderId" The order ID.
* @option string "origClientOrderId" The original client order ID.
* @option string "newClientOrderId" Used to uniquely identify this cancel. Automatically generated by default.
* @option int "timestamp" A UNIX timestamp. (required)
* @option int "recvWindow" The number of milliseconds after timestamp the request is valid for.
*
* @return \Psr\Http\Message\ResponseInterface
* @throws \Exception
*
* @link https://www.binance.com/restapipub.html#cancel-order-signed
*/
public function cancelOrder($params)
{
return $this->_makeApiRequest('DELETE', 'order', 'SIGNED', $params);
}
/**
* Returns all open orders on a symbol.
*
* @param array $params The data to send.
* @option string "symbol" The symbol to search for. (required)
* @option int "timestamp" A UNIX timestamp. (required)
* @option int "recvWindow" The number of milliseconds after timestamp the request is valid for.
*
* @return \Psr\Http\Message\ResponseInterface
*
* @link https://www.binance.com/restapipub.html#current-open-orders-signed
*/
public function getOpenOrders($params)
{
return $this->_makeApiRequest('GET', 'openOrders', 'SIGNED', $params);
}
/**
* Returns all account orders; active, canceled, or filled.
*
* @param array $params The data to send.
* @option string "symbol" The symbol to search for. (required)
* @option int "orderId" The order ID.
* @option int "timestamp" A UNIX timestamp. (required)
* @option int "limit" The request limit, max value 500, min value 1.
* @option int "recvWindow" The number of milliseconds after timestamp the request is valid for.
*
* @return \Psr\Http\Message\ResponseInterface
*
* @link https://www.binance.com/restapipub.html#all-orders-signed
*/
public function getOrders($params)
{
return $this->_makeApiRequest('GET', 'allOrders', 'SIGNED', $params);
}
/**
* Returns current account information.
*
* @param array $params The data to send.
* @option int "timestamp" A UNIX timestamp. (required)
* @option int "recvWindow" The number of milliseconds after timestamp the request is valid for.
*
* @return \Psr\Http\Message\ResponseInterface
*
* @link https://www.binance.com/restapipub.html#account-information-signed
*/
public function getAccount($params)
{
return $this->_makeApiRequest('GET', 'account', 'SIGNED', $params);
}
/**
* Returns trades for a specific account and symbol.
*
* @param array $params The data to send.
* @option string "symbol" The symbol to search for. (required)
* @option int "fromId" The order ID.
* @option int "timestamp" A UNIX timestamp. (required)
* @option int "limit" The number of results returned from the query. (max value 500)
* @option int "recvWindow" The number of milliseconds after timestamp the request is valid for.
*
* @return \Psr\Http\Message\ResponseInterface
*
* @link https://www.binance.com/restapipub.html#account-trade-list-signed
*/
public function getTrades($params)
{
return $this->_makeApiRequest('GET', 'myTrades', 'SIGNED', $params);
}
/**
* Submit a withdraw request.
*
* @param array $params The data to send.
* @option string "asset" The requested asset. (required)
* @option string "address" The request address. (required)
* @option double "amount" The request amount. (required)
* @option string "name" Description of the address.
* @option int "recvWindow" The number of milliseconds after timestamp the request is valid for.
* @option int "timestamp" A UNIX timestamp. (required)
*
* @return \Psr\Http\Message\ResponseInterface
*
* @link https://www.binance.com/restapipub.html#account-trade-list-signed
*/
public function withdraw($params)
{
return $this->_makeApiRequest('POSTV2', 'wapi/v1/withdraw.html', 'WAPI_SIGNED', $params);
}
/**
* Fetch deposit history.
*
* @param array $params The data to send.
* @option string "asset" The requested asset.
* @option enum "status" Enum as WAPI_DEPOSIT_STATUS_*.
* @option int "startTime" Timestamp in milliseconds.
* @option int "endTime" Timestamp in milliseconds.
* @option int "recvWindow" The number of milliseconds after timestamp the request is valid for.
* @option int "timestamp" A UNIX timestamp. (required)
*
* @return \Psr\Http\Message\ResponseInterface
*
* @link https://www.binance.com/restapipub.html#account-trade-list-signed
*/
public function getDepositHistory($params)
{
return $this->_makeApiRequest('POSTV2', 'wapi/v1/getDepositHistory.html', 'WAPI_SIGNED', $params);
}
/**
* Fetch withdraw history.
*
* @param array $params The data to send.
* @option string "asset" The requested asset.
* @option enum "status" Enum as WAPI_WITHDRAW_STATUS_*.
* @option int "startTime" Timestamp in milliseconds.
* @option int "endTime" Timestamp in milliseconds.
* @option int "recvWindow" The number of milliseconds after timestamp the request is valid for.
* @option int "timestamp" A UNIX timestamp. (required)
*
* @return \Psr\Http\Message\ResponseInterface
*
* @link https://www.binance.com/restapipub.html#account-trade-list-signed
*/
public function getWithdrawHistory($params)
{
return $this->_makeApiRequest('POSTV2', 'wapi/v1/getWithdrawHistory.html', 'WAPI_SIGNED', $params);
}
/**
* Start a new user data stream.
*
* @return \Psr\Http\Message\ResponseInterface
*
* @link https://www.binance.com/restapipub.html#start-user-data-stream-api-key
*/
public function startUserDataStream()
{
return $this->_makeApiRequest('POST', 'userDataStream', 'API-KEY');
}
/**
* PING a user data stream to prevent a time out.
*
* @param array $params The data to send.
* @option string "listenKey" The key for the user's data steam. (required)
*
* @return \Psr\Http\Message\ResponseInterface
*
* @link https://www.binance.com/restapipub.html#keepalive-user-data-stream-api-key
*/
public function keepaliveUserDataStream($params)
{
return $this->_makeApiRequest('PUT', 'userDataStream', 'API-KEY', $params);
}
/**
* Close out a user data stream.
*
* @param array $params The data to send.
* @option string "listenKey" The key for the user's data steam. (required)
*
* @return \Psr\Http\Message\ResponseInterface
*
* @link https://www.binance.com/restapipub.html#close-user-data-stream-api-key
*/
public function closeUserDataStream($params)
{
return $this->_makeApiRequest('DELETE', 'userDataStream', 'API-KEY', $params);
}
/**
* Websocket url for depth endpoint.
*
* @param array $params The data to send.
* @option string "symbol" The symbol to search for. (required)
*
* @link https://www.binance.com/restapipub.html#depth-wss-endpoint
*/
public function depthWebsocket($params)
{
$this->_makeWebsocketRequest('DEPTH', $params);
}
/**
* Websocket url for kline endpoint.
*
* @param array $params The data to send.
* @option string "symbol" The symbol to search for. (required)
* @option string "interval" Kline intervals enum. (required)
*
* @link https://www.binance.com/restapipub.html#kline-wss-endpoint
*/
public function klineWebsocket($params)
{
$this->_makeWebsocketRequest('KLINE', $params);
}
/**
* Websocket url for trades endpoint.
*
* @param array $params The data to send.
* @option string "symbol" The symbol to search for. (required)
*
* @link https://www.binance.com/restapipub.html#trades-wss-endpoint
*/
public function tradesWebsocket($params)
{
$this->_makeWebsocketRequest('TRADES', $params);
}
/**
* Websocket url for user data endpoint.
*
* @param array $params The data to send.
* @option string "listenKey" The key for the user's data steam. (required)
*
* @link https://www.binance.com/restapipub.html#user-wss-endpoint
*/
public function userWebsocket($params)
{
$this->_makeWebsocketRequest('USER', $params);
}
/**
* Does an HTTP request to the given endpoint with the given parameters.
*
* @param string $type The HTTP method.
* @param string $endPoint The API endpoint.
* @param string $securityType Security type enum.
* @param array $params Additional parameters.
*
* @return \Psr\Http\Message\ResponseInterface
* @throws BinanceApiException
*/
private function _makeApiRequest($type, $endPoint, $securityType = 'NONE', $params = [])
{
$params = array_filter($params, 'strlen');
switch (strtoupper($securityType)) {
default:
case 'NONE':
$client = new Client(['http_errors' => false]);
$url = ConnectionDetails::API_URL . ConnectionDetails::API_VERSION . $endPoint;
break;
case 'API-KEY':
$client = new Client(['headers' => ['X-MBX-APIKEY' => $this->_apiKey], 'http_errors' => false]);
$url = ConnectionDetails::API_URL . ConnectionDetails::API_VERSION . $endPoint;
break;
case 'SIGNED':
$client = new Client(['headers' => ['X-MBX-APIKEY' => $this->_apiKey], 'http_errors' => false]);
$url = ConnectionDetails::API_URL . ConnectionDetails::API_VERSION_SIGNED . $endPoint;
$params['signature'] = hash_hmac('sha256', http_build_query($params), $this->_apiSecret);
break;
case 'WAPI_SIGNED':
$client = new Client(['headers' => ['X-MBX-APIKEY' => $this->_apiKey], 'http_errors' => false]);
$url = ConnectionDetails::API_URL . $endPoint;
$params['signature'] = hash_hmac('sha256', http_build_query($params), $this->_apiSecret);
break;
}
switch (strtoupper($type)) {
default:
case 'GET':
$params['query'] = $params;
break;
case 'POST':
case 'PUT':
case 'DELETE':
$params['form_params'] = $params;
break;
case 'POSTV2':
$type = 'POST';
$params['query'] = $params;
break;
}
$response = $client->request(strtoupper($type), $url, $params);
if ($response->getStatusCode() < 200 || $response->getStatusCode() > 299) {
throw new BinanceApiException($response->getBody()->getContents());
}
return $response;
}
/**
* Opens a websocket connection and transmits received messages until closed.
*
* @param string $type The websocket method.
* @param array $params The parameters to send.
* @param bool $once If true, it will close the connection after the first successful message.
*
* @return void
* @throws LarislackersException
*/
private function _makeWebsocketRequest($type, $params, $once = false)
{
switch (strtoupper($type)) {
default:
case 'DEPTH':
$url = ConnectionDetails::WEBSOCKET_URL . strtolower($params['symbol']) . '@depth';
break;
case 'KLINE':
$url = ConnectionDetails::WEBSOCKET_URL . strtolower($params['symbol']) . '@kline_' . $params['interval'];
break;
case 'TRADES':
$url = ConnectionDetails::WEBSOCKET_URL . strtolower($params['symbol']) . '@aggTrade';
break;
case 'USER':
$url = ConnectionDetails::WEBSOCKET_URL . strtolower($params['symbol']);
break;
}
\Ratchet\Client\connect($url)->then(function (WebSocket $conn) use ($once) {
$conn->on('message', function (MessageInterface $msg) use ($conn, $once) {
echo $msg . "\n";
if ($once) $conn->close();
});
$conn->on('close', function ($code = null, $reason = null) {
echo 'Connection closed (' . $code . ' - ' . $reason . ')';
});
$conn->on('error', function () {
throw new LarislackersException('[ERROR|Websocket] Could not establish a connection.');
});
});
}
}