Hello I try get value from bitfinex JSON. I need break script ever 90 queries, because in the documencation bitfinex API are informations link:
If an IP address exceeds 90 requests per minute to the REST APIs, the requesting IP address will be blocked for 10-60 seconds
<?php
$json = file_get_contents('https://api.bitfinex.com/v1/symbols');
$bitfinex = json_decode($json, true);
$insertBitfinex = $this->code = $this->conn->prepare("INSERT INTO exchange_bitfinex (`first_coin`,`second_coin`,`price`,`volume`,`volume_24`,`time`) VALUES (?,?,?,?,?,?)");
for ($j = 0; $j < count($bitfinex); $j++) {
if($j % 90 == 0 && $j > 0) {
sleep(60);
}
$symbol = $bitfinex[$j];
$json_2 = file_get_contents("https://api.bitfinex.com/v1/pubticker/" . $symbol);
$bitfinex_2 = json_decode($json_2, true);
$first_coin = mb_substr($symbol, 0, 3);
$second_coin = mb_substr($symbol, 3, 6);
$price = $bitfinex_2["last_price"];
$volume_24 = $bitfinex_2["volume"];
$volume = null;
$insertBitfinex = $this->code->bind_param('ssssss', $first_coin, $second_coin, $price, $volume, $volume_24, $time);
$insertBitfinex = $this->code->execute();
$insertBitfinex = $this->code->store_result();
}
My script is not executed correctly because it does not stop after 90 queries. I do not know if I am correctly trying to solve the problem using modulus %
The inner loop does not use the modulo operator right. Even if it would execute more than the 90 times of the outer loop.
But besides that here is the problem with the inner loop.
if($i % $limit_query != 0 && $i != $limit_query) {
When the loop counter is for example 1 the modulo operator returns also one (wich is not zero) because the rest from 1 / 90 is one. So it would do sleep on every cycle where $i cannot be evenly divided by 90.
The better approach would be.
if($i % $limit_query == 0 && $i > 0) {
This would wait on every cycle that is evenly divisible by 90 but skip the first one.
An alternative approach would be to the api call 90 times and then wait 60 seconds and repeat.
while(true) {
//execute the loop for 90 times
for($i=0; $i < 90; $i++) {
//do something
}
//wait for 60 seconds to not exceed api limit
sleep(60);
}
Or if you have to use modulo.
$some_big_limit = 10000;
for($i = 0; $i < $some_big_limit; $i++) {
if($i % 90 == 0 && $i > 0) {
//wait for 60 seconds, when the loop counter is evenly divisible by 90
sleep(60);
}
//do something
}