├── LICENSE
├── README.md
├── composer.json
└── src
├── HitBTC.php
├── HitBtcAPIConf.php
├── HitBtcAPIPublic.php
├── HitBtcAPITrading.php
├── examples
└── get_total_balance_example.php
└── tools
└── Request.php
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 Dmytro Zarezenko
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # HitBTC API
2 | PHP wrapper for the HitBTC API
3 |
4 | [](https://packagist.org/packages/dzarezenko/hitbtc-api)
5 | [](https://packagist.org/packages/dzarezenko/hitbtc-api)
6 | [](https://styleci.io/repos/108166351)
7 | [](https://codeclimate.com/github/dzarezenko/hitbtc-api/maintainability)
8 |
9 |
10 |
11 | Requirements
12 | ------------
13 | The minimum requirement by HitBTC API is that your Web server supports PHP 5.6.
14 |
15 | Installation
16 | ------------
17 | To install HitBTC API package you can use simple `composer.json`...
18 |
19 | ```javascript
20 | {
21 | "minimum-stability": "dev",
22 | "require": {
23 | "php": ">=5.6.0",
24 | "dzarezenko/hitbtc-api": "*"
25 | }
26 | }
27 | ```
28 |
29 | or run command:
30 |
31 | ```
32 | composer require dzarezenko/hitbtc-api:dev-master
33 | ```
34 |
35 | Usage
36 | -----
37 | You can find usage examples in the `examples/` folder or ask for new example in the issues.
38 |
39 | Donate
40 | -----
41 | You can support this project by continuously donations to
42 | * ETH wallet: `0x8Ef300465FBf0f3867E85AC60D9faD9DC6a232d9`
43 | * BTC wallet: `1DKLUPCWoLFje7RBWVpDZk1tXjyRKHFkQw`
44 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "dzarezenko/hitbtc-api",
3 | "description": "PHP wrapper for the HitBTC API.",
4 | "type": "library",
5 | "keywords": ["hitbtc", "api"],
6 | "homepage": "https://github.com/dzarezenko/hitbtc-api",
7 | "license": "MIT",
8 | "authors": [
9 | {
10 | "name": "Dmytro Zarezenko",
11 | "email": "dmytro.zarezenko@gmail.com",
12 | "homepage": "https://github.com/dzarezenko",
13 | "role": "Development"
14 | }
15 | ],
16 | "support": {
17 | "email": "dmytro.zarezenko@gmail.com"
18 | },
19 | "minimum-stability": "dev",
20 | "require": {
21 | "php": ">=5.6.0"
22 | },
23 | "autoload": {
24 | "psr-4": {
25 | "hitbtc\\api\\": "src/"
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/HitBTC.php:
--------------------------------------------------------------------------------
1 |
10 | * @copyright (c) 2017, Dmytro Zarezenko
11 | *
12 | * @git https://github.com/dzarezenko/hitbtc-api
13 | * @license http://opensource.org/licenses/MIT
14 | */
15 | class HitBTC extends HitBtcAPITrading {
16 | /**
17 | * API version number.
18 | *
19 | * @var int
20 | */
21 | protected $apiVersion = 2;
22 |
23 | /**
24 | * Demo API flag.
25 | *
26 | * @var bool
27 | */
28 | private $isDemoAPI = false;
29 |
30 | /**
31 | * HitBTC public API object.
32 | *
33 | * @var HitBtcAPIPublic
34 | */
35 | private $publicAPI = null;
36 |
37 | /**
38 | * @var array Available balances list.
39 | */
40 | private $balances = null;
41 |
42 | /**
43 | * @var array Full balances information.
44 | */
45 | private $completeBalances = null;
46 |
47 | /**
48 | * @var array All deposit addresses list.
49 | */
50 | private $depositAddresses = null;
51 |
52 | /**
53 | * Initiates HitBTC API functionality. If API keys are not provided
54 | * then only public API methods will be available.
55 | *
56 | * @param string $apiKey HitBTC API key
57 | * @param string $apiSecret HitBTC API secret
58 | * @param int $apiVersion API version number.
59 | * @param bool $isDemoAPI Demo API flag
60 | *
61 | * @return
62 | */
63 | public function __construct($apiKey = null, $apiSecret = null, $apiVersion = 2, $isDemoAPI = false) {
64 | if (is_null($apiKey) || is_null($apiSecret)) {
65 | return;
66 | }
67 |
68 | $this->apiVersion = $apiVersion;
69 | $this->isDemoAPI = $isDemoAPI;
70 | $this->publicAPI = new HitBtcAPIPublic($this->apiVersion, $isDemoAPI);
71 |
72 | return parent::__construct($apiKey, $apiSecret, $isDemoAPI);
73 | }
74 |
75 | public function __call($method, $args) {
76 | return call_user_func_array([$this->publicAPI, $method], $args);
77 | }
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/src/HitBtcAPIConf.php:
--------------------------------------------------------------------------------
1 |
10 | * @copyright (c) 2017, Dmytro Zarezenko
11 | *
12 | * @git https://github.com/dzarezenko/hitbtc-api
13 | * @license http://opensource.org/licenses/MIT
14 | */
15 | class HitBtcAPIConf {
16 |
17 | const URL_DEMO = "http://demo-api.hitbtc.com";
18 | const URL = "http://api.hitbtc.com";
19 |
20 | const URL_DEMO_V2 = "https://demo-api.hitbtc.com";
21 | const URL_V2 = "https://api.hitbtc.com";
22 |
23 | const SEGMENT_TYPE_PUBLIC = 'public';
24 | const SEGMENT_TYPE_TRADING = 'trading';
25 |
26 | /**
27 | * Returns HitBTC API URL.
28 | *
29 | * @param int $apiVersion API version number
30 | * @param bool $isDemoAPI Demo API flag
31 | *
32 | * @return string HitBTC API URL
33 | */
34 | public static function getAPIUrl($apiVersion = 2, $isDemoAPI = false) {
35 | switch ($apiVersion) {
36 | case 1:
37 | return ($isDemoAPI ? self::URL_DEMO : self::URL);
38 | case 2:
39 | return ($isDemoAPI ? self::URL_DEMO_V2 : self::URL_V2);
40 | }
41 | }
42 |
43 | /**
44 | * Returns API URL segment for the API request.
45 | *
46 | * @param string $segmentType Segment type 'public' or 'trading'
47 | * @param int $apiVersion API version number
48 | *
49 | * @return string API URL segment
50 | */
51 | public static function getAPIUrlSegment($segmentType, $apiVersion = 2) {
52 | switch ($apiVersion) {
53 | case 1:
54 | return "/api/{$apiVersion}/{$segmentType}/";
55 | case 2:
56 | if ($segmentType === self::SEGMENT_TYPE_PUBLIC) {
57 | return "/api/{$apiVersion}/{$segmentType}/";
58 | }
59 |
60 | return "/api/{$apiVersion}/";
61 | }
62 | }
63 |
64 | }
65 |
--------------------------------------------------------------------------------
/src/HitBtcAPIPublic.php:
--------------------------------------------------------------------------------
1 |
14 | * @copyright (c) 2017, Dmytro Zarezenko
15 | *
16 | * @git https://github.com/dzarezenko/hitbtc-api
17 | * @license http://opensource.org/licenses/MIT
18 | */
19 | class HitBtcAPIPublic {
20 | /**
21 | * API version number.
22 | *
23 | * @var int
24 | */
25 | private $apiVersion = 2;
26 |
27 | /**
28 | * Demo API flag.
29 | *
30 | * @var bool
31 | */
32 | private $isDemoAPI = false;
33 |
34 | /**
35 | * Constructor of the class.
36 | *
37 | * @param int $apiVersion API version number.
38 | * @param bool $isDemoAPI Demo API flag
39 | */
40 | public function __construct($apiVersion = 2, $isDemoAPI = false) {
41 | $this->apiVersion = $apiVersion;
42 | $this->isDemoAPI = $isDemoAPI;
43 | }
44 |
45 | /**
46 | * Returns the server time in UNIX timestamp format.
47 | *
48 | * @return json
49 | */
50 | public function getTime() {
51 | return $this->_request('time');
52 | }
53 |
54 | /**
55 | * Returns the actual list of currency symbols traded on HitBTC exchange
56 | * with their characteristics.
57 | *
58 | * @return json
59 | */
60 | public function getSymbols() {
61 | return $this->_request('symbols');
62 | }
63 |
64 | /**
65 | * Return the actual list of available currencies, tokens, ICO etc.
66 | *
67 | * @param string $currency Currency ID.
68 | *
69 | * @return array JSON data.
70 | */
71 | public function getCurrency($currency = null) {
72 | return $this->_request('currency', ($currency) ? "currency/{$currency}" : null);
73 | }
74 |
75 | /**
76 | * Returns the actual data on exchange rates for all traded
77 | * cryptocurrencies - all tickers or specified cryptocurrency.
78 | *
79 | * @param string $symbol is a currency symbol traded on HitBTC exchange
80 | * (see https://hitbtc.com/api#cursymbols)
81 | *
82 | * @return json
83 | */
84 | public function getTicker($symbol = null) {
85 | switch ($this->apiVersion) {
86 | case 1:
87 | return $this->_request('ticker', ($symbol ? "$symbol/" : "") . 'ticker');
88 | case 2:
89 | $ticker = $this->_request('ticker', "ticker/" . ($symbol ? "$symbol" : ""));
90 | $assocTicker = []; // TODO: implement more efficient solution
91 | foreach ($ticker as $tickerData) {
92 | if (isset($tickerData['symbol'])) {
93 | $assocTicker[$tickerData['symbol']] = $tickerData;
94 | }
95 | }
96 | unset($ticker);
97 |
98 | return $assocTicker;
99 | }
100 | }
101 |
102 | /**
103 | * Returns a list of open orders for specified currency symbol:
104 | * their prices and sizes.
105 | *
106 | * @param string $symbol is a currency symbol traded on HitBTC exchange
107 | * (see https://hitbtc.com/api#cursymbols)
108 | * @param string $formatPrice Format of prices returned: as a string (default)
109 | * or as a number
110 | * @param string $formatAmount Format of amount returned: as a string (default)
111 | * or as a number
112 | * @param string $formatAmountUnit Units of amount returned: in currency units
113 | * (default) or in lots
114 | *
115 | * @return json
116 | */
117 | public function getOrderBook($symbol, $formatPrice = "string", $formatAmount = "string", $formatAmountUnit = "currency") {
118 | return $this->_request('orderbook',
119 | ($this->apiVersion == 1 ? "{$symbol}/orderbook" : "orderbook/{$symbol}")
120 | . "?format_price={$formatPrice}"
121 | . "&format_amount={$formatAmount}"
122 | . "&format_amount_unit={$formatAmountUnit}"
123 | );
124 | }
125 |
126 | /**
127 | * Returns data on trades for specified currency symbol in specified ID or
128 | * timestamp interval.
129 | *
130 | * Parameters list and more details: https://hitbtc.com/api#trades
131 | *
132 | * @param string $symbol is a currency symbol traded on HitBTC exchange
133 | * (see https://hitbtc.com/api#cursymbols)
134 | * @param string $by Selects if filtering and sorting is performed by trade_id
135 | * or by timestamp ('trade_id' or 'ts')
136 | * @param int $from Returns trades with trade_id > specified trade_id
137 | * (if by = 'trade_id') or returns trades with timestamp >= specified
138 | * timestamp (if by = 'ts')
139 | * @param int $startIndex Start index for the query, zero-based
140 | * @param int $maxResults Maximum quantity of returned items, at most 1000
141 | * @param array $optionalParams Optional parameters (see https://hitbtc.com/api#trades)
142 | *
143 | * @return json
144 | */
145 | public function getTrades($symbol, $by, $from, $startIndex = 0, $maxResults = 1000, $optionalParams = []) {
146 | $request = "$symbol/trades"
147 | . "?by={$by}"
148 | . "&from={$from}"
149 | . "&start_index={$startIndex}"
150 | . "&max_results={$maxResults}";
151 |
152 | foreach ($optionalParams as $param => $value) {
153 | $request.= "&{$param}={$value}";
154 | }
155 |
156 | return $this->_request('trades', $request);
157 | }
158 |
159 | /**
160 | * Returns recent trades for the specified currency symbol.
161 | * (https://hitbtc.com/api#recenttrades).
162 | *
163 | * @param string $symbol is a currency symbol traded on HitBTC exchange
164 | * (see https://hitbtc.com/api#cursymbols)
165 | * @param int $maxResults Maximum quantity of returned items, at most 1000
166 | * @param string $formatItem Format of items returned: as an array (default)
167 | * or as a list of objects ('array' or 'object')
168 | * @param bool $side Selects if the side of a trade is returned.
169 | *
170 | * @return json
171 | */
172 | public function getRecentTrades($symbol, $maxResults = 1000, $formatItem = 'array', $side = true) {
173 | $request = "$symbol/trades/recent"
174 | . "?max_results={$maxResults}"
175 | . "&format_item={$formatItem}"
176 | . "&side=" . ($side ? 'true' : 'false');
177 |
178 | return $this->_request('trades', $request);
179 | }
180 |
181 | /**
182 | * JSON request functionality wrapper.
183 | *
184 | * @param string $method API method name
185 | * @param string $request API request
186 | *
187 | * @return array JSON data.
188 | */
189 | private function _request($method, $request = null) {
190 | if (is_null($request)) {
191 | $request = $method;
192 | }
193 |
194 | $response = tools\Request::json($request, $this->apiVersion, $this->isDemoAPI);
195 |
196 | if (isset($response[$method])) {
197 | return $response[$method];
198 | }
199 |
200 | return $response;
201 | }
202 |
203 | }
204 |
--------------------------------------------------------------------------------
/src/HitBtcAPITrading.php:
--------------------------------------------------------------------------------
1 |
18 | * @copyright (c) 2017, Dmytro Zarezenko
19 | *
20 | * @git https://github.com/dzarezenko/hitbtc-api
21 | * @license http://opensource.org/licenses/MIT
22 | */
23 | class HitBtcAPITrading {
24 |
25 | private $apiKey = "";
26 | private $apiSecret = "";
27 |
28 | private $request = null;
29 |
30 | /**
31 | * Constructor of the class.
32 | *
33 | * @param string $apiKey HitBTC API key
34 | * @param string $apiSecret HitBTC API secret
35 | * @param bool $isDemoAPI Demo API flag
36 | */
37 | public function __construct($apiKey, $apiSecret, $isDemoAPI = false) {
38 | $this->apiKey = $apiKey;
39 | $this->apiSecret = $apiSecret;
40 |
41 | $this->request = new Request($this->apiKey, $this->apiSecret, $this->apiVersion, $isDemoAPI);
42 | }
43 |
44 | /**
45 | * Returns all of your available balances.
46 | *
47 | * @param bool $hideZeroBalances Hide zero balances or not.
48 | *
49 | * @return array JSON data.
50 | */
51 | public function getBalances($hideZeroBalances = false) {
52 | switch ($this->apiVersion) {
53 | case 1:
54 | $balances = $this->request('balance');
55 | if ($hideZeroBalances) {
56 | return array_filter($balances, function ($e) {
57 | return ($e['cash'] != 0 || $e['reserved'] != 0);
58 | });
59 | }
60 | break;
61 | case 2:
62 | $balances = $this->request('balance', "trading/balance");
63 | if ($hideZeroBalances) {
64 | return array_filter($balances, function ($e) {
65 | return ($e['available'] != 0 || $e['reserved'] != 0);
66 | });
67 | }
68 | break;
69 | }
70 |
71 | return $balances;
72 | }
73 |
74 | /**
75 | * Returns all orders in status new or partiallyFilled.
76 | *
77 | * @param string $clientOrderId Unique order ID.
78 | *
79 | * @return array JSON data.
80 | */
81 | public function getActiveOrders($clientOrderId = null) {
82 | $params = [];
83 | if ($clientOrderId) {
84 | $params['clientOrderId'] = $clientOrderId;
85 | }
86 |
87 | switch ($this->apiVersion) {
88 | case 1:
89 | return $this->request('orders', "orders/active", $params);
90 | case 2:
91 | return $this->request('order', $clientOrderId ? "order/{$clientOrderId}" : null);
92 | }
93 | }
94 |
95 | /**
96 | * create a new buy order at the market price
97 | * (or other option from $optional['type']: limit, stopLimit, stopMarket).
98 | *
99 | * @param string $currency is a currency symbol traded on HitBTC exchange
100 | * (see https://hitbtc.com/api#cursymbols)
101 | * @param string $amount order quantity
102 | * @param string $rate order price
103 | * @param array $optional Optional parameters array.
104 | *
105 | * @return json
106 | */
107 | public function buy($currency, $amount, $rate = null, $optional = []) {
108 | $optional['side'] = 'buy';
109 |
110 | return $this->addOrder($currency, $amount, $rate, $optional);
111 | }
112 |
113 | /**
114 | * create a new sell order at the market price
115 | * (or other option from $optional['type']: limit, stopLimit, stopMarket).
116 | *
117 | * @param string $currency is a currency symbol traded on HitBTC exchange
118 | * (see https://hitbtc.com/api#cursymbols)
119 | * @param string $amount order quantity
120 | * @param string $rate order price
121 | * @param array $optional Optional parameters array.
122 | *
123 | * @return json
124 | */
125 | public function sell($currency, $amount, $rate = null, $optional = []) {
126 | $optional['side'] = 'sell';
127 |
128 | return $this->addOrder($currency, $amount, $rate, $optional);
129 | }
130 |
131 | /**
132 | * Create a new order at the market price.
133 | *
134 | * @param string $currency is a currency symbol traded on HitBTC exchange
135 | * (see https://hitbtc.com/api#cursymbols)
136 | * @param string $amount order quantity
137 | * @param string $rate order price
138 | * @param array $params parameters array.
139 | *
140 | * @return json
141 | */
142 | public function addOrder($currency, $amount, $rate = null, $params = []) {
143 | $params['symbol'] = $currency;
144 | $params['quantity'] = $amount;
145 | if (empty($params['type'])) {
146 | $params['type'] = 'market';
147 | }
148 | if (!empty($rate)) {
149 | $params['price'] = $rate;
150 | }
151 |
152 | return $this->request('order', null, $params, 'POST');
153 | }
154 |
155 | /**
156 | * Closes all orders in status new or partiallyFilled.
157 | */
158 | public function cancelAllOrders() {
159 | return $this->request('order', null, [], 'DELETE');
160 | }
161 | /**
162 | * JSON request functionality wrapper.
163 | *
164 | * @param string $method API method name
165 | * @param string $request API request
166 | * @param string $httpmethod GET or POST
167 | *
168 | * @return array JSON data.
169 | */
170 | private function request($method, $request = null, $params = [], $httpmethod = 'GET') {
171 | if (is_null($request)) {
172 | $request = $method;
173 | }
174 |
175 | $response = $this->request->exec($request, $params, $httpmethod);
176 |
177 | if (isset($response[$method])) {
178 | return $response[$method];
179 | }
180 |
181 | return $response;
182 | }
183 |
184 | }
185 |
--------------------------------------------------------------------------------
/src/examples/get_total_balance_example.php:
--------------------------------------------------------------------------------
1 | apiKey, $keys->apiSecret);
8 |
9 | $balances = $hitBtc->getBalances(true);
10 | $ticker = $hitBtc->getTicker();
11 | $ethBtcTicker = $ticker['ETHBTC'];
12 | $ethBtcPrice = (float)$ethBtcTicker['last'];
13 |
14 | $btcValue = 0.0;
15 | foreach ($balances as $balance) {
16 | $currencyCode = $balance['currency'];
17 | $amount = (float)$balance['available'] + (float)$balance['reserved'];
18 |
19 | if ($currencyCode === "BTC") {
20 | $btcAmount = $amount;
21 | } elseif ($currencyCode === "ETH") {
22 | $btcAmount = $amount * $ethBtcPrice;
23 | } elseif (isset($ticker[$currencyCode . "BTC"])) {
24 | $btcAmount = (float)$ticker[$currencyCode . "BTC"]['last'] * $amount;
25 | } elseif (isset($ticker[$currencyCode . "ETH"])) {
26 | $ethAmount = (float)$ticker[$currencyCode . "ETH"]['last'] * $amount;
27 | $btcAmount = $ethBtcPrice * $ethAmount;
28 | } else {
29 | $btcAmount = 0.0;
30 | }
31 |
32 | $btcValue+= $btcAmount;
33 | }
34 |
35 | print(sprintf("%.8f\n", $btcValue));
36 |
--------------------------------------------------------------------------------
/src/tools/Request.php:
--------------------------------------------------------------------------------
1 |
12 | * @copyright (c) 2017, Dmytro Zarezenko
13 | *
14 | * @git https://github.com/dzarezenko/hitbtc-api
15 | * @license http://opensource.org/licenses/MIT
16 | */
17 | class Request {
18 |
19 | /**
20 | * HitBTC API Key value.
21 | *
22 | * @var string
23 | */
24 | private $apiKey = "";
25 |
26 | /**
27 | * HitBTC API Secret value.
28 | *
29 | * @var string
30 | */
31 | private $apiSecret = "";
32 |
33 | /**
34 | * API version number.
35 | *
36 | * @var int
37 | */
38 | private $apiVersion = 2;
39 |
40 | /**
41 | * Demo API flag.
42 | *
43 | * @var bool
44 | */
45 | private $isDemoAPI = false;
46 |
47 | /**
48 | * cURL handle.
49 | *
50 | * @var resource
51 | */
52 | private static $ch = null;
53 |
54 | /**
55 | * Initiates HitBTC API object for trading methods.
56 | *
57 | * @param string $apiKey HitBTC API Key value
58 | * @param string $apiSecret HitBTC API Secret value
59 | * @param int $apiVersion API version number.
60 | * @param bool $isDemoAPI Demo API flag
61 | */
62 | public function __construct($apiKey, $apiSecret, $apiVersion = 2, $isDemoAPI = false) {
63 | $this->apiKey = $apiKey;
64 | $this->apiSecret = $apiSecret;
65 |
66 | $this->apiVersion = $apiVersion;
67 | $this->isDemoAPI = $isDemoAPI;
68 | }
69 |
70 | /**
71 | * Executes curl request to the HitBTC API.
72 | *
73 | * @param string $request API entrypoint method.
74 | * @param array $params Request parameters list.
75 | * @param string $method HTTP method (default: 'GET').
76 | *
77 | * @return array JSON data.
78 | * @throws \Exception If Curl error or HitBTC API error occurred.
79 | */
80 | public function exec($request, array $params = [], $method = "GET") {
81 | usleep(100000);
82 |
83 | $requestUri = HitBtcAPIConf::getAPIUrlSegment(HitBtcAPIConf::SEGMENT_TYPE_TRADING, $this->apiVersion)
84 | . $request;
85 | if ($this->apiVersion == 1) {
86 | $requestUri.= "?nonce=" . self::getNonce() . "&apikey=" . $this->apiKey;
87 | }
88 |
89 | // generate the POST data string
90 | $params = http_build_query($params);
91 | if (strlen($params) && $method === 'GET') {
92 | $requestUri .= '&' . $params;
93 | }
94 |
95 | // curl handle (initialize if required)
96 | if (is_null(self::$ch)) {
97 | self::$ch = curl_init();
98 | }
99 |
100 | if ($this->apiVersion == 2) {
101 | curl_setopt(self::$ch, CURLOPT_USERPWD, $this->apiKey . ":" . $this->apiSecret);
102 | }
103 | curl_setopt(self::$ch, CURLOPT_URL, HitBtcAPIConf::getAPIUrl($this->apiVersion, $this->isDemoAPI) . $requestUri);
104 | curl_setopt(self::$ch, CURLOPT_CONNECTTIMEOUT, 10);
105 | curl_setopt(self::$ch, CURLOPT_RETURNTRANSFER, true);
106 |
107 | if ($method === 'POST') {
108 | curl_setopt(self::$ch, CURLOPT_POST, true);
109 | curl_setopt(self::$ch, CURLOPT_POSTFIELDS, $params);
110 | }
111 |
112 | if ($method === 'DELETE') {
113 | curl_setopt(self::$ch, CURLOPT_CUSTOMREQUEST, "DELETE");
114 | }
115 |
116 | curl_setopt(self::$ch, CURLOPT_HTTPHEADER, [
117 | 'X-Signature: ' . strtolower(hash_hmac('sha512', $requestUri . (($method === 'POST') ? $params : ''), $this->apiSecret))
118 | ]);
119 |
120 | // run the query
121 | $res = curl_exec(self::$ch);
122 | if ($res === false) {
123 | $e = curl_error(self::$ch);
124 | curl_close(self::$ch);
125 |
126 | throw new \Exception("Curl error: " . $e);
127 | }
128 | curl_close(self::$ch);
129 |
130 | $json = json_decode($res, true);
131 |
132 | // Check for the HitBTC API error
133 | if (isset($json['error'])) {
134 | throw new \Exception(
135 | "HitBTC API error ({$json['error']['code']}): {$json['error']['message']}. {$json['error']['description']}"
136 | );
137 | }
138 |
139 | return $json;
140 | }
141 |
142 | /**
143 | * Executes simple GET request to the HitBtc public API.
144 | *
145 | * @param string $request API entrypoint method.
146 | * @param int $apiVersion API version number.
147 | * @param bool $isDemoAPI Demo API flag.
148 | *
149 | * @return array JSON data.
150 | */
151 | public static function json($request, $apiVersion = 2, $isDemoAPI = false) {
152 | $ch = curl_init();
153 |
154 | curl_setopt($ch, CURLOPT_URL,
155 | HitBtcAPIConf::getAPIUrl($apiVersion, $isDemoAPI)
156 | . HitBtcAPIConf::getAPIUrlSegment(HitBtcAPIConf::SEGMENT_TYPE_PUBLIC, $apiVersion)
157 | . $request
158 | );
159 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
160 |
161 | $output = curl_exec($ch);
162 |
163 | curl_close($ch);
164 |
165 | switch ($output) {
166 | case ("Not implemented"):
167 | $json = [
168 | 'error' => [
169 | 'message' => $output
170 | ]
171 | ];
172 | break;
173 | default:
174 | $json = json_decode($output, true);
175 | }
176 |
177 | return $json;
178 | }
179 |
180 | private static function getNonce() {
181 | $mt = explode(' ', microtime());
182 |
183 | return ($mt[1] . substr($mt[0], 2, 6));
184 | }
185 |
186 | }
187 |
--------------------------------------------------------------------------------