Skip to content

Instantly share code, notes, and snippets.

@colindean
Created December 13, 2017 06:16
Show Gist options
  • Save colindean/9e8d79e439207c0f4c375e9365b4ccbb to your computer and use it in GitHub Desktop.
Save colindean/9e8d79e439207c0f4c375e9365b4ccbb to your computer and use it in GitHub Desktop.
ledger price database "getquote" tool for cryptocurrencies using coinmarketcap
#!/bin/bash
# by colindean
# unlicensed, public domain: https://unlicense.org
# invocation:
# getquote-coinmarketcap.sh crypto-transactions.ledger
#
# This tool may try to look up any commodity that is in the commodity list.
# I recommend tracking cryptocurrencies in a separate ledger file that is
# included from the main file used in querying.
LEDGER_FILE="$1"
if [[ -z "${LEDGER_FILE}" ]]; then
>&2 echo "Specify a ledger file as the first argument"
exit 1
fi
LEDGER="$(command -v ledger)"
if [[ -z "${LEDGER}" ]]; then
>&2 echo "Ledger not found in PATH. Is it installed?"
exit 2
fi
CURL="$(command -v curl)"
if [[ -z "${CURL}" ]]; then
>&2 echo "curl not found in PATH. Is it installed?"
exit 3
fi
JQ="$(command -v jq)"
if [[ -z "${JQ}" ]]; then
>&2 echo "jq not found in PATH. Is it installed?"
exit 4
fi
JSON="$("${CURL}" -q 'https://api.coinmarketcap.com/v1/ticker/?limit=0')"
for symbol in `"${LEDGER}" -f "${LEDGER_FILE}" commodities`; do
case ${symbol} in
# cryptos not tracked on coinmarketcap plus some common fiat currencies that might be commingled.
"NSC" | "cyberShare" | "USD" | "EUR" | "CAD" )
continue
;;
# ambiguous symbols need special handling
"BTG" )
price="$(echo "$JSON" | "${JQ}" -r ".[] | select(.id == \"bitcoin-gold\") | .price_usd")"
last_updated_secs="$(echo "$JSON" | "${JQ}" -r ".[] | select(.id == \"bitcoin-gold\") | .last_updated")"
;;
*)
price="$(echo "$JSON" | "${JQ}" -r ".[] | select(.symbol == \"${symbol}\") | .price_usd")"
last_updated_secs="$(echo "$JSON" | "${JQ}" -r ".[] | select(.symbol == \"${symbol}\") | .last_updated")"
;;
esac
#TODO: this is dependent on BSD date, not GNU date, which wants `date -d @secs format`
ts="$(date -r ${last_updated_secs} "+%Y-%m-%d %H:%I:%S")"
echo "P ${ts} ${symbol} ${price} USD"
done
# TODO: can jq handle the output formatting?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment