#!/bin/sh

HOUR=$(date +%H)
IFS=";"
while read DATE CURRENCY COIN PRICE FEE BUYRATE SELLTHRESH;
do
	weeklyMax=$(rrdtool fetch rrd/crypto-${CURRENCY}.rrd AVERAGE --start -7d | grep -v -- '-nan' | sort -n -k 2 | tail -1 | awk '{print $2}' | sed 's/e+/ * 10^/g; s/e-/ * 10^-/g;' | bc -l)
	current=$(rrdtool fetch rrd/crypto-${CURRENCY}.rrd LAST --start -10m | grep -v -- '-nan' | tail -1 | awk '{print $2}' | sed 's/e+/ * 10^/g; s/e-/ * 10^-/g' | bc -l)
	curValue=$(echo "$COIN * $current - $FEE" | bc -l)
	curProfit=$(printf "%0.2f" $(echo "$curValue - $PRICE" | bc))
	profitPerc=$(printf "%0.2f" $(echo "$curProfit / $PRICE * 100" | bc -l))
	maxDiff=$(printf "%0.2f" $(echo "(($weeklyMax) - ($current)) / ($weeklyMax) * 100" | bc -l))

	if [ "$CURRENCY" == "BTC" ] && [ "${current%%.*}" -lt "7000" ];
	then
		echo "[$CURRENCY] low exchange rate: $current EUR/${CURRENCY} => Buy more?"
		continue;
	fi

	if [ "${profitPerc%%.*}" -ge "$SELLTHRESH" ];
	then
		echo "[$CURRENCY] bought: ${DATE}"
		echo "[$CURRENCY] profit: ${profitPerc}% >= ${SELLTHRESH}% !!!!"
		echo "[$CURRENCY] profit: $curProfit EUR (${profitPerc}%)"
		echo "[$CURRENCY] maxDiff: ${maxDiff}%"
		echo
		continue
	fi

#	if [ "0${maxDiff%%.*}" -ge "10" ];
#	then
#		echo "[$CURRENCY] exchange rate dropped ${maxDiff}% (max: $weeklyMax EUR/${CURRENCY}, cur: $current EUR/${CURRENCY}) => Buy more?"
#		continue;
#	fi
#
#	if [ "0${maxDiff%%.*}" -gt "3" ];
#	then
#		echo "[$CURRENCY] prices dropped ${maxDiff}% (max: $weeklyMax EUR/${CURRENCY}, cur: $current EUR/${CURRENCY})"
#		if [ "0${profitPerc%%.*}" -ge "10" ];
#		then
#			echo "[$CURRENCY] profit: $curProfit EUR (${profitPerc}%) => sell?"
#			continue;
#		fi
#	fi

	if [ "0$HOUR" -eq "6" ];
	then
		echo "[$CURRENCY] bought: ${DATE}"
		echo "[$CURRENCY] profit: $curProfit EUR (${profitPerc}%)"
		echo "[$CURRENCY] maxDiff: ${maxDiff}%"
		echo
	fi
done < $1