pstadler / ticker.sh

Real-time stock tickers from the command-line.
MIT License
511 stars 87 forks source link

Symbol listed twice crashes ticker.sh script #14

Closed PSLLSP closed 4 years ago

PSLLSP commented 4 years ago

Symbol listed twice crashes ticker.sh script. Example:

$ ./ticker.sh GOOG GOOG
./ticker.sh: line 43: [: POSTPOST: binary operator expected
./ticker.sh: line 51: [: too many arguments
./ticker.sh: line 58: [: too many arguments
GOOG       1265.131265.13       0.00./ticker.sh: line 81: printf: (0.33%)(0.33%): invalid number
      4.14   4.1400146      0.00

Problem is that once symbol is listed more than once, "jq" returns not a string but an array.

The fix:

$ git diff
diff --git a/ticker.sh b/ticker.sh
index 6bceda6..acf2435 100755
--- a/ticker.sh
+++ b/ticker.sh
@@ -34,13 +34,13 @@ results=$(curl --silent "$API_ENDPOINT&fields=$fields&symbols=$symbols" \
   | jq '.quoteResponse .result')

 query () {
-  echo $results | jq -r ".[] | select(.symbol == \"$1\") | .$2"
+  echo $results | jq -r "[.[] | select(.symbol == \"$1\") | .$2][0]"
 }

 for symbol in $(IFS=' '; echo "${SYMBOLS[*]}"); do
   marketState="$(query $symbol 'marketState')"

-  if [ -z $marketState ]; then
+  if [ "$marketState" = "null" ]; then
     printf 'No results for symbol "%s"\n' $symbol
     continue
   fi

Example after the fix:

$ ./ticker.sh GOOG GOOG
GOOG       1270.00      4.87     (0.38%) *
GOOG       1270.00      4.87     (0.38%) *

There is one more problem with some symbols those are not active anymore. I am not sure, for example "YHOO" or "NV". printf command crashes because it cannot print "null" as number. I suggest following fix but I am not sure if it is the right solution; maybe some message should be written:

@@ -69,6 +69,12 @@ for symbol in $(IFS=' '; echo "${SYMBOLS[*]}"); do
     percent=$(query $symbol 'regularMarketChangePercent')
   fi

+  if [ "$price" = "null" ]; then
+    price="0"
+    diff="0"
+    percent="0"
+  fi
+
   if [ "$diff" == "0" ]; then
     color=
   elif ( echo "$diff" | grep -q ^- ); then
pstadler commented 4 years ago

Why would you list the same ticker twice?