-
-
Notifications
You must be signed in to change notification settings - Fork 308
/
price_alerts.go
434 lines (387 loc) · 11 KB
/
price_alerts.go
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
package cointop
import (
"errors"
"fmt"
"log"
"regexp"
"strconv"
"strings"
"time"
"github.com/miguelmota/cointop/pkg/humanize"
"github.com/miguelmota/cointop/pkg/notifier"
"github.com/miguelmota/cointop/pkg/pad"
"github.com/miguelmota/cointop/pkg/table"
)
// GetPriceAlertsTableHeaders returns the alerts table headers
func (ct *Cointop) GetPriceAlertsTableHeaders() []string {
return []string{
"name",
"symbol",
"target_price",
"price",
"frequency",
}
}
// PriceAlertOperatorMap is map of valid price alert operator symbols
var PriceAlertOperatorMap = map[string]string{
">": ">",
"<": "<",
">=": "≥",
"<=": "≤",
"=": "=",
}
// PriceAlertFrequencyMap is map of valid price alert frequency values
var PriceAlertFrequencyMap = map[string]bool{
"once": true,
"reoccurring": true,
}
// GetPriceAlertsTable returns the table for displaying alerts
func (ct *Cointop) GetPriceAlertsTable() *table.Table {
ct.debuglog("getPriceAlertsTable()")
maxX := ct.width()
t := table.NewTable().SetWidth(maxX)
for _, entry := range ct.State.priceAlerts.Entries {
if entry.Expired {
continue
}
ifc, ok := ct.State.allCoinsSlugMap.Load(entry.CoinName)
if !ok {
continue
}
coin, ok := ifc.(*Coin)
if !ok {
continue
}
name := TruncateString(entry.CoinName, 20)
symbol := TruncateString(coin.Symbol, 6)
namecolor := ct.colorscheme.TableRow
frequency := entry.Frequency
_, ok = PriceAlertOperatorMap[entry.Operator]
if !ok {
continue
}
targetPrice := fmt.Sprintf("%s %s", entry.Operator, humanize.Commaf(entry.TargetPrice))
t.AddRowCells(
&table.RowCell{
LeftMargin: 1,
Width: 22,
LeftAlign: true,
Color: namecolor,
Text: name,
},
&table.RowCell{
LeftMargin: 1,
Width: 10,
LeftAlign: true,
Color: ct.colorscheme.TableRow,
Text: symbol,
},
&table.RowCell{
LeftMargin: 1,
Width: 16,
LeftAlign: false,
Color: ct.colorscheme.TableColumnPrice,
Text: targetPrice,
},
&table.RowCell{
LeftMargin: 1,
Width: 11,
LeftAlign: false,
Color: ct.colorscheme.TableRow,
Text: humanize.Commaf(coin.Price),
},
&table.RowCell{
LeftMargin: 2,
Width: 11,
LeftAlign: true,
Color: ct.colorscheme.TableRow,
Text: frequency,
},
)
}
return t
}
// TogglePriceAlerts toggles the price alerts view
func (ct *Cointop) TogglePriceAlerts() error {
ct.debuglog("togglePriceAlerts()")
ct.ToggleSelectedView(PriceAlertsView)
ct.NavigateFirstLine()
go ct.UpdateTable()
return nil
}
// IsPriceAlertsVisible returns true if alerts view is visible
func (ct *Cointop) IsPriceAlertsVisible() bool {
return ct.State.selectedView == PriceAlertsView
}
// PriceAlertWatcher starts the price alert watcher
func (ct *Cointop) PriceAlertWatcher() {
ct.debuglog("priceAlertWatcher()")
alerts := ct.State.priceAlerts.Entries
ticker := time.NewTicker(2 * time.Second)
for {
select {
case <-ticker.C:
for _, alert := range alerts {
err := ct.CheckPriceAlert(alert)
if err != nil {
log.Fatal(err)
}
}
}
}
}
// CheckPriceAlert checks the price alert
func (ct *Cointop) CheckPriceAlert(alert *PriceAlert) error {
ct.debuglog("checkPriceAlert()")
if alert.Expired {
return nil
}
coinIfc, _ := ct.State.allCoinsSlugMap.Load(alert.CoinName)
coin, ok := coinIfc.(*Coin)
if !ok {
return nil
}
var msg string
title := "Cointop Alert"
priceStr := fmt.Sprintf("%s%s (%s%s)", ct.CurrencySymbol(), humanize.Commaf(alert.TargetPrice), ct.CurrencySymbol(), humanize.Commaf(coin.Price))
if alert.Operator == ">" {
if coin.Price > alert.TargetPrice {
msg = fmt.Sprintf("%s price is greater than %v", alert.CoinName, priceStr)
}
} else if alert.Operator == ">=" {
if coin.Price >= alert.TargetPrice {
msg = fmt.Sprintf("%s price is greater than or equal to %v", alert.CoinName, priceStr)
}
} else if alert.Operator == "<" {
if coin.Price < alert.TargetPrice {
msg = fmt.Sprintf("%s price is less than %v", alert.CoinName, priceStr)
}
} else if alert.Operator == "<=" {
if coin.Price <= alert.TargetPrice {
msg = fmt.Sprintf("%s price is less than or equal to %v", alert.CoinName, priceStr)
}
} else if alert.Operator == "=" {
if coin.Price == alert.TargetPrice {
msg = fmt.Sprintf("%s price is equal to %v", alert.CoinName, priceStr)
}
}
if msg != "" {
if ct.State.priceAlerts.SoundEnabled {
notifier.NotifyWithSound(title, msg)
} else {
notifier.Notify(title, msg)
}
alert.Expired = true
}
if err := ct.Save(); err != nil {
return err
}
return nil
}
// UpdatePriceAlertsUpdateMenu updates the alerts update menu view
func (ct *Cointop) UpdatePriceAlertsUpdateMenu(isNew bool) error {
ct.debuglog("updatePriceAlertsUpdateMenu()")
exists := false
var value string
var currentPrice string
var coinName string
ct.State.priceAlertEditID = ""
if !isNew && ct.IsPriceAlertsVisible() {
rowIndex := ct.HighlightedRowIndex()
entry := ct.State.priceAlerts.Entries[rowIndex]
ifc, ok := ct.State.allCoinsSlugMap.Load(entry.CoinName)
if ok {
coin, ok := ifc.(*Coin)
if ok {
coinName = entry.CoinName
currentPrice = strconv.FormatFloat(coin.Price, 'f', -1, 64)
value = fmt.Sprintf("%s %v", entry.Operator, entry.TargetPrice)
ct.State.priceAlertEditID = entry.ID
exists = true
}
}
}
var mode string
var current string
var submitText string
var offset int
if exists {
mode = "Edit"
current = fmt.Sprintf("(current %s%s)", ct.CurrencySymbol(), currentPrice)
submitText = "Set"
offset = ct.width() - 21
} else {
coin := ct.HighlightedRowCoin()
coinName = coin.Name
currentPrice = strconv.FormatFloat(coin.Price, 'f', -1, 64)
value = fmt.Sprintf("> %s", currentPrice)
mode = "Create"
submitText = "Create"
offset = ct.width() - 23
}
header := ct.colorscheme.MenuHeader(fmt.Sprintf(" %s Alert Entry %s\n\n", mode, pad.Left("[q] close ", offset, " ")))
label := fmt.Sprintf(" Enter target price for %s %s", ct.colorscheme.MenuLabel(coinName), current)
content := fmt.Sprintf("%s\n%s\n\n%s%s\n\n\n [Enter] %s [ESC] Cancel", header, label, strings.Repeat(" ", 29), ct.State.currencyConversion, submitText)
ct.UpdateUI(func() error {
ct.Views.Menu.SetFrame(true)
ct.Views.Menu.Update(content)
ct.Views.Input.Write(value)
ct.Views.Input.SetCursor(len(value), 0)
return nil
})
return nil
}
// ShowPriceAlertsAddMenu shows the alert add menu
func (ct *Cointop) ShowPriceAlertsAddMenu() error {
ct.debuglog("showPriceAlertsAddMenu()")
ct.State.lastSelectedRowIndex = ct.HighlightedPageRowIndex()
ct.UpdatePriceAlertsUpdateMenu(true)
ct.ui.SetCursor(true)
ct.SetActiveView(ct.Views.Menu.Name())
ct.g.SetViewOnTop(ct.Views.Input.Name())
ct.g.SetCurrentView(ct.Views.Input.Name())
return nil
}
// ShowPriceAlertsUpdateMenu shows the alerts update menu
func (ct *Cointop) ShowPriceAlertsUpdateMenu() error {
ct.debuglog("showPriceAlertsUpdateMenu()")
ct.State.lastSelectedRowIndex = ct.HighlightedPageRowIndex()
ct.UpdatePriceAlertsUpdateMenu(false)
ct.ui.SetCursor(true)
ct.SetActiveView(ct.Views.Menu.Name())
ct.g.SetViewOnTop(ct.Views.Input.Name())
ct.g.SetCurrentView(ct.Views.Input.Name())
return nil
}
// HidePriceAlertsUpdateMenu hides the alerts update menu
func (ct *Cointop) HidePriceAlertsUpdateMenu() error {
ct.debuglog("hidePriceAlertsUpdateMenu()")
ct.ui.SetViewOnBottom(ct.Views.Menu)
ct.ui.SetViewOnBottom(ct.Views.Input)
ct.ui.SetCursor(false)
ct.SetActiveView(ct.Views.Table.Name())
ct.UpdateUI(func() error {
ct.Views.Menu.SetFrame(false)
ct.Views.Menu.Update("")
ct.Views.Input.Update("")
return nil
})
return nil
}
// EnterKeyPressHandler is the key press handle for update menus
func (ct *Cointop) EnterKeyPressHandler() error {
if ct.IsPriceAlertsVisible() {
return ct.CreatePriceAlert()
}
return ct.SetPortfolioHoldings()
}
// CreatePriceAlert sets price from inputed value
func (ct *Cointop) CreatePriceAlert() error {
ct.debuglog("createPriceAlert()")
defer ct.HidePriceAlertsUpdateMenu()
var coinName string
if ct.State.priceAlertEditID == "" {
coin := ct.HighlightedRowCoin()
coinName = coin.Name
} else {
for i, entry := range ct.State.priceAlerts.Entries {
if entry.ID == ct.State.priceAlertEditID {
coinName = ct.State.priceAlerts.Entries[i].CoinName
}
}
}
operator, targetPrice, err := ct.ReadAndParsePriceAlertInput()
if err != nil {
return err
}
if err := ct.SetPriceAlert(coinName, operator, targetPrice); err != nil {
return err
}
ct.UpdateTable()
ct.GoToPageRowIndex(ct.State.lastSelectedRowIndex)
return nil
}
// ReadAndParsePriceAlertInput reads and parses price alert input field value
func (ct *Cointop) ReadAndParsePriceAlertInput() (string, float64, error) {
// read input field
b := make([]byte, 100)
n, err := ct.Views.Input.Read(b)
if err != nil {
return "", 0, err
}
if n == 0 {
return "", 0, nil
}
inputValue := string(b)
operator, targetPrice, err := ct.ParsePriceAlertInput(inputValue)
if err != nil {
return "", 0, err
}
return operator, targetPrice, nil
}
// ParsePriceAlertInput parses price alert input field value
func (ct *Cointop) ParsePriceAlertInput(value string) (string, float64, error) {
regex := regexp.MustCompile(`(>|<|>=|<=|=)?\s*([0-9.]+).*`)
matches := regex.FindStringSubmatch(strings.TrimSpace(value))
operator := ""
amountValue := ""
if len(matches) == 2 {
amountValue = matches[1]
} else if len(matches) == 3 {
operator = matches[1]
amountValue = matches[2]
}
amountValue = normalizeFloatString(amountValue)
targetPrice, err := strconv.ParseFloat(amountValue, 64)
if err != nil {
return "", 0, err
}
return operator, targetPrice, nil
}
// SetPriceAlert sets a price alert
func (ct *Cointop) SetPriceAlert(coinName string, operator string, targetPrice float64) error {
ct.debuglog("setPriceAlert()")
if operator == "" {
operator = "="
}
if _, ok := PriceAlertOperatorMap[operator]; !ok {
return errors.New("price alert operator is invalid")
}
frequency := "once"
id := strings.ToLower(fmt.Sprintf("%s_%s_%v_%s", coinName, operator, targetPrice, frequency))
newEntry := &PriceAlert{
ID: id,
CoinName: coinName,
Operator: operator,
TargetPrice: targetPrice,
Frequency: frequency,
}
if ct.State.priceAlertEditID == "" {
ct.State.priceAlerts.Entries = append([]*PriceAlert{newEntry}, ct.State.priceAlerts.Entries...)
} else {
for i, entry := range ct.State.priceAlerts.Entries {
if entry.ID == ct.State.priceAlertEditID {
ct.State.priceAlerts.Entries[i] = newEntry
}
}
}
if err := ct.Save(); err != nil {
return err
}
return nil
}
// ActivePriceAlerts returns the active price alerts
func (ct *Cointop) ActivePriceAlerts() []*PriceAlert {
var filtered []*PriceAlert
for _, entry := range ct.State.priceAlerts.Entries {
if entry.Expired {
continue
}
filtered = append(filtered, entry)
}
return filtered
}
// ActivePriceAlertsLen returns the number of active price alerts
func (ct *Cointop) ActivePriceAlertsLen() int {
return len(ct.ActivePriceAlerts())
}