Skip to content

Commit 49b0cf6

Browse files
committed
Create new service for cryptocurrency price monitoring
1 parent e216e8a commit 49b0cf6

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

services/price_monitor.go

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package services
2+
3+
import (
4+
"encoding/json"
5+
"fmt"
6+
"net/http"
7+
"sync"
8+
"time"
9+
)
10+
11+
type PriceMonitor struct {
12+
apiKey string
13+
httpClient *http.Client
14+
prices sync.Map
15+
}
16+
17+
type CoinGeckoPrice struct {
18+
Bitcoin struct {
19+
USD float64 `json:"usd"`
20+
} `json:"bitcoin"`
21+
Ethereum struct {
22+
USD float64 `json:"ethereum"`
23+
} `json:"ethereum"`
24+
}
25+
26+
func NewPriceMonitor(apiKey string) *PriceMonitor {
27+
return &PriceMonitor{
28+
apiKey: apiKey,
29+
httpClient: &http.Client{
30+
Timeout: 10 * time.Second,
31+
},
32+
}
33+
}
34+
35+
func (pm *PriceMonitor) StartMonitoring(checkInterval time.Duration) {
36+
ticker := time.NewTicker(checkInterval)
37+
go func() {
38+
for range ticker.C {
39+
pm.updatePrices()
40+
}
41+
}()
42+
}
43+
44+
func (pm *PriceMonitor) updatePrices() error {
45+
url := fmt.Sprintf("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum&vs_currencies=usd")
46+
resp, err := pm.httpClient.Get(url)
47+
if err != nil {
48+
return fmt.Errorf("failed to fetch prices: %w", err)
49+
}
50+
defer resp.Body.Close()
51+
52+
var prices CoinGeckoPrice
53+
if err := json.NewDecoder(resp.Body).Decode(&prices); err != nil {
54+
return fmt.Errorf("failed to decode response: %w", err)
55+
}
56+
57+
pm.prices.Store("BTC", prices.Bitcoin.USD)
58+
pm.prices.Store("ETH", prices.Ethereum.USD)
59+
return nil
60+
}
61+
62+
func (pm *PriceMonitor) GetPrice(cryptoID string) (float64, error) {
63+
price, ok := pm.prices.Load(cryptoID)
64+
if !ok {
65+
return 0, fmt.Errorf("price not available for %s", cryptoID)
66+
}
67+
return price.(float64), nil
68+
}

0 commit comments

Comments
 (0)