Skip to content

Instantly share code, notes, and snippets.

@eploko
Created March 16, 2021 03:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eploko/c054baa8b71c194819e18c0d06237ee9 to your computer and use it in GitHub Desktop.
Save eploko/c054baa8b71c194819e18c0d06237ee9 to your computer and use it in GitHub Desktop.
Getting currency and commodity rates for ledger-cli w/ a simple babashka script
PATH=/parent/dir/of/daily-quotes.sh:/parent/dir/of/getquote.clj:/usr/local/bin:/usr/bin:/bin
00 10,14,16,20,22 * * * daily-quotes.sh
#!/usr/bin/env zsh
set -euo pipefail
LEDGER_PRICE_DB="/path/to/your/price/db/fx-rates.ledger"
# Repeat for each currency you are interested in...
echo P `getquote.clj USD` >> "${LEDGER_PRICE_DB}"
echo P `getquote.clj RUB` >> "${LEDGER_PRICE_DB}"
echo P `getquote.clj BTC` >> "${LEDGER_PRICE_DB}"
#!/usr/bin/env bb
(require '[babashka.curl :as curl]
'[cheshire.core :as json])
(import 'java.time.format.DateTimeFormatter
'java.time.LocalDateTime)
;; The base/main currency in your ledger
(def base-sym "AUD")
;; Get your API key at:
;; https://free.currencyconverterapi.com
(def api-key "YOUR-API-KEY-HERE")
(defn ldate
[]
(let [date (LocalDateTime/now)
formatter (DateTimeFormatter/ofPattern "yyyy-MM-dd HH:mm:ss")]
(.format date formatter)))
(defn ep
[sym]
(str "https://free.currconv.com/api/v7/convert"
"?apiKey=" api-key
"&q=" sym
"&compact=y"))
(defn to-base
[sym base]
(str sym "_" base))
(defn get-url
[url]
(-> (curl/get url {:headers {"Accept" "application/json"}})
:body
(json/parse-string true)))
(defn to-ledger
[x sym base]
(let [q (keyword (to-base sym base))
v (-> x q :val)]
(str (ldate) " " sym " " v " " base)))
(let [[sym] *command-line-args*]
(when (empty? sym)
(println "Usage: <sym>")
(System/exit 1))
(-> sym (to-base base-sym) ep get-url (to-ledger sym base-sym) println))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment