I'm trying to access to the sum of the last buy and sell orders for all the coins on Cryptopia using the official API.
First of all here is the link to the API: https://www.cryptopia.co.nz/Forum/Thread/255
When I make a request for a single coin, everything works just fine.
$coin = 100;
$url = "https://www.cryptopia.co.nz/api/GetMarketHistory/". $coin . "/" . 1;
$curl_dscr = curl_init($url);
curl_setopt($curl_dscr, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl_dscr, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_dscr, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl_dscr, CURLOPT_SSLVERSION, 'CURL_SSLVERSION_SSLv3');
curl_setopt($curl_dscr, CURLOPT_FOLLOWLOCATION, 1);
$data = json_decode(curl_exec($curl_dscr), 1);
if (empty($data['Data'])) exit;
$sell_total = 0;
$buy_total = 0;
foreach ($data['Data'] as $pair) {
list($market) = explode('_', $pair['Label']);
if ($pair['Type'] == 'Sell')
$sell_total += $pair['Total'];
elseif ($pair['Type'] == 'Buy') {
$buy_total += $pair['Total'];
}
}
echo $sell_total;
echo $buy_total;
echo $url;
However, when I create an array of coins and run the script on Terminal, the script outputs nothing. I don't even get an error. Here is the code.
$coins = array(1261,5313);
foreach ($coins as $coin) {
$url = "https://www.cryptopia.co.nz/api/GetMarketHistory/" . $coin . "/" . 1;
$curl_dscr = curl_init($url);
curl_setopt($curl_dscr, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl_dscr, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_dscr, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl_dscr, CURLOPT_SSLVERSION, 'CURL_SSLVERSION_SSLv3');
curl_setopt($curl_dscr, CURLOPT_FOLLOWLOCATION, 1);
$data = json_decode(curl_exec($curl_dscr), 1);
if (empty($data['Data'])) exit;
$sell_total = 0;
$buy_total = 0;
foreach ($data['Data'] as $pair) {
list($market) = explode('_', $pair['Label']);
if ($pair['Type'] == 'Sell')
$sell_total += $pair['Total'];
elseif ($pair['Type'] == 'Buy') {
$buy_total += $pair['Total'];
}
}
echo $sell_total;
echo $buy_total;
echo $url;
unset($coin);
}
Can you explain how you are testing your code, i just run it and it worked, it display:
0.000635710.00052873https://www.cryptopia.co.nz/api/GetMarketHistory/1261/1
Related
I am trying to skip when InnerText is empty but it put a default value.
This is my code:
if (strip_tags($result[$c]->innertext) == '') {
$c++;
continue;
}
This is the output:
Thanks
EDIT2: I did the var_dump
var_dump($result[$c]->innertext)
and I got this:
how can I fix it please?
EDIT3: This is my code; I extract in this way the names of the teams and the results, but the last one not works in the best way when We have postponed matches
<?php
include('../simple_html_dom.php');
function getHTML($url,$timeout)
{
$ch = curl_init($url); // initialize curl with given url
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]); // set useragent
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // write the response to a variable
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects if any
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // max. seconds to execute
curl_setopt($ch, CURLOPT_FAILONERROR, 1); // stop when it encounters an error
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
return #curl_exec($ch);
}
$response=getHTML("https://www.betexplorer.com/soccer/japan/j3-league/results/",10);
$html = str_get_html($response);
$titles = $html->find("a[class=in-match]"); // name match
$result = $html->find("td[class=h-text-center]/a"); // result match
$c=0; $b=0; $o=0; $z=0; $h=0; // set counters
foreach ($titles as $match) { //get all data
$match_status = $result[$h++];
if (strip_tags($result[$c]->innertext) == 'POSTP.') { //bypass postponed match but it doesn't work anymore
$c++;
continue;
}
list($num1, $num2) = explode(':', $result[$c++]->innertext); // <- explode
$num1 = intval($num1);
$num2 = intval($num2);
$num3 = ($num1 + $num2);
$risultato = ($num1 . '-' . $num2);
list($home, $away) = explode(' - ', $titles[$z++]->innertext); // <- explode
$home = strip_tags($home);
$away = strip_tags($away);
$matchunit = $home . ' - ' . $away;
echo "<tr><td class='rtitle'>".
"<td> ".$matchunit. "</td> / " . // name match
"<td class='first-cell'>" . $risultato . "</td> " .
"</td></tr><br/>";
} //close foreach
?>
By browsing the content of the website you will always be dependent on the changes made in the future.
However, I will use PHP's native libxml DOM extension.
By doing the following:
<?php
function getHTML($url,$timeout)
{
$ch = curl_init($url); // initialize curl with given url
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]); // set useragent
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // write the response to a variable
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects if any
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // max. seconds to execute
curl_setopt($ch, CURLOPT_FAILONERROR, 1); // stop when it encounters an error
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
return #curl_exec($ch);
}
$response=getHTML("https://www.betexplorer.com/soccer/japan/j3-league/results/",10);
// "Create" the new DOM document
$doc = new DomDocument();
// Load HTML from a string, and disable xml error handling
$doc->loadHTML($response, LIBXML_NOERROR);
// Creates a new DOMXPath object
$xpath = new DomXpath($doc);
// Evaluates the given XPath expression and get all tr's without first line from table main
$row = $xpath->query('//table[#class="table-main js-tablebanner-t js-tablebanner-ntb"]/tr[position()>1]');
echo '<table>';
// Parse the values in row
foreach ($row as $tr) {
// Only get 2 first td's
$col = $xpath->query('td[position()<3]', $tr);
// Do not show POSTP and Round values
if (!str_contains($tr->nodeValue, 'POSTP') && !str_contains($tr->nodeValue, 'Round')) {
echo '<tr><td>'.$col->item(0)->nodeValue.'</td><td>'.$col->item(1)->nodeValue.'</td></tr>';
}
}
echo '</table>';
You obtain:
<tr><td>Nagano - Tegevajaro Miyazaki</td><td>3:2</td></tr>
<tr><td>YSCC - Toyama</td><td>1:2</td></tr>
...
I am calling the Binance Klines API to get current prices.
// Get Assets - ideally I'd just like the currency name (e.g. ETH) rather ETC/BTC
$url = 'https://api.binance.com/api/v3/exchangeInfo';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$result = curl_exec($ch);
curl_close($ch);
$json = json_decode($result);
foreach($json->symbols as $symbol)
{
// Get prices for teh asset
$ccode = $symbol->symbol;
$nurl = 'https://api.binance.com/api/v3/klines?symbol=' . $ccode . '&interval=1m';
$stime = 1000*(time() - 60); // Time period is the last minute
$etime = 1000*time();
$nurl .= '&startTime=' . $stime;
$nurl .= '&endTime=' . $etime;
$ch = curl_init($nurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $nurl);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$json = curl_exec($ch);
curl_close($ch);
if ( $json === "" || $json === "[]" || substr($json, 0, 8) == '{"code":' )
{
echo "Not found " . $ccode . " .. skipping <BR>";
continue;
}
$arr = explode(",", $json);
$price = $arr[4];
$tstamp1 = $arr[6];
$tstamp = gmdate("Y-m-d\TH:i:s\Z", ($arr[6]/1000));
echo $ccode . " " . $tstamp . " " . $price . "<BR>";
}
The problem is I get all combinations of coin/currency, when I only want the GBP prices for each coin. The full list about times out as it runs for over 5 minutes.
I'd like to just get the price of each coin in GBP.
How can I do that?
You're asking for all the symbols (exchangeInfo) and then getting the candle info (klines) for each symbol (= currency pair).
You can do so just for the GBP pairs by looking for GBP in the two currencies you're currently iterating on, by adding this to your foreach:
// rest of the code
foreach($json->symbols as $symbol)
{
if ($symbol->baseAsset === "GBP" || $symbol->quoteAsset === "GBP" ) {
// rest of your foreach
}
}
In your foreach you have these three properties under $symbol you can leverage:
$symbol->symbol // "ADAGBP"
$symbol->baseAsset // "ADA"
$symbol->quoteAsset // "GBP"
I need to parse JSON from multiple URLs. Here is the way that I'm following:
<?php
//call
$url1 = file_get_contents("https://www.url1.com");
$url2 = file_get_contents("https://www.url2.com");
$url3 = file_get_contents("https://www.url3.com");
$url4 = file_get_contents("https://www.url4.com");
$url5 = file_get_contents("https://www.url5.com");
//parse
$decode1 = json_decode($url1, true);
$decode2 = json_decode($url2, true);
$decode3 = json_decode($url3, true);
$decode4 = json_decode($url4, true);
$decode5 = json_decode($url5, true);
//echo
if (is_array($decode1)) {
foreach ($decode1 as $key => $value) {
if (is_array($value) && isset($value['price'])) {
$price = $value['price'];
echo '<span><b>' . $price . '</b><span>';
}
}
}
?>
This way causes slowness in the page openings. On the other hand, I get these errors:
Warning: file_get_contents(https://www.url1.com): failed to open
stream: Redirection limit reached, aborting in
/home/directory/public_html/file.php on line 12
Warning: file_get_contents(https://www.url2.com): failed to open
stream: Redirection limit reached, aborting in
/home/directory/public_html/file.php on line 13
etc.
How can I fix the redirection limit reached warning?
I would suggest using cURL for fetching remote data. You could do this:
$urls = [
"https://www.url1.com",
"https://www.url2.com",
"https://www.url3.com",
"https://www.url4.com",
"https://www.url5.com"
];
$decoded = array_map("loadJSON", $urls);
if (is_array($decoded[0])) {
foreach ($decoded[0] as $key => $value) {
if (is_array($value) && isset($value['price'])) {
$price = $value['price'];
echo '<span><b>' . $price . '</b><span>';
}
}
}
/**
* Downloads a JSON file from a URL and returns its decoded content
*/
function loadJSON($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // If your server does not have SSL
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // Follow redirections
curl_setopt($ch, CURLOPT_MAXREDIRS, 10); // 10 max redirections
$content = curl_exec($ch);
curl_close($ch);
$res = json_decode($content, true);
return $res;
}
i have a very weird issue with curl and url defined inside an array.
I have an array of url and i want perform an http GET on those urls with curl
for ($i = 0, $n = count($array_station) ; $i < $n ; $i++)
{
$station= curl_init();
curl_setopt($station, CURLOPT_VERBOSE, true);
curl_setopt($station, CURLOPT_URL, $array_station[$i]);
curl_setopt($station, CURLOPT_RETURNTRANSFER, true);
curl_setopt($station, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($station);
curl_close($station);
}
If i define my $array_station in the way below
$array_station=array("http://www.example.com","http://www.example2.com");
the code above with curl working flawlassy,but since my $array_station is build in the way below (i perform a scan of directory searchin a specific filename, then i clean the url), the curl does not work, no error showed and nothing happens..
$di = new RecursiveDirectoryIterator(__DIR__,RecursiveDirectoryIterator::SKIP_DOTS);
$it = new RecursiveIteratorIterator($di);
$array_station=array();
$i=0;
foreach($it as $file) {
if (pathinfo($file, PATHINFO_FILENAME ) == "db_insert") {
$string = str_replace('/web/htdocs/', 'http://', $file.PHP_EOL);
$string2 = str_replace('/home','', $string);
$array_station[$i]=$string2;
$i++;
}
}
Doyou have some ideas? i'm giving up :-(
I'm on mobile right now so i cannot test it, but why are you adding a new line (PHP_EOL) to the url? Try to remove the new line or trim() the url at the end.
Add the lines of code below.
If there is a curl error it will report the error number.
If the request is made, it will show the HTTP request and response headers. The request is in $info and response header is in $head
for ($i = 0, $n = count($array_station) ; $i < $n ; $i++)
{
$station= curl_init();
curl_setopt($station, CURLOPT_VERBOSE, true);
curl_setopt($station, CURLOPT_URL, $array_station[$i]);
curl_setopt($station, CURLOPT_RETURNTRANSFER, true);
curl_setopt($station, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$response = curl_exec($station);
if (curl_errno($station)){
$response .= 'Retreive Base Page Error: ' . curl_error($station);
}
else {
$skip = intval(curl_getinfo($station, CURLINFO_HEADER_SIZE));
$head = substr($response ,0,$skip);
$response = substr($response ,$skip);
$info = var_export(curl_getinfo($station),true);
}
echo $head;
echo $info;
curl_close($station);
}
i am totaly new to CURL thing . i have a problem .
i have the below script which supposed to get remote files using a proxy , i am trying this code on my local host machine and it is working great "done successfully part: .
when i run it from server , it just keep going to the "invalid proxy" although it is same proxy as used in the local host ..
<?php
$dots = '';
include($dots.'classes/config.php');
$wordsLimitPerCall = 1;
$maxAttemptsTrials = 3;
$timeout = 10; // Seconds
$proxy = sqlSelectRow('proxy', array(
'condition'=>'not_valid=0',
'order'=>'rand()'
));
echo '<ul>';
if($proxy)
echo '<li>Using proxy: '.$proxy['proxy'].':'.$proxy['port'].'</li>';
$wordsRes = sqlSelectRows('words', array(
'condition'=>'is_done=0 and trials<'.$maxAttemptsTrials,
'limit'=>$wordsLimitPerCall,
'order'=>'created asc'
));
while($arr = $wordsRes->fetch_assoc()) {
$word = urlencode($arr['word']);
$url = 'http://example.com'.$word;
$callSettings = array(
'method'=>'curl',
'timeout'=>$timeout
);
if($proxy)
$callSettings['proxy'] = $proxy['proxy'].':'.$proxy['port'];
$result = callRemoteURL($url, $callSettings);
$filename = urldecode($word);
$filename = 'file/'.$arr['id'].' - '.$filename.'.mp3';
echo '<li>Getting the word: '.$word.'</li>';
if($result && strpos($result, '<html')===false) {
if(file_exists($dots.$filename))
unlink($dots.$filename);
fileWrite($filename, $result);
$is_done = 1;
echo '<li>done successfully</li>';
}
else {
$is_done = 0;
if($proxy) {
sqlUpdate('proxy', array(
'not_valid'=>0
), array(
'condition'=>'id='.$proxy['id']
));
echo '<li>Proxy is not valid</li>';
}
}
sqlUpdate('words', array(
'trials'=>$arr['trials']+1,
'path'=>$url,
'last_call_date'=>date('Y-m-d H:i:s'),
'is_done'=>$is_done
), array(
'condition'=>'id='.$arr['id']
));
}
echo '</ul>'; ?>
below the function called from utils
<? php
if($set['method']=='curl' && extension_loaded('curl'))
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, $set['timeout']); // Seconds
if($set['proxy'])
curl_setopt($ch, CURLOPT_PROXY, $set['proxy']);
ob_start();
if(curl_exec($ch) === false)
{
$errorNo = curl_errno($ch);
if($errorNo==28)
print_r('The connection took time more than '. $set['timeout'].' seconds, so we disconnected the process');
else
if($errorNo!=7)
print_r(curl_error($ch));
$result=false;
}
else
{
$result = ob_get_contents();
}
ob_end_clean();
return $result;
}
?>
sorry if its too long ... but i've spent the last couple days tryng to find out . any idea or what shall i do ?