-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgfo
executable file
·389 lines (315 loc) · 10.7 KB
/
gfo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
#!/usr/bin/env bash
set -Eeuo pipefail
trap cleanup SIGINT SIGTERM ERR EXIT
script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd -P)
CONFIG_FILE="$HOME/.config/gfo-cli/gfo.conf"
NAME="gfo"
AUTHOR="Johannes Herforth <[email protected]>"
VERSION="0.1.0"
usage() {
cat <<EOF
Program: $NAME
Version: $VERSION
Author : $AUTHOR
Check up on your Ghostfolio account via a convenient CLI.
The script aims to require minimal dependencies to be as simple and
portable as possible.
If logged in, the script with no arguments will show a smiley face
depending on how well your portfolio is doing today! (super-zen mode)
USAGE:
$NAME <SUBCOMMAND>
OPTIONS:
-h, --help Print this help and exit
SUBCOMMANDS:
login Login to the Ghostfolio instance using your secret token
status Check to see overview information about your profile
account Print overview account information
positions Print all positions sorted by relative net percentage change
config Print out the configuration file
EOF
exit
}
cleanup() {
trap - SIGINT SIGTERM ERR EXIT
# script cleanup here
}
setup_colors() {
if [[ -t 2 ]] && [[ -z "${NO_COLOR-}" ]] && [[ "${TERM-}" != "dumb" ]]; then
NOFORMAT='\033[0m' RED='\033[0;31m' GREEN='\033[0;32m' ORANGE='\033[0;33m' BLUE='\033[0;34m' PURPLE='\033[0;35m' CYAN='\033[0;36m' YELLOW='\033[1;33m'
else
NOFORMAT='' RED='' GREEN='' ORANGE='' BLUE='' PURPLE='' CYAN='' YELLOW=''
fi
}
msg() {
echo >&2 -e "${1-}"
}
die() {
local msg=$1
local code=${2-1} # default exit status 1
msg "$msg"
exit "$code"
}
parse_params() {
# default values of variables set from params
source $CONFIG_FILE
while :; do
case "${1-}" in
-h | --help) usage ;;
-v | --verbose) set -x ;;
--no-color) NO_COLOR=1 ;;
-?*) die "Unknown option: $1" ;;
*) break ;;
esac
shift
done
args=("$@")
return 0
}
login () {
if [ "$1" = "demo" ]
then
GHOSTFOLIO_AUTH="$(execute_api "v1/info" | jq -r .demoAuthToken)"
else
GHOSTFOLIO_AUTH="$(execute_api "v1/auth/anonymous/$1" | jq -r .authToken)"
fi
if [ $(echo -n "$GHOSTFOLIO_AUTH" | wc -m) = 187 ]
then
sed -i "s/\($GHOSTFOLIO_AUTH *= *\).*/\1$GHOSTFOLIO_AUTH/" $CONFIG_FILE
sed -i "/GHOSTFOLIO_AUTH=/d" $CONFIG_FILE
echo "GHOSTFOLIO_AUTH=$GHOSTFOLIO_AUTH" >> $CONFIG_FILE
msg "${GREEN}Ghostfolio bearer token has been updated!${NOFORMAT}"
else
msg "${RED}Error:${NOFORMAT} There was an error in updating your bearer token! Auth token was: $GHOSTFOLIO_AUTH"
fi
exit 0
}
is_logged_in () {
if [ $(echo -n "$GHOSTFOLIO_AUTH" | wc -m) = 187 ]
then
echo true
else
echo false
fi
}
logged_in_check () {
if [ $(is_logged_in) = false ]
then
msg "You are not logged in! Login using your security token with: $NAME login <security token>"
exit 1
fi
}
execute_api () {
echo $(curl -s $GHOSTFOLIO_INSTANCE/api/$1 -H "Authorization: Bearer $GHOSTFOLIO_AUTH" -H "User-Agent: ghostfolio-cli/$VERSION")
}
execute_api_debug () {
echo $(curl -s -v $GHOSTFOLIO_INSTANCE/api/$1 -H "Authorization: Bearer $GHOSTFOLIO_AUTH" -H "User-Agent: ghostfolio-cli/$VERSION")
}
bool_expression () {
echo $(printf 'if(%s '$2' %s){a=1};a\n' $1 $3 | bc -s)
}
conform_number () {
# check if the result is insanely small
if echo $1 | grep -q "e"
then
echo 0
else
# return number including trailing 0 if -1 < number < 1
echo $1 | sed -e 's/^\./0./' -e 's/^-\./-0./'
fi
}
get_symbol () {
case "$1" in
USD) echo "$ " ;;
EUR) echo "€ " ;;
GBP) echo "£ " ;;
JPY) echo "¥ " ;;
INR) echo "₹ " ;;
CHF) echo "₣ " ;;
*) echo "$1 "
esac
}
get_account_ids () {
local accounts=$(execute_api "v1/account" | jq .accounts[1:] | jq .[].id -r )
echo $accounts
}
accounts () {
logged_in_check
local accounts=$(execute_api "v1/account" | jq .accounts )
local counter=0
echo $accounts | jq -c '.[]' | while read account; do
local name=$(echo "$account" | jq -r .name)
local is_default=$(echo $account | jq -r .isDefault)
if [ $is_default = true ]
then
msg "Account $counter: $name (${RED}DEFAULT${NOFORMAT}) \n"
else
msg "Account $counter: $name \n"
fi
accounts_view "$account" | column -s '|' --table
if [ $counter = 0 ]
then
msg "\n"
fi
counter=$(echo "$counter + 1" | bc -s )
done
}
accounts_view () {
read account_type currency value balance trans_count created updated < <(echo $(echo "$1" | jq -r '.accountType, .currency, .value, .balance, .transactionCount, .createdAt, .updatedAt'))
echo -e "Account Type:|$account_type"
echo -e "Currency:|$currency"
echo -e "Current Value:|$(echo "scale=2;$value / 1" | bc -s)"
echo -e "Current Balance:|$(echo "scale=2;$balance / 1" | bc -s)"
echo -e "Completed Transactions:|$trans_count"
echo -e "Created:|$(date -d "$created" -R)"
echo -e "Last Update:|$(date -d "$updated" -R)"
}
positions () {
logged_in_check
# input handling
if [ -z "${1-}" ]
then
local time_range=$DEFAULT_RANGE
else
case "$1" in
1d|ytd|1y|5y|max) local time_range=$1 ;;
*) msg "${ORANGE}Invalid Timerange:${NOFORMAT} Select between (1d,ytd,1y,5y,max)"; exit 1 ;;
esac
fi
# sort the positions by performance percentage. Better positions are higher up
local positions=$(execute_api "v1/portfolio/positions?range=$time_range" | jq '.positions | sort_by(.netPerformancePercentage) | reverse')
local chart=$(execute_api "v2/portfolio/performance?range=$time_range" | jq .chart)
local start_date=$(echo $chart | jq -r .[0].date)
local end_date=$(echo $chart | jq -r .[-1].date)
msg "${ORANGE}Portfolio Performance change from${NOFORMAT} ${CYAN}$start_date${NOFORMAT} ${ORANGE}to${NOFORMAT} ${CYAN}$end_date${NOFORMAT} ${ORANGE}($time_range)${NOFORMAT}"
position_list "$positions" | column -s '|' --table --table-right 2
}
position_list () {
echo $1 | jq -c '.[]' | while read position; do
local name=$(echo $position | jq -r .name)
read currency symbol market_price net_percentage < <(echo $(echo $position | jq -r '.currency, .symbol, .marketPrice, .netPerformancePercentage'))
net_percentage=$(conform_number $net_percentage | echo "scale=2;$(cat -) / 0.01" | bc -s )
if [ $(bool_expression $net_percentage ">=" 0) = 1 ]
then
echo -e "$name|($symbol):|$(get_symbol $currency)$market_price (${GREEN}+$net_percentage%${NOFORMAT})"
else
echo -e "$name|($symbol):|$(get_symbol $currency)$market_price (${RED}$net_percentage%${NOFORMAT})"
fi
done
}
quick_check () {
local portfolio_info=$(execute_api "v2/portfolio/performance?range=1d")
local change=$(conform_number $(conform_number $(echo $portfolio_info | jq .performance.currentNetPerformancePercent) | echo "scale=2;$(cat -) / 0.01" | bc -s))
local dow=$(date +%u)
if [ $(bool_expression "$dow" ">" "5" ) -eq 1 ]
then
# if it is the weekend, make sure to tell them that they are not doing it right
msg "It's the weekend. Go out and have some fun! 8-)"
elif [ $(bool_expression "$change" "<" "$SMILE_MID_MAX") -eq 1 ] && [ $(bool_expression "$change" ">" "$SMILE_MID_MIN") -eq 1 ]
then
# if basically zero
msg ":-|"
elif [ $(bool_expression "$change" ">=" "$SMILE_MID_MAX") -eq 1 ]
then
# Doing good!
if [ $(bool_expression "$change" "<" "$SMILE_GOOD_MAX") -eq 1 ]
then
msg ":-)"
else
msg ":-D"
fi
elif [ $(bool_expression "$change" "<=" "$SMILE_MID_MIN") -eq 1 ]
then
# Doing bad!
if [ $(bool_expression "$change" ">" "$SMILE_BAD_MAX") -eq 1 ]
then
msg ":-("
else
msg ":'-("
fi
fi
exit 0
}
config () {
cat $CONFIG_FILE
}
overview () {
logged_in_check
# input handling
if [ -z "${1-}" ]
then
local time_range=$DEFAULT_RANGE
else
case "$1" in
1d|ytd|1y|5y|max) local time_range=$1 ;;
*) msg "${ORANGE}Invalid Timerange:${NOFORMAT} Select between (1d,ytd,1y,5y,max)"; exit 1 ;;
esac
fi
local portfolio_info=$(execute_api "v2/portfolio/performance/?range=$time_range")
local accounts_info=$(execute_api "v1/user")
local base_currency=$(get_symbol $(echo "$accounts_info" | jq -r .settings.baseCurrency))
# dates
local chart=$(echo $portfolio_info | jq .chart)
local start_date=$(echo $chart | jq -r .[0].date)
local end_date=$(echo $chart | jq -r .[-1].date)
msg "${ORANGE}Portfolio Performance change from${NOFORMAT} ${CYAN}$start_date${NOFORMAT} ${ORANGE}to${NOFORMAT} ${CYAN}$end_date${NOFORMAT} ${ORANGE}($time_range)${NOFORMAT}"
overview_message $portfolio_info $base_currency | column -s "|" --table
exit 0
}
overview_message () {
# main blocks
local performance=$(echo $1 | jq .performance)
# value changes
local current_value=$(echo $performance | jq .currentValue | echo "scale=2;$(cat -) / 1" | bc -s)
local net_absolute=$(echo $performance | jq .currentNetPerformance | echo "scale=2;$(cat -) / 1" | bc -s)
local net_relative=$(conform_number $(echo $1 | jq .performance.currentNetPerformancePercent) | echo "scale=2;$(cat -) / 0.01" | bc -s )
echo -e "Current Value:|$2 $current_value"
if [ $(bool_expression $net_relative ">=" "0") = 1 ]
then
echo -e "Net Value Change:|${GREEN}$2 $net_absolute (+$net_relative%)${NOFORMAT}"
else
echo -e "Net Value Change:|${RED}$2 $net_absolute ($net_relative%)${NOFORMAT}"
fi
}
if [ ! -f $CONFIG_FILE ]
then
mkdir -p $(dirname $CONFIG_FILE)
cat << EOF > $CONFIG_FILE
# Instance URL
GHOSTFOLIO_INSTANCE="http://localhost:3333"
# Default range that should be used in arguments
DEFAULT_RANGE="1d"
# Smiley settings: When is a portfolio doing well and when not?
SMILE_MID_MIN=-0.25 # minimum value to be considered neutral portfolio
SMILE_MID_MAX=0.25 # maximum value to be considered neutral portfolio
SMILE_GOOD_MAX=1 # maximum value to be considered "good". Above is "great"!
SMILE_BAD_MAX=-1 # minimum value to be considered "bad". Below is "terrible"!
# Bearer Auth Code
GHOSTFOLIO_AUTH=
EOF
msg "Config file did not exist. Created default file at $CONFIG_FILE."
msg "Please review the settings and fill the AUTH token by signing in using:"
msg "$NAME login <security token>"
exit 0
fi
parse_params "$@"
setup_colors
# script logic here
# msg "${RED}Read parameters:${NOFORMAT}"
# msg "- flag: ${flag}"
# msg "- param: ${param}"
# msg "- arguments: ${args[*]-}"
# msg "$(${args[0]} ${args[1]})"
# without subcommand
if [ $(is_logged_in) = true ] && [ $# -lt 1 ]
then
quick_check
fi
# if there is a subcommand
case "$1" in
login) shift; login "$@" ;;
accounts) shift; accounts "$@" ;;
positions) shift; positions "$@" ;;
status) shift; overview "$@" ;;
config) shift; config "$@" ;;
*) die "${RED}Error:${NOFORMAT} Unknown option: $1" ;;
esac