Code for Top 100 Cryptos

This revision is from 2024/12/19 21:53. You can Restore it.

<?php

// Set error reporting level to capture all errors, notices, and warnings

error_reporting(E_ALL);

ini_set('display_errors', 1);

set_time_limit(180);

// Blacklist of base assets to exclude

$stablecoins = ['USDT', 'USDC', 'BUSD', 'DAI', 'TUSD', 'UST', 'GUSD', 'PAX', 'EURS', 'FDUSD', 'SUSD', 'LUNC', 'LUNA', 'LUNA2', 'FTT', 'NOT', 'RDNT', 'GFT', 'IRIS', 'KEY', 'OAX', 'REN', 'DAR', 'RARE', 'THETA', 'UTK', 'COS', 'FXS', 'KP3R', 'OOKI', 'UNFI', 'IDRT', 'EUR'];

$directory = '/path/';

// Minimum criteria

$min_volume = 9000000; // Minimum 24h volume in USD

$min_age_days = 90; // Minimum age in days on Binance

$min_trades = 90000; // Minimum number of trades in 24 hours

$min_cmc_rank = 300; // Maximum CoinMarketCap rank allowed

$min_coingecko_rank = 300; //Maximum Coingeck rank allowed

function fetchData($url) {

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

curl_close($ch);

return json_decode($response, true);

}

function getFirstCandleTimestamp($symbol) {

$url = 'https://api.binance.com/api/v3/klines?symbol=' . $symbol . '&interval=1d&limit=1&startTime=0';

$data = fetchData($url);

if (!empty($data) && isset($data[0][0])) {

return $data[0][0];

}

return null;

}

function calculateAge($timestamp) {

if ($timestamp) {

$start = $timestamp / 1000;

$now = time();

$diff = $now - $start;

$days = floor($diff / (60 * 60 * 24));

return $days;

}

return 'N/A';

}

function formatNumber($num) {

if (is_numeric($num)) {

return number_format($num, 2, '.', ',');

} else {

return 'N/A';

}

}

// Function to get the rank of a cryptocurrency from the rank file

function getRankFromJson($symbol) {

$directory = '/path/';

$rankFile = $directory . 'top_500_ranks.json';

if (!file_exists($rankFile)) {

die("Rank file not found. Run generate_top_500_rankings.php to generate it.");

}

$rankData = json_decode(file_get_contents($rankFile), true);

if (json_last_error() !== JSON_ERROR_NONE) {

die('JSON decode error: ' . json_last_error_msg());

}

$symbol = strtoupper($symbol);

return isset($rankData[$symbol]) ? $rankData[$symbol] : 'N/A';

}

function getCoingeckoRankFromJson($symbol) {

$directory = '/path/';

$rankFile = $directory . 'top_500_ranks_coingecko.json';

if (!file_exists($rankFile)) {

die("Coingecko rank file not found.");

}

$rankData = json_decode(file_get_contents($rankFile), true);

if (json_last_error() !== JSON_ERROR_NONE) {

die('JSON decode error for CoinGecko ranks: ' . json_last_error_msg());

}

$symbol = strtoupper($symbol);

return isset($rankData[$symbol]) ? $rankData[$symbol] : 'N/A';

}

$exchangeInfoUrl = 'https://api.binance.com/api/v3/exchangeInfo';

$ticker24hrUrl = 'https://api.binance.com/api/v3/ticker/24hr';

$pricesUrl = 'https://api.binance.com/api/v3/ticker/price';

$exchangeInfo = fetchData($exchangeInfoUrl);

$ticker24hr = fetchData($ticker24hrUrl);

$prices = fetchData($pricesUrl);

$symbols = [];

if (isset($exchangeInfo['symbols']) && is_array($exchangeInfo['symbols'])) {

foreach ($exchangeInfo['symbols'] as $symbolData) {

$baseAsset = $symbolData['baseAsset'];

$quoteAsset = $symbolData['quoteAsset'];

if ($quoteAsset !== 'USDT' || in_array($baseAsset, $stablecoins)) {

continue;

}

$symbol = $symbolData['symbol'];

$symbols[$symbol] = [

'baseAsset' => $baseAsset,

'quoteAsset' => $quoteAsset,

'status' => $symbolData['status'],

'minOrderQty' => 'N/A',

];

foreach ($symbolData['filters'] as $filter) {

if ($filter['filterType'] === 'LOT_SIZE' && isset($filter['minQty'])) {

$symbols[$symbol]['minOrderQty'] = $filter['minQty'];

break;

}

}

}

}

$ticker24hrMap = [];

if (is_array($ticker24hr)) {

foreach ($ticker24hr as $tick) {

$ticker24hrMap[$tick['symbol']] = [

'volume' => isset($tick['volume']) ? $tick['volume'] : 'N/A',

'priceChangePercent' => isset($tick['priceChangePercent']) ? $tick['priceChangePercent'] : 'N/A',

'numTrades' => isset($tick['count']) ? $tick['count'] : 0,

'lastPrice' => isset($tick['lastPrice']) ? $tick['lastPrice'] : 'N/A',

'quoteVolume' => isset($tick['quoteVolume']) ? $tick['quoteVolume'] : 'N/A',

];

}

}

$pricesMap = [];

if (is_array($prices)) {

foreach ($prices as $price) {

$pricesMap[$price['symbol']] = $price['price'];

}

}

$combinedData = [];

foreach ($symbols as $symbol => $symbolData) {

if (isset($ticker24hrMap[$symbol])) {

$ticker = $ticker24hrMap[$symbol];

$combinedData[$symbol] = array_merge(['symbol' => $symbol], $symbolData, $ticker);

$combinedData[$symbol]['lastPrice'] = isset($pricesMap[$symbol]) ? $pricesMap[$symbol] : 'N/A';

if (is_numeric($combinedData[$symbol]['volume']) && is_numeric($combinedData[$symbol]['lastPrice']) && $combinedData[$symbol]['lastPrice'] != 'N/A') {

$volumeInUsd = $combinedData[$symbol]['volume'] * $combinedData[$symbol]['lastPrice'];

} else {

$volumeInUsd = 'N/A';

}

$combinedData[$symbol]['volumeInUsd'] = $volumeInUsd;

} else {

continue;

}

}

$filteredData = [];

foreach ($combinedData as $symbol => $data) {

if (

$data['volume'] > 0 &&

$data['status'] === 'TRADING' &&

$data['volumeInUsd'] >= $min_volume &&

isset($data['numTrades']) &&

is_numeric($data['numTrades']) &&

$data['numTrades'] >= $min_trades

) {

$filteredData[] = $data;

}

}

foreach ($filteredData as $key => $data) {

$symbol = $data['symbol'];

$timestamp = getFirstCandleTimestamp($symbol);

$age = calculateAge($timestamp);

$filteredData[$key]['ageInDays'] = $age;

// Add CoinMarketCap rank from the JSON file

$baseAsset = strtoupper($data['baseAsset']);

$filteredData[$key]['coinmarketcap_rank'] = getRankFromJson($baseAsset);

// Add CoinGecko rank from the JSON file

$filteredData[$key]['coingecko_rank'] = getCoingeckoRankFromJson($baseAsset);

usleep(200000);

}

usort($filteredData, function ($a, $b) {

return $b['volumeInUsd'] <=> $a['volumeInUsd'];

});

$filteredData = array_slice($filteredData, 0, 150, true);

echo '<table border="1">';

echo '<tr>';

echo '<th>Rank</th>';

echo '<th>Symbol</th>';

echo '<th>Base Asset</th>';

echo '<th>Quote Asset</th>';

echo '<th>Status</th>';

echo '<th>24-hour Volume (USD)</th>';

echo '<th>Last Price</th>';

echo '<th>Price Change Percentage</th>';

echo '<th>Number of Trades (24h)</th>';

