-
Notifications
You must be signed in to change notification settings - Fork 4
/
rates.go
103 lines (88 loc) · 2.41 KB
/
rates.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
package main
import (
"fmt"
"log"
"time"
ws "github.com/aopoltorzhicky/go_kraken/websocket"
)
type RatesClient interface {
Subscribe() error
MarketPrice(base, quote string) (float64, error)
FeePercentage(base, quote string) float64
}
type Rates struct {
Client RatesClient
}
type KrakenClient struct {
ws *ws.Kraken
PriceStreams map[string]chan float64
LastPrices map[string]float64
}
func NewKrakenClient() *KrakenClient {
kraken := ws.NewKraken(ws.ProdBaseURL)
if err := kraken.Connect(); err != nil {
log.Fatalf("Error connecting to web socket: %s", err.Error())
}
return &KrakenClient{
ws: kraken,
PriceStreams: make(map[string]chan float64),
LastPrices: make(map[string]float64),
}
}
func (kc *KrakenClient) FeePercentage(base, quote string) float64 {
// Set a fixed fee percentage
const feePercentage = 1 // 1% fee
return feePercentage
}
func (kc *KrakenClient) MarketPrice(base, quote string) (float64, error) {
marketPair := base + "/" + quote
price, ok := kc.LastPrices[marketPair]
if !ok {
return 0, fmt.Errorf("no price available for market pair: %s", marketPair)
}
return price, nil
}
func (kc *KrakenClient) Subscribe() error {
// Initialize the map
kc.PriceStreams = make(map[string]chan float64)
// Create channels to stream the market prices
kc.PriceStreams["L-BTC/USDT"] = make(chan float64)
kc.PriceStreams["L-BTC/L-BTC"] = make(chan float64)
// Start a goroutine for each market pair to read from the WebSocket and update the last price
for marketPair, priceStream := range kc.PriceStreams {
go func(marketPair string, priceStream chan float64) {
for price := range priceStream {
kc.LastPrices[marketPair] = price
}
}(marketPair, priceStream)
}
// XBT/USDT
// Subscribe to ticker information for the trading pair
if err := kc.ws.SubscribeTicker([]string{ws.BTCUSDT}); err != nil {
return fmt.Errorf("SubscribeTicker error: %s", err.Error())
}
go func() {
defer close(kc.PriceStreams["L-BTC/USDT"])
for update := range kc.ws.Listen() {
switch data := update.Data.(type) {
case ws.TickerUpdate:
price, err := data.Ask.Price.Float64()
if err != nil {
log.Println("Error parsing price:", err)
continue
}
kc.PriceStreams["L-BTC/USDT"] <- price
default:
return
}
}
}()
// L-BTC/L-BTC
go func() {
for {
kc.PriceStreams["L-BTC/L-BTC"] <- 1.00
time.Sleep(1 * time.Second)
}
}()
return nil
}