SpeedCrunch is an awesome calculator. Good history, variables and realtime calculations.
Missing was currency conversion, which is available in other calculators. I was trying to find plugins for it but no go.
So the strategy here is to use an API to grab the current conversions and then write them to SpeedCrunch’s history file which is a JSON of past commands and saved variables. We’ll save our exchange rates as variables that can then be used in SpeedCrunch.
You’ll need to get a free API Key from https://freecurrencyapi.com/ – the free tier is good for 5k/month calls so that should be plenty
Here’s the bash script which calls an inline PHP script:
#!/bin/bash
JSONFILE="$HOME/freecurrencyapi-currencies.json"
HISTORYFILE="$HOME/.local/share/SpeedCrunch/history.json"
APIKEY=<PUTYOURAPIKEYHERE>
curl --silent "https://api.freecurrencyapi.com/v1/latest?apikey=$APIKEY" > $JSONFILE
php <<EOF
<?php
\$data = json_decode(file_get_contents("$JSONFILE"));
\$currenciesWeCareAbout = [
'CAD',
'EUR',
'GBP',
'USD',
'CHF',
];
\$vars = [];
foreach( \$currenciesWeCareAbout as \$currency1 ) {
foreach( \$currenciesWeCareAbout as \$currency2 ) {
# if it's the same currency
if( \$currency1 == \$currency2 ) continue;
# if the currency doesn't involve CAD (remove to see all)
if( \$currency1 != 'CAD' && \$currency2 != 'CAD' ) continue;
\$currency1ToUSD = \$data->data->{\$currency1} / \$data->data->USD;
\$currency2ToUSD = \$data->data->{\$currency2} / \$data->data->USD;
\$vars[ strtolower(\$currency2 . \$currency1 ) ] = \$currency1ToUSD / \$currency2ToUSD;
\$vars[ strtolower(\$currency1 . \$currency2 ) ] = \$currency2ToUSD / \$currency1ToUSD;
}
}
# okay now vars contains our variables we want to write
\$history = json_decode(file_get_contents("$HISTORYFILE"), TRUE);
\$newVariables = \$history['variables'];
foreach( \$history['variables'] as \$arr ) {
# if the variable name is found in our \$vars array, then remove it as it will be added later
if( in_array( \$arr['identifier'], \$vars) ) {
unset(\$newVariables[ \$arr['identifier'] ]);
}
}
foreach( \$vars as \$varName => \$value ) {
\$newVariables[] = [
'identifier' => \$varName,
'type' => 'User',
'value' => [
'numeric_value' => [
'value' => (string)\$value,
],
],
];
}
\$history['variables'] = \$newVariables;
file_put_contents("$HISTORYFILE", json_encode(\$history));
?>
EOF
Make it executable <code>chmod +x currency-conversion-speedcrunch.sh</code>. And then add a cronjob to have it update once a week (or whatever frequency):
0 0 * * 0 currency-conversion-speedcrunch.sh