echo '<th>Age (Days)</th>';

echo '<th>Minimum Order Quantity</th>';

echo '<th>CoinMarketCap Rank</th>';

echo '<th>Coingecko Rank</th>'; // Added new header

echo '</tr>';

$rank = 1;

foreach ($filteredData as $data) {

// Check all criteria: age, CoinMarketCap rank, Coingecko rank, and other conditions

if (

$data['ageInDays'] >= $min_age_days &&

isset($data['coinmarketcap_rank']) &&

is_numeric($data['coinmarketcap_rank']) &&

$data['coinmarketcap_rank'] <= $min_cmc_rank &&

isset($data['coingecko_rank']) &&

is_numeric($data['coingecko_rank']) &&

$data['coingecko_rank'] <= $min_coingecko_rank

) {

echo '<tr>';

echo '<td>' . $rank . '</td>';

$rank++;

echo '<td>' . $data['symbol'] . '</td>';

echo '<td>' . $data['baseAsset'] . '</td>';

echo '<td>' . $data['quoteAsset'] . '</td>';

echo '<td>' . $data['status'] . '</td>';

echo '<td>' . formatNumber($data['volumeInUsd']) . '</td>';

echo '<td>' . $data['lastPrice'] . '</td>';

echo '<td>' . $data['priceChangePercent'] . '%</td>';

echo '<td>' . number_format($data['numTrades']) . '</td>';

echo '<td>' . $data['ageInDays'] . '</td>';

echo '<td>' . $data['minOrderQty'] . '</td>';

echo '<td>' . $data['coinmarketcap_rank'] . '</td>';

echo '<td>' . $data['coingecko_rank'] . '</td>'; // Added new data field

echo '</tr>';

}

}

echo '</table>';

$pairlist = [];

$pairlist_f = [];

foreach ($filteredData as $data) {

if (

$data['ageInDays'] >= $min_age_days &&

isset($data['coinmarketcap_rank']) &&

is_numeric($data['coinmarketcap_rank']) &&

$data['coinmarketcap_rank'] <= $min_cmc_rank &&

isset($data['coingecko_rank']) &&

is_numeric($data['coingecko_rank']) &&

$data['coingecko_rank'] <= $min_coingecko_rank

) {

$pair = $data['baseAsset'] . '/' . $data['quoteAsset'];

$pair_f = $pair . ':' . $data['quoteAsset'];

$pairlist[] = $pair;

$pairlist_f[] = $pair_f;

}

}

// Ensure the directory path ends with a slash

if (substr($directory, -1) !== '/') {

$directory .= '/';

}

// Define file names

$pairlistFile = $directory . 'pairlist.json';

$pairlistFFile = $directory . 'pairlist_f.json';

// Check if files exist and get their original permissions

$originalPermissions1 = file_exists($pairlistFile) ? fileperms($pairlistFile) : null;

$originalPermissions2 = file_exists($pairlistFFile) ? fileperms($pairlistFFile) : null;

// Change permissions of the files to 0777

$chmod1 = @chmod($pairlistFile, 0777);

$chmod2 = @chmod($pairlistFFile, 0777);

// Write content to the files

$result2 = file_put_contents($pairlistFile, json_encode(['pairs' => $pairlist], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));

$result3 = file_put_contents($pairlistFFile, json_encode(['pairs' => $pairlist_f], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));

// Restore original permissions

$chmodBack1 = $originalPermissions1 !== null ? @chmod($pairlistFile, $originalPermissions1) : true;

$chmodBack2 = $originalPermissions2 !== null ? @chmod($pairlistFFile, $originalPermissions2) : true;

// Check for success

if ($chmod1 && $chmod2 && $result2 !== false && $result3 !== false && $chmodBack1 && $chmodBack2) {

echo "Pair lists generated successfully.";

} else {

echo "Failed to generate pair lists or restore permissions.";

}

?>

<?php

// API Key (replace with your actual API key)

$api_key = "00000000000000000000000000";

