forked from polyrabbit/my-token
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
326 lines (295 loc) 路 10.1 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
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
package main
import (
"fmt"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"encoding/json"
"github.com/fatih/color"
"github.com/gosuri/uilive"
"github.com/mattn/go-colorable"
"github.com/olekukonko/tablewriter"
. "github.com/maurodelazeri/token-ticker/exchange"
"github.com/sirupsen/logrus"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"math"
)
// Will be set by go-build
var (
Version string
Rev string
)
type exchangeConfig struct {
Name string
Tokens []string
}
// Return a slice of waiting chans, each of them represents a pending request
func requestSymbolPrice(client ExchangeClient, symbols []string) []chan *SymbolPrice {
// Use slice to hold the waiting chans in order to keep requested order
waitingChans := make([]chan *SymbolPrice, len(symbols))
for i, symbol := range symbols {
done := make(chan *SymbolPrice, 1)
waitingChans[i] = done
go func(symbol string) {
sp, err := client.GetSymbolPrice(symbol)
if err != nil {
logrus.Warnf("Failed to get symbol price for %s from %s, error: %s", symbol, client.GetName(), err)
if strings.Contains(err.Error(), "i/o timeout") {
logrus.Info("Maybe you are blocked by a firewall, try using --proxy to go through a proxy?")
}
close(done) // close channel to indicate an error has happened, any other good idea?
} else {
done <- sp
}
}(symbol)
}
return waitingChans
}
func checkForUpdate(httpClient *http.Client) {
releaseUrl := "https://api.github.com/repos/maurodelazeri/token-ticker/releases/latest"
resp, err := httpClient.Get(releaseUrl)
if err != nil {
logrus.Debugf("Failed to fetch Github release page, error %s", err)
return
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
var releaseJSON struct {
Tag string `json:"tag_name"`
Url string `json:"html_url"`
}
if err := decoder.Decode(&releaseJSON); err != nil {
logrus.Debugf("Failed to decode Github release page JSON, error %s", err)
return
}
if releaseJSON.Tag == "" {
logrus.Debugf("Get an empty release tag?")
return
}
releaseJSON.Tag = strings.TrimPrefix(releaseJSON.Tag, "v")
logrus.Debugf("Latest release tag is %s", releaseJSON.Tag)
if Version != "" && releaseJSON.Tag != Version {
color.New(color.FgYellow).Fprintf(os.Stderr, "You are using version %s, however version %s is available.\n",
Version, releaseJSON.Tag)
color.New(color.FgYellow).Fprintf(os.Stderr, "You should consider getting the latest release from '%s'.\n",
releaseJSON.Url)
}
}
var (
faint = color.New(color.Faint).SprintFunc()
)
func highlightChange(changePct float64) string {
if changePct == math.MaxFloat64 {
return ""
}
changeText := strconv.FormatFloat(changePct, 'f', 2, 64)
if changePct == 0 {
changeText = faint("0")
} else if changePct > 0 {
changeText = color.GreenString(changeText)
} else {
changeText = color.RedString(changeText)
}
return changeText
}
func renderTable(symbolPriceList []*SymbolPrice, writer *uilive.Writer) {
// Set up ascii table writer
table := tablewriter.NewWriter(writer)
table.SetAutoFormatHeaders(false)
table.SetAutoWrapText(false)
headers := []string{color.YellowString("Symbol"), color.YellowString("Price"),
color.YellowString("%Change(1h)"), color.YellowString("%Change(24h)"),
color.YellowString("Source"), color.YellowString("Updated")}
table.SetHeader(headers)
table.SetRowLine(true)
table.SetCenterSeparator(faint("-"))
table.SetColumnSeparator(faint("|"))
table.SetRowSeparator(faint("-"))
// Fill in data
for _, sp := range symbolPriceList {
table.Append([]string{sp.Symbol, sp.Price, highlightChange(sp.PercentChange1h),
highlightChange(sp.PercentChange24h), sp.Source, sp.UpdateAt.Local().Format("15:04:05")})
}
table.Render()
writer.Flush()
}
func newHttpClient(rawProxyUrl string) *http.Client {
transport := http.DefaultTransport.(*http.Transport)
if rawProxyUrl != "" {
proxyUrl, err := url.Parse(rawProxyUrl)
if err != nil {
logrus.Warnf("Failed to parse proxy URL: %s, error: %v, using system proxy\n", rawProxyUrl, err)
} else {
transportWithProxy := *transport // Copy the default transport
transportWithProxy.Proxy = http.ProxyURL(proxyUrl) // Set custom proxy
transport = &transportWithProxy
logrus.Debugf("Using proxy %s", rawProxyUrl)
}
}
logrus.Debugf("HTTP request timeout is set to %d", viper.GetInt("timeout"))
return &http.Client{
Transport: transport,
Timeout: time.Duration(viper.GetInt("timeout")) * time.Second,
}
}
func showUsageAndExit() {
// Print usage message and exit
fmt.Fprintf(os.Stderr, "\nUsage: %s [Options] [Exchange1.Token1 Exchange2.Token2 ...]\n", os.Args[0])
fmt.Fprintln(os.Stderr, "\nTrack token prices of your favorite exchanges in the terminal")
fmt.Fprintln(os.Stderr, "\nOptions:")
pflag.PrintDefaults()
fmt.Fprintln(os.Stderr, "\nExchange.Token Pairs:")
fmt.Fprintln(os.Stderr, " Specify which exchange and token pair to query, different exchanges use different forms to express tokens/trading pairs, refer to their URLs to find the format"+
" (eg. to get BitCoin price from Bitfinex and CoinMarketCap you should use query string \"Bitfinex.BTCUSDT CoinMarketCap.Bitcoin\").")
fmt.Fprintln(os.Stderr, "\nFind help/updates from here - https://github.com/maurodelazeri/token-ticker")
os.Exit(0)
}
func init() {
// Set log format
formatter := &logrus.TextFormatter{
FullTimestamp: true,
TimestampFormat: "15:04:05",
}
logrus.SetFormatter(formatter)
logrus.SetOutput(colorable.NewColorableStderr()) // For Windows
showVersion := pflag.BoolP("version", "v", false, "Show version number")
showHelp := pflag.BoolP("help", "h", false, "Show usage message")
pflag.CommandLine.MarkHidden("help")
pflag.BoolP("debug", "d", false, "Enable debug mode")
showList := pflag.BoolP("list-exchanges", "l", false, "List supported exchanges")
pflag.IntP("refresh", "r", 0, "Auto refresh on every specified seconds, "+
"note every exchange has a rate limit, \ntoo frequent refresh may cause your IP banned by their servers")
var configFile string
pflag.StringVarP(&configFile, "config-file", "c", "", "Config file path, "+
"refer to \"token_ticker.example.yaml\" for the format, \nby default token-ticker uses \"token_ticker.yml\" "+
"in current directory or $HOME as config file")
pflag.StringP("proxy", "p", "", "Proxy used when sending HTTP request \n(eg. "+
"\"http://localhost:7777\", \"https://localhost:7777\", \"socks5://localhost:1080\")")
pflag.IntP("timeout", "t", 20, "HTTP request timeout in seconds")
pflag.CommandLine.SortFlags = false
pflag.Usage = showUsageAndExit
pflag.Parse()
if *showHelp {
showUsageAndExit()
}
if *showVersion {
fmt.Fprintf(os.Stderr, "Version %s", Version)
if Rev != "" {
fmt.Fprintf(os.Stderr, ", build %s", Rev)
}
fmt.Fprintln(os.Stderr)
os.Exit(0)
}
if *showList {
fmt.Fprintln(os.Stderr, "Supported exchanges:")
for _, name := range ListExchanges() {
fmt.Fprintf(os.Stderr, " %s\n", name)
}
os.Exit(0)
}
viper.BindPFlags(pflag.CommandLine)
// Set configure file
viper.SetConfigName("token_ticker") // name of config file (without extension)
viper.AddConfigPath(".") // path to look for the config file in
viper.AddConfigPath("$HOME") // optionally look for config in the HOME directory
viper.AddConfigPath("/etc") // and /etc
if configFile != "" {
viper.SetConfigFile(configFile)
}
err := viper.ReadInConfig() // Find and read the config file
if err != nil {
switch err.(type) {
case viper.ConfigFileNotFoundError:
if pflag.NArg() == 0 { // And no specified tokens
showUsageAndExit()
}
default:
logrus.Warnf("Error reading config file: %s\n", err)
}
}
if viper.GetBool("debug") {
logrus.SetLevel(logrus.DebugLevel)
}
logrus.Debugln("Using config file:", viper.ConfigFileUsed())
}
func getSymbolPrice(exchanges []*exchangeConfig, httpClient *http.Client) []*SymbolPrice {
// Loop all exchanges from config
var waitingChanList []chan *SymbolPrice
for _, exchangeCfg := range exchanges {
var client = CreateExchangeClient(exchangeCfg.Name, httpClient)
if client == nil {
logrus.Warnf("Unknown exchange %s, skipping", exchangeCfg.Name)
continue
}
pendings := requestSymbolPrice(client, exchangeCfg.Tokens)
waitingChanList = append(waitingChanList, pendings...)
}
var symbolPriceList []*SymbolPrice
for _, done := range waitingChanList {
sp := <-done
if sp != nil {
symbolPriceList = append(symbolPriceList, sp)
}
}
return symbolPriceList
}
func buildExchangeFromCLI(cliArgs []string) []*exchangeConfig {
var (
lastExchangeDef = &exchangeConfig{}
exchangeList []*exchangeConfig
)
for _, arg := range cliArgs {
tokenDef := strings.SplitN(arg, ".", 2)
if len(tokenDef) != 2 {
logrus.Fatalf("Unrecognized token definition - %s, expecting {exchange}.{token}", arg)
}
if lastExchangeDef.Name == tokenDef[0] {
// Merge consecutive exchange definitions
// Do not sort/reorder here, to remain the order user specified
lastExchangeDef.Tokens = append(lastExchangeDef.Tokens, tokenDef[1])
} else {
exchangeDef := &exchangeConfig{
Name: tokenDef[0],
Tokens: []string{tokenDef[1]}}
lastExchangeDef = exchangeDef
exchangeList = append(exchangeList, exchangeDef)
}
}
return exchangeList
}
func main() {
var configs []*exchangeConfig
if pflag.NArg() != 0 {
// Construct exchange from command-line
configs = buildExchangeFromCLI(pflag.Args())
} else {
// Read from config file
err := viper.UnmarshalKey("exchanges", &configs)
if err != nil {
logrus.Fatalf("Unable to decode config file, %v", err)
}
}
refreshInterval := viper.GetInt("refresh")
if refreshInterval != 0 {
logrus.Infof("Auto refresh on every %d seconds", refreshInterval)
}
httpClient := newHttpClient(viper.GetString("proxy"))
go checkForUpdate(httpClient)
var writer = uilive.New()
writer.Out = colorable.NewColorableStdout() // For Windows
logrus.SetOutput(writer)
defer logrus.SetOutput(colorable.NewColorableStderr())
for {
symbolPriceList := getSymbolPrice(configs, httpClient)
renderTable(symbolPriceList, writer)
if refreshInterval == 0 {
break
}
// Use sleep here so I can stall as much as I can to avoid exceeding API limit
time.Sleep(time.Duration(refreshInterval) * time.Second)
}
}