#!/bin/sh -eu
#
# Connect to BitcoinWisdom web socket and display rates real time
#
# Requires `wscat` from Debian package `node-ws`. NB! Oh Lord would
# you fix its output not to contain ANSI escape sequences.

. "`dirname $0`/common.sh"
old_price=0

while sleep 60; do
    # Produce ping command to the web socket stream every minute
    echo say ping >&2
    echo ping
done |
    # Fetch the content via web socket
    wscat --connect 'https://d2.bitcoinwisdom.com/?symbol=bitfinexbtcusd' |
	# Ugly colors in wscat output, get only the payload
	sed -urn 's/^> .\[2K.\[E.\[34m< (.*).\[39m$/\1/p' |
	# Get last trade in a packet and get its price
	stdbuf -oL jq 'select(.type=="trades") | .trades | last | .price' |
	while read -r price; do
	    if test $old_price = $price; then
		arrow='→'
	    elif test 1 -eq `echo "$old_price < $price" | bc`; then
		arrow='↑'
	    else
		arrow='↓'
	    fi
	    render_text "`printf "$ %.2f" $price`$arrow"
	    echo got trade $price >&2
	    old_price=$price
	done |
	send_to_screen "$1"
