-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprice_alert.go
95 lines (82 loc) · 2.17 KB
/
price_alert.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
package services
import (
"fmt"
"log"
"strconv"
"time"
"github.com/Jetlum/WalletAlertService/models"
"github.com/Jetlum/WalletAlertService/repository"
)
type PriceAlertService struct {
priceMonitor *PriceMonitor
alertRepo *repository.PriceAlertRepository
emailNotifier EmailNotifier
}
func NewPriceAlertService(
priceMonitor *PriceMonitor,
alertRepo *repository.PriceAlertRepository,
emailNotifier EmailNotifier,
) *PriceAlertService {
return &PriceAlertService{
priceMonitor: priceMonitor,
alertRepo: alertRepo,
emailNotifier: emailNotifier,
}
}
func (s *PriceAlertService) StartMonitoring() {
ticker := time.NewTicker(1 * time.Minute)
go func() {
for range ticker.C {
s.checkAlerts()
}
}()
}
func (s *PriceAlertService) checkAlerts() {
alerts, err := s.alertRepo.GetActiveAlerts()
if err != nil {
log.Printf("Error fetching active alerts: %v", err)
return
}
for _, alert := range alerts {
price, err := s.priceMonitor.GetPrice(alert.CryptocurrencyID)
if err != nil {
log.Printf("Error getting price for %s: %v", alert.CryptocurrencyID, err)
continue
}
threshold, _ := strconv.ParseFloat(alert.ThresholdPrice, 64)
if s.shouldTriggerAlert(price, threshold, alert.IsUpperBound) {
s.triggerAlert(&alert, price)
}
}
}
func (s *PriceAlertService) shouldTriggerAlert(currentPrice, threshold float64, isUpperBound bool) bool {
if isUpperBound {
return currentPrice >= threshold
}
return currentPrice <= threshold
}
func (s *PriceAlertService) triggerAlert(alert *models.PriceAlert, currentPrice float64) {
message := fmt.Sprintf(
"Price Alert: %s has reached $%.2f (Threshold: $%s)",
alert.CryptocurrencyID,
currentPrice,
alert.ThresholdPrice,
)
if alert.EmailNotification {
event := &models.Event{
EventType: "PRICE_ALERT",
Value: fmt.Sprintf("%.2f", currentPrice),
Message: message,
FromAddress: "PriceAlert",
ToAddress: alert.UserID,
Notified: false,
}
userPref := &models.UserPreference{
UserID: alert.UserID,
EmailNotification: true,
}
if err := s.emailNotifier.Send(event, userPref); err != nil {
log.Printf("Failed to send price alert email: %v", err)
}
}
}