As with any data service you will need to deal with some kind of fee and/or rate-limiting to retrieve real-time data. Generally there are different approaches:
APIs: e.g. CoinGecko or CoinMarketCap
DEX-APIs: e.g. Radium, Serum, or Orca
Solana-focused APIs: e.g. Solscan or Solana Beach
Wallets/DEXs: view prices directly in wallets like Phantom or on DEXs
An example bash script performing this task with ratelimiting and only sending changes to an own API:
#!/usr/bin/env bash
# poll an API and post updates to own service only on changes
pricecheck() {
declare -r log="pricecheck $1 ${2^^}:" currency="${2:-usd}"
declare -r url="https://api.coingecko.com/api/v3/simple/price?ids=$1&vs_currencies=$currency"
declare -i max_attempt=5 attempt_delay_sec=12 attempt=0
declare -gx pricecheck_previous=0 pricecheck=0
local res http_code content
local -r apiKeyHeader="x-cg-pro-api-key" apiKey="" # pay for key
local post_url="" # where to post data if price changed
local req=( "curl --silent --insecure --location --user-agent 'Mozilla/5.0'"
"-H accept:application/json -w %{http_code}"
"--url $url" )
[ "$apiKey" ] && req+="-H \"$apiKeyHeader: $apiKey\""
while [ $attempt -lt $max_attempt ]; do
res=$( ${req[*]} ) || { >&2 echo -e "\033[31m$log Error #$?\033[0m"; return 1; }
http_code="${res: -3}" && content="${res:0:${#res}-3}"
if [ "$http_code" -eq 200 ]; then
pricecheck="${content##*"$currency\":"}" && pricecheck="${pricecheck%%\}*}"
if [ "$pricecheck_previous" != "$pricecheck" ]; then
>&2 echo -e "\033[33m$log changed from $pricecheck_previous to $pricecheck \033[0m"
pricecheck_previous="$pricecheck"
echo "$pricecheck"
[ "$post_url" ] && curl -sk --json "$content" "$post_url"
else
>&2 echo -e "\033[32m$log no change\033[0m"
fi
attempt=1 && sleep $attempt_delay_sec
elif [ "$http_code" -eq 429 ]; then
attempt=$(( ++attempt ))
echo "$log rate limited (status $http_code). Retrying in $attempt_delay_sec seconds..."
sleep $attempt_delay_sec
else
printf "%s" "$log $http_code $url\n $content" && return 2
fi
done
echo "$log: too many retries" && return 3
}
pricecheck solana usd || echo failed with statuscode $?