Binance API - Get Klines for XXX/GBP only - php

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"

Related

how to skip InnerText empy in a If statment using php

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>
...

PHP cURL add pagination using foreach loop

I am using the attached script to output 100 results at a time from an XML file. The total record count e.g 1000 is held in $totalRecordCount = $oXML['total_record_count']; The user enters a search term in a form and results get outputted on same page. Each result is a link to a detail page. How do I integrate pagination in it if there's a 1000 results 1|2|3...10? I tried integrating something as per Simple pagination for foreach loop with no success however. Any help appreciated. Thanks
<?php
if (isset($_GET['submit2'])) {
$search2 = preg_replace('/\s+/', '+', $_GET["dept-keywords"]);
$sanitizeSearch2 = filter_var($search2, FILTER_SANITIZE_STRING);
echo '<b>Results: ' . $_GET["dept-keywords"] . '</b>';
$ch = curl_init();
$baseUrl = 'https://example.com/';
$templateParamNames = array('{user_id}');
$templateParamValues = array(urlencode('exl_impl'));
$baseUrl = str_replace($templateParamNames, $templateParamValues, $baseUrl);
$queryParams = array(
//info
);
$url = $baseUrl . "?" . http_build_query($queryParams);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
$oXML = new SimpleXMLElement($response);
echo '<ol>';
$totalRecordCount = $oXML['total_record_count'];
$count = 0;
foreach ($oXML->user as $user) {
$first_name = $user->first_name;
$user_link = strtolower("https://example.com/" . $first_name);
echo '<li>';
echo "<a href='" . $user_link . "'> " . $first_name . " </a>" . "\r\n";
echo '</li>';
$count++;
}
if ($count == 0) {
echo '<label>Sorry, no results!</label>';
}
echo '</ol>';
curl_close($ch);
}

cant read data from epever to raspberry

I'm using Raspberry-pi to read data from epever by rs485 to usb.I'm using this PHP file to read data.
<?php
/*
* PHP EpSolar Tracer Class (PhpEpsolarTracer) v0.9
*
*/
//EPEver tracer php library
require_once 'PhpEpsolarTracer.php';
//influxDB php client library
require 'vendor/autoload.php';
//Define IP of influxDB
$host = 'localhost';
$tracer = new PhpEpsolarTracer('/dev/ttyUSBACM0');
$client = new InfluxDB\Client($host,8086,"root","root");
$db = $client->selectDB("logger");
//'http://localhost:8086/write?db=mydb' --data-binary 'cpu_load_short,host=server01,region=us-west value=0.64 1434055562000000000'
Print "\n Realtime Data\n";
if ($tracer->getRealtimeData()) {
for ($i = 0; $i < count($tracer->realtimeData); $i++) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost:8086/write?db=powerwall" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$Item = $tracer->realtimeData[$i];
$Key_Name = str_replace(" ","-",$tracer->realtimeKey[$i]);
Print str_pad($i, 2, '0', STR_PAD_LEFT) . " " . $Key_Name . " " . $Item . "\n";
curl_setopt($ch, CURLOPT_POSTFIELDS, "$Key_Name,unit=Realtime value=$Item" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result = curl_exec ($ch);
}
} else
print "Cannot get RealTime Data\n";
Print "\n Statistical Data\n";
if ($tracer->getStatData()) {
for ($i = 0; $i < count($tracer->statData); $i++) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost:8086/write?db=powerwall" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$Item = $tracer->statData[$i];
$Key_Name = str_replace(" ","-",$tracer->statKey[$i]);
$Key_Name = 'Stat-' . $Key_Name;
Print str_pad($i, 2, '0', STR_PAD_LEFT) . " " . $Key_Name . " " . $Item . "\n";
curl_setopt($ch, CURLOPT_POSTFIELDS, "$Key_Name,unit=statData value=$Item" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result = curl_exec ($ch);
}
} else
print "Cannot get Statistical Data\n";
?>
When I run this code I got the error message:
Cannot get Real Time Data
So then I followed the issue in here:
Modbus cant read data from epever tracer 1210a to raspberry
But I haven't do this, I got several errors.
Then I have checked the kernel version of my raspberry pi and it shows as
Linux raspberry pi 4.19.57-v7+ #1244 SMP Thu Jul 4 18:45:25 BST 2019 armv7l GNU/Linux

Accessing the Trade History via Cryptopia API using PHP

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

Response On Process Complete

<?php
$mysender2= "";
$myrecepient2= "923336088811,923126812536,923134126153";
$mymessage2 = "this is message";
$api_key = "****";
$api_secret="****";
$to_arr = explode(",", $myrecepient2);
foreach ($to_arr as $b){
$url = "https://rest.nexmo.com/sms/json?" .
"api_key=".$api_key. "&" .
"api_secret=" .$api_secret . "&" .
"from=" . urlencode($mysender2) . "&" .
"to=" . urlencode($b) . "&" .
"text=" .urlencode($mymessage2);
$c = curl_init($url);
// Use SSL
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($c, CURLOPT_RETURNTRANSFER, TRUE);
$html = curl_exec($c);
curl_close ($c);
}
?>
The above script will run again and again untill the process completed . how to show an echo on process complete .. such as "Your Process Completed"
Sorry, but, your script is so bad and your server goes cry, I know that exists 3 calls only, because your array have 3 values, but if you need more? You will have problems.
The best way in your case is a php header refresh with offset, see bellow:
$offset = isset( $_GET['offset'] ) ? $_GET['offset'] : 0;
$mysender2= "";
$myrecepient2= "923336088811,923126812536,923134126153";
$mymessage2 = "this is message";
$api_key = "****";
$api_secret="****";
$to_arr = explode( ",", $myrecepient2 );
if( $offset > count( $to_arr ) )
{
echo 'Completed!';
}
else
{
$b = $to_arr[ $offset ];
$url = "https://rest.nexmo.com/sms/json?" .
"api_key=".$api_key. "&" .
"api_secret=" .$api_secret . "&" .
"from=" . urlencode($mysender2) . "&" .
"to=" . urlencode($b) . "&" .
"text=" .urlencode($mymessage2);
$c = curl_init($url);
// Use SSL
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($c, CURLOPT_RETURNTRANSFER, TRUE);
$html = curl_exec($c);
curl_close ($c);
header('Refresh: 0.5; url=YOUR-URL?offset=' . $offset + 1 );
// half a second
}

Categories