/
main.go
158 lines (130 loc) · 3.74 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
package main
import (
"fmt"
"log"
"os"
"os/signal"
"strconv"
"syscall"
"code.cryptowat.ch/cw-sdk-go/client/rest"
"code.cryptowat.ch/cw-sdk-go/client/websocket"
"code.cryptowat.ch/cw-sdk-go/common"
"code.cryptowat.ch/cw-sdk-go/config"
flag "github.com/spf13/pflag"
)
func main() {
// We need this since getting user's home dir can fail.
defaultConfig, err := config.DefaultFilepath()
if err != nil {
log.Print(err)
os.Exit(1)
}
var (
configFile string
verbose bool
)
flag.StringVarP(&configFile, "config", "c", defaultConfig, "Configuration file")
flag.BoolVarP(&verbose, "verbose", "v", false, "Prints all debug messages to stdout")
flag.Parse()
cfg, err := config.New(configFile)
if err != nil {
log.Print(err)
os.Exit(1)
}
if err := cfg.Validate(); err != nil {
log.Print(err)
os.Exit(1)
}
restclient := rest.NewCWRESTClient(nil)
// Get exchange description, in particular we'll need the ID to use it
// in stream subscriptions.
// Get market descriptions, to know symbols (like "btcusd") by integer ID.
marketsSlice, err := restclient.GetMarketsIndex()
if err != nil {
log.Printf("failed to get markets: %s", err)
os.Exit(1)
}
markets := map[common.MarketID]rest.MarketDescr{}
for _, market := range marketsSlice {
markets[common.MarketID(strconv.Itoa(market.ID))] = market
}
// Create a new stream connection instance. Note that the actual connection
// will happen later.
c, err := websocket.NewStreamClient(&websocket.StreamClientParams{
WSParams: &websocket.WSParams{
URL: cfg.StreamURL,
APIKey: cfg.APIKey,
SecretKey: cfg.SecretKey,
},
Subscriptions: []*websocket.StreamSubscription{
&websocket.StreamSubscription{
Resource: "markets:*:trades",
},
},
})
if err != nil {
log.Print(err)
os.Exit(1)
}
c.OnSubscriptionResult(func(sr websocket.SubscriptionResult) {
log.Println(sr)
})
if verbose {
lastErrChan := make(chan error, 1)
c.OnError(func(err error, disconnecting bool) {
if disconnecting {
lastErrChan <- err
return
}
log.Printf("Error: %s", err)
})
// Ask for the state transition updates, and present them to the user somehow.
c.OnStateChange(
websocket.ConnStateAny,
func(oldState, state websocket.ConnState) {
select {
case err := <-lastErrChan:
if err != nil {
log.Printf("State updated: %s -> %s: %s", websocket.ConnStateNames[oldState], websocket.ConnStateNames[state], err)
} else {
log.Printf("State updated: %s -> %s", websocket.ConnStateNames[oldState], websocket.ConnStateNames[state])
}
default:
log.Printf("State updated: %s -> %s", websocket.ConnStateNames[oldState], websocket.ConnStateNames[state])
}
},
)
}
// Listen for received market messages and print them.
c.OnMarketUpdate(func(market common.Market, md common.MarketUpdate) {
if md.TradesUpdate == nil {
return
}
tradesUpdate := md.TradesUpdate
for _, trade := range tradesUpdate.Trades {
log.Printf(
"%-25s %-25s %-25s %-25s",
fmt.Sprintf("Exchange: %s (%s)", market.ExchangeID, markets[market.ID].Exchange),
fmt.Sprintf("Pair: %s (%s)", market.CurrencyPairID, markets[market.ID].Pair),
fmt.Sprintf("Price: %s", trade.Price),
fmt.Sprintf("Amount: %s", trade.Amount),
)
}
})
if verbose {
log.Printf("Connecting to %s ...", c.URL())
}
// Finally, connect.
if err := c.Connect(); err != nil {
log.Print(err)
os.Exit(1)
}
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)
// Wait until the OS signal is received, at which point we'll close the connection and quit.
<-signals
log.Print("Closing connection...")
if err := c.Close(); err != nil {
log.Printf("Failed to close connection: %s", err)
}
}