This repository has been archived by the owner on Oct 30, 2023. It is now read-only.
forked from jaggedsoft/php-binance-api
-
Notifications
You must be signed in to change notification settings - Fork 94
/
php-binance-api-rate-limiter.php
executable file
·264 lines (237 loc) · 8.01 KB
/
php-binance-api-rate-limiter.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
<?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");
}
/**
* Wrapper/Decorator for the binance api, providing rate limiting
*
* Eg. Usage:
* require 'vendor/autoload.php';
* $api = new Binance\\API();
* $api = new Binance\\RateLimiter($api);
*/
class RateLimiter
{
private $api = null;
private $weights = null;
private $ordersfunctions = null;
private $exchangeRequestsRateLimit = 10;
private $exchangeOrdersRateLimit = 10;
private $exchangeOrdersDailyLimit = 10;
private $requestsQueue = array();
private $ordersQueue = array();
private $ordersDayQueue = array();
public function __construct($api)
{
$this->api = $api;
$this->weights = array(
'account' => 5,
'addToTransfered' => 0,
'aggTrades' => 1,
'balances' => 1,
'bookPrices' => 1,
'buy' => 1,
'buyTest' => 1,
'cancel' => 1,
'candlesticks' => 1,
'chart' => 0,
'cumulative' => 0,
'depositAddress' => 1,
'depositHistory' => 1,
'assetDetail' => 1,
'depth' => 1,
'depthCache' => 1,
'displayDepth' => 1,
'exchangeInfo' => 1,
'first' => 0,
'getProxyUriString' => 0,
'getRequestCount' => 0,
'getTransfered' => 0,
'highstock' => 1,
'history' => 5,
'keepAlive' => 0,
'kline' => 1,
'last' => 0,
'marketBuy' => 1,
'marketBuyTest' => 1,
'marketSell' => 1,
'marketSellTest' => 1,
'miniTicker' => 1,
'openOrders' => 2,
'order' => 1,
'orders' => 5,
'orderStatus' => 1,
'prevDay' => 2,
'prices' => 1,
'report' => 0,
'sell' => 1,
'sellTest' => 1,
'setProxy' => 0,
'sortDepth' => 1,
'terminate' => 0,
'ticker' => 1,
'time' => 1,
'trades' => 5,
'userData' => 1,
'useServerTime' => 1,
'withdraw' => 1,
'withdrawFee' => 1,
'withdrawHistory' => 1,
);
$this->ordersfunctions = array(
'buy',
'buyTest',
'cancel',
'history',
'marketBuy',
'marketBuyTest',
'marketSell',
'marketSellTest',
'openOrders',
'order',
'orders',
'orderStatus',
'sell',
'sellTest',
'trades',
);
$this->init();
}
private function init()
{
$exchangeLimits = $this->api->exchangeInfo()['rateLimits'];
if (is_array($exchangeLimits) === false) {
print "Problem getting exchange limits\n";
return;
}
foreach ($exchangeLimits as $exchangeLimit) {
switch ($exchangeLimit['rateLimitType']) {
case "REQUESTS":
$this->exchangeRequestsRateLimit = round($exchangeLimit['limit'] * 0.95);
break;
case "ORDERS":
if ($exchangeLimit['interval'] === "SECOND") {
$this->exchangeOrdersRateLimit = round($exchangeLimit['limit'] * 0.9);
}
if ($exchangeLimit['interval'] === "DAY") {
$this->exchangeOrdersDailyLimit = round($exchangeLimit['limit'] * 0.98);
}
break;
}
}
}
/**
* magic get for private and protected members
*
* @param $file string the name of the property to return
* @return null
*/
public function __get(string $member)
{
return $this->api->$member;
}
/**
* magic set for private 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->api->$member = $value;
}
private function requestsPerMinute()
{
// requests per minute restrictions
if (count($this->requestsQueue) === 0) {
return;
}
while (count($this->requestsQueue) > $this->exchangeOrdersDailyLimit) {
$oldest = isset($this->requestsQueue[0]) ? $this->requestsQueue[0] : time();
while ($oldest < time() - 60) {
array_shift($this->requestsQueue);
$oldest = isset($this->requestsQueue[0]) ? $this->requestsQueue[0] : time();
}
print "Rate limiting in effect for requests " . PHP_EOL;
sleep(1);
}
}
private function ordersPerSecond()
{
// orders per second restrictions
if (count($this->ordersQueue) === 0) {
return;
}
while (count($this->ordersQueue) > $this->exchangeOrdersRateLimit) {
$oldest = isset($this->ordersQueue[0]) ? $this->ordersQueue[0] : time();
while ($oldest < time() - 1) {
array_shift($this->ordersQueue);
$oldest = isset($this->ordersQueue[0]) ? $this->ordersQueue[0] : time();
}
print "Rate limiting in effect for orders " . PHP_EOL;
sleep(1);
}
}
private function ordersPerDay()
{
// orders per day restrictions
if (count($this->ordersDayQueue) === 0) {
return;
}
$yesterday = time() - (24 * 60 * 60);
while (count($this->ordersDayQueue) > round($this->exchangeOrdersDailyLimit * 0.8)) {
$oldest = isset($this->ordersDayQueue[0]) ? $this->ordersDayQueue[0] : time();
while ($oldest < $yesterday) {
array_shift($this->ordersDayQueue);
$oldest = isset($this->ordersDayQueue[0]) ? $this->ordersDayQueue[0] : time();
}
print "Rate limiting in effect for daily order limits " . PHP_EOL;
$remainingRequests = round($this->exchangeOrdersDailyLimit * 0.2);
$remainingSeconds = $this->ordersDayQueue[0] - $yesterday;
$sleepTime = ($remainingSeconds > $remainingRequests) ? round($remainingSeconds / $remainingRequests) : 1;
sleep($sleepTime);
}
}
/**
* magic call to redirect cal to the API, caputinrg and monitoring the weight limit
*
* @param $name the function to call
* @param $arguments the paramters to the function
*/
public function __call(string $name, array $arguments)
{
$weight = $this->weights[$name] ?? false;
if ($weight && $weight > 0) {
$this->requestsPerMinute();
if (in_array($name, $this->ordersfunctions) === true) {
$this->ordersPerSecond();
$this->ordersPerDay();
}
$c_time = time();
for ($w = 0; $w < $weight; $w++) {
$this->requestsQueue[] = $c_time;
}
if (in_array($name, $this->ordersfunctions) === true) {
for ($w = 0; $w < $weight; $w++) {
$this->ordersQueue[] = $c_time;
$this->ordersDayQueue[] = $c_time;
}
}
}
return call_user_func_array(array(&$this->api, $name), $arguments);
}
}