-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
193 lines (151 loc) · 3.95 KB
/
main.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
package main
import (
"log"
"time"
"flag"
"net/url"
"strings"
"net/http"
"encoding/json"
"strconv"
"sync"
)
const defDuration = 5 * time.Second
const defUpdateURL = "https://wex.nz/api/3/ticker/"
const defPairsURL = "https://wex.nz/api/3/info/"
const defEndpointURL = "/"
const defTimeFrame = 10 * time.Minute
const defPort = 3512
type Config struct {
UpdateDuration time.Duration
UpdateURL url.URL
EndpointURL url.URL
TimeFrame time.Duration
Pairs []string
Port int
}
type Rate struct {
Pair string
Value float64
}
type RateTime struct {
Rate Rate
Time time.Time
}
type Averages = sync.Map
func RunUpdater(url url.URL, duration time.Duration, pairs []string) (<-chan RateTime) {
ch := make(chan RateTime)
go func() () {
defer close(ch)
t := time.NewTicker(duration)
for {
for i := range pairs {
go APIGetStatsForPair(ch, pairs[i], url)
}
<-t.C
}
}()
return ch
}
func RunCalculator(chIn <-chan RateTime, chSignal <-chan struct{}, timeSpan time.Duration) (<-chan Averages) {
curAverage := Averages{}
queue := map[string][]float64{}
timeStarted := time.Now()
ch := make(chan Averages)
go func() () {
defer close(ch)
for {
select {
case rateTime := <-chIn:
r := rateTime.Rate
UpdateAverages(
r.Pair,
r.Value,
&queue,
&curAverage,
rateTime.Time.Sub(timeStarted) <= timeSpan,
)
case <-chSignal:
ch <- curAverage
}
}
}()
return ch
}
func Handler(chSignal chan<- struct{}, chOut <-chan Averages, w http.ResponseWriter) () {
chSignal <- struct{}{}
averages := <-chOut
strAverages := map[string]float64{}
averages.Range(func(k, v interface{}) bool {
strAverages[k.(string)] = v.(float64)
return true
})
js, err := json.Marshal(strAverages)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
func InitConfig() (*Config, error) {
duration := flag.Duration("update_duration", defDuration, "how often rates are updated")
pairsURLStr := flag.String("get_pairs_url", defPairsURL, "URL to get pairs information")
updateURLStr := flag.String("update_url", defUpdateURL, "URL to update rates for pair")
endpointURLStr := flag.String("api_endpoint", defEndpointURL, "API endpoint to request average rates")
timeFrame := flag.Duration("timeframe", defTimeFrame, "time interval to use for moving averages")
pairsStr := flag.String("pairs", "", "comma separated currency pairs : btc_usd, eth_eur, xrp_btc")
port := flag.Int("port", defPort, "port for connections")
flag.Parse()
pairsURL, err := url.Parse(*pairsURLStr)
if err != nil {
pairsURL, _ = url.Parse(defPairsURL)
}
updateURL, err := url.Parse(*updateURLStr)
if err != nil {
updateURL, _ = url.Parse(defUpdateURL)
}
endpointURL, err := url.Parse(*endpointURLStr)
if err != nil {
endpointURL, _ = url.Parse(defEndpointURL)
}
var pairs []string
if len(*pairsStr) > 0 {
pairs = strings.Split(*pairsStr, ",")
}
//If no pairs provided, we get all from API
if 0 == len(pairs) {
pairs, err = APIGetAllPairs(*pairsURL)
if err != nil {
return nil, err
}
}
return &Config{
*duration,
*updateURL,
*endpointURL,
*timeFrame,
pairs,
*port,
}, nil
}
func main() {
log.Println("Service started")
config, err := InitConfig()
if err != nil {
log.Fatalf("unable to load currency pairs, error: %v", err)
}
confStr, err := json.MarshalIndent(config, "", " ")
if err != nil {
log.Printf("error while unmarshalling config: %v", err)
}
log.Printf("Config initialized: %s", confStr)
ch := RunUpdater(config.UpdateURL, config.UpdateDuration, config.Pairs)
chSignal := make(chan struct{})
defer close(chSignal)
chOut := RunCalculator(ch, chSignal, config.TimeFrame)
http.HandleFunc(config.EndpointURL.Path, func(w http.ResponseWriter, r *http.Request) {
Handler(chSignal, chOut, w)
})
log.Fatal(http.ListenAndServe(":"+strconv.Itoa(config.Port), nil))
}