// Set error reporting level to capture all errors, notices, and warnings

error_reporting(E_ALL);

ini_set('display_errors', 1);

// Configuration

define('CMC_API_KEY', $api_key); // Replace with your CoinMarketCap API key

// Function to fetch data from an API

function fetchData($url, $headers = []) {

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($ch);

if ($response === false) {

echo 'cURL error: ' . curl_error($ch) . '<br>';

curl_close($ch);

return null;

}

curl_close($ch);

$decoded = json_decode($response, true);

if (json_last_error() !== JSON_ERROR_NONE) {

echo 'JSON decode error: ' . json_last_error_msg() . '<br>';

return null;

}

return $decoded;

}

// Fetch CoinMarketCap rankings (top 500 coins)

$coinmarketcapUrl = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?limit=500';

$headers = [

'Accepts: application/json',

'X-CMC_PRO_API_KEY: ' . CMC_API_KEY

];

$coinmarketcapData = fetchData($coinmarketcapUrl, $headers);

if ($coinmarketcapData === null || !isset($coinmarketcapData['data'])) {

die('Failed to fetch CoinMarketCap data.');

}

// Create rank lookup array

$rankLookup = [];

foreach ($coinmarketcapData['data'] as $coin) {

if (isset($coin['symbol']) && isset($coin['cmc_rank'])) {

$rankLookup[strtoupper($coin['symbol'])] = $coin['cmc_rank']; // Map symbol to rank

}

}

// Save the rank lookup array to a file

$rankFile = 'top_500_ranks.json';

file_put_contents($rankFile, json_encode($rankLookup, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));

echo "Top 500 rankings saved to $rankFile successfully.";

?>

<?php

// API Key (replace with your actual API key)

$api_key = "000000000000000000000000000"; // Replace with your CoinGecko API key

// Set error reporting level to capture all errors, notices, and warnings

error_reporting(E_ALL);

ini_set('display_errors', 1);

// Function to fetch data from an API

function fetchData($url, $headers = []) {

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($ch);

if ($response === false) {

echo 'cURL error: ' . curl_error($ch) . '<br>';

curl_close($ch);

return null;

}

curl_close($ch);

$decoded = json_decode($response, true);

if (json_last_error() !== JSON_ERROR_NONE) {

echo 'JSON decode error: ' . json_last_error_msg() . '<br>';

return null;

}

return $decoded;

}

// Fetch CoinGecko rankings (top 500 coins)

$coingeckoUrlPage1 = 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&per_page=250&page=1&sparkline=false';

$coingeckoUrlPage2 = 'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&per_page=250&page=2&sparkline=false';

$headers = [

'Accept: application/json',

'x-cg-demo-api-key: ' . $api_key

];

// Fetch data for page 1

$coingeckoDataPage1 = fetchData($coingeckoUrlPage1, $headers);

if ($coingeckoDataPage1 === null || empty($coingeckoDataPage1)) {

die('Failed to fetch CoinGecko data for page 1.');

}

// Fetch data for page 2

$coingeckoDataPage2 = fetchData($coingeckoUrlPage2, $headers);

if ($coingeckoDataPage2 === null || empty($coingeckoDataPage2)) {

die('Failed to fetch CoinGecko data for page 2.');

}

// Combine the data from both pages

$coingeckoData = array_merge($coingeckoDataPage1, $coingeckoDataPage2);

// Create rank lookup array

$rankLookup = [];

foreach ($coingeckoData as $coin) {

if (isset($coin['symbol']) && isset($coin['market_cap_rank'])) {

$rankLookup[strtoupper($coin['symbol'])] = $coin['market_cap_rank']; // Map symbol to rank

}

}

// Save the rank lookup array to a file

$rankFile = 'top_500_ranks_coingecko.json';

file_put_contents($rankFile, json_encode($rankLookup, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));

echo "Top 500 rankings saved to $rankFile successfully.";

?>

  

📝 📜 ⏱️ ⬆️