#! /bin/bash
# Last edited on 2014-06-15 19:35:57 by stolfilocal

# Plots the ratio of prices at two exchanges.
# 
# Arguments: {TITLE} {VMIN} {VMAX} {FNAME}
# 
# Where 
#   
#   {TITLE} is the plot's title;
#   {VMIN},{VMAX} is the range of ratios for the vertical scale of the plot; 
#   {FNAME} is a data file with one line per slumber time in format
#      "{DATE} {TIME} | {HUBI.L} | {HUBI.H} | {HUBI.M} | {BSTP.L} | {BSTP.H} | {BSTP.M} |
#   

title="$1"; shift  # Plot title.
vmin="$1"; shift   # Min price for plot range.
vmax="$1"; shift   # Max price for plot range.
ptsize="$1"; shift # Variable for plot size: (daily) "volume", or "weight".
fname="$1"; shift  # Input file name. 
label=( "HUBI" "BSTP" )

if [[ "/${ptsize}" == "/volume" ]]; then
  pszcode=0; 
elif [[ "/${ptsize}" == "/weight" ]]; then
  pszcode=1;
else
  echo "** invalid ptsize \"${ptsize}\"" 1>&2 ; exit 1
fi

show="SHOW"

tmp="/tmp/$$"

color=( '#0022ff' '#ff0000' '#008800' '#8800dd' '#dd4400' '#0066ff' )

export GDFONTPATH=.:..

gnuplot <<EOF
set term png size 4000,800 font "courbd,24"
set output "${tmp}-full.png"
set title "${title}"

vratio(i,j) = ((column(i) == 0) || (column(j) == 0) ? 0/0 : column(i)/column(j))
vmin = ${vmin}
vmax = ${vmax}
pszcode=${pszcode}
set timefmt "%Y-%m-%d %H:%M:%S" # For {timecolumn}.

set ytics 0.5
set mytics 5

set xtics 10*24*3600
set mxtics 10

ratit = "${label[0]}/${label[1]}"
set yrange [vmin:vmax]
set grid ytics lt 1 lw 4 lc rgb '#ffaa55', lt 1 lw 1.5 lc rgb '#ffaa55'
set grid mytics

set xdata time
set format x "%b/%d"
set grid xtics lt 1 lw 4 lc rgb '#ffaa55', lt 1 lw 1.5 lc rgb '#ffaa55'
set grid mxtics
set key bottom right

minps = 1.0  # Min point size.
refps = 5.0  # Max point size.

minwt = 0.0  # Clip weight up to this value.
refwt = 1.0  # Weight for point size = {refps}.

minvol =   0.00  # Clip volume up to this value.
refvol = 150.00  # Volume for point size = {refps}.

load "plot_slumber_funcs.gnuplot"

psz(code) = (code == 0 ? volps(column(22)) : wps(column(28)))

plot \
  "< grep -e '^20' ${fname}" using (timecolumn(1)):(vratio(8,14)):(psz(pszcode)) title ratit \
    with linespoints pt 7 ps variable lt 1 lw 3.0 lc rgb '#0044dd'
    
quit
EOF

plotfile="${tmp}.png"
convert ${tmp}-full.png -resize '50%' ${plotfile}

if [[ "/${show}" == "/SHOW" ]]; then
  if [[ -s ${plotfile} ]]; then
    display ${plotfile}
  fi
fi

cat ${plotfile}

rm -fv ${tmp}{-*,}.*
    
        
