#!/bin/bash
set -euo pipefail
# Versio 0.03 / TK
rawtempdata=$(mktemp)
pricedata=$(mktemp)
finalprices=$(mktemp)
RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[0;33m'
NOCOLOR='\033[0m'
currentdate=$(date "+%d-%m-%Y")
# Fetching current data from unofficial API (series there starts from 1:00 Finnish time)
curl -s -L --connect-timeout 3 --retry-delay 0 --retry 3 --max-time 10 "https://www.nordpoolspot.com/api/marketdata/page/10?currency=EUR&endDate=$currentdate" -o "$rawtempdata"
if [ $? -eq 0 ]; then
# Parsing only prices from JSON reply
jq '.data.Rows[].Columns[] | select(.CombinedName | contains("FI"))' "$rawtempdata" | grep '"Value"' | \
sed -r 's/.*: "(.*)".*/\1/' | tr "," "." | awk '{ printf("%.1f\n", ($1/10)*1.24 )}' | head -24 > "$pricedata"
# Adding hours to the front of prices
seq -f "%02g:00" 01 24 | paste - "$pricedata" | sed 's/24:00/00:00/' > "$finalprices"
# Printing hourly prices with ANSI colours (escape codes)
echo
echo "Time Price (snt/kWh, with 24% VAT)"
while read -r line; do
price=$(echo "$line" | expand | sed 's/.* //')
if (( $(echo "$price > 15" |bc -l) )); then # If price is above 15 snt/kWh
echo -e "${RED}$line${NOCOLOR}"
elif (( $(echo "$price < 5" |bc -l) )); then # If price is below 5 snt/kWh
echo -e "${GREEN}$line${NOCOLOR}"
else
echo -e "${YELLOW}$line${NOCOLOR}" # Default colour for price if no match
fi
done < "$finalprices"
# Calculating and printing average price
average=$(cat "$pricedata" | awk '{ sum += $1; n++ } END { if (n > 0) printf("%.1f\n", sum / n); }')
echo
echo "Average price:"
echo "$average snt/kWh"
# Current price
hournow=$(date +%0H:00)
echo
echo "Price now (snt/kWh):"
seq -f "%02g:00" 01 24 | paste - "$pricedata" | grep "$hournow"
echo
# Example how to use Gnuplot to make a ASCII chart from prices. Quite useless
#seq -f "%02g:00" 01 24 | paste - "$pricedata" | gnuplot -e "set term dumb 70 20; set tic scale 0; plot '-' with lines notitle"
fi
# Clearing temporary files
rm -f "$rawtempdata" "$pricedata" "$finalprices"