-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
117 lines (99 loc) · 1.97 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
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"time"
"github.com/gorilla/websocket"
"github.com/urfave/cli"
)
const (
FINNHUB_STREAM_URL = "wss://ws.finnhub.io?token=%s"
)
func run(ctx *cli.Context) error {
token := ctx.String("token")
if token == "" {
return errors.New("must provide a token")
}
c, _, err := websocket.DefaultDialer.Dial(fmt.Sprintf(FINNHUB_STREAM_URL, token), nil)
if err != nil {
return err
}
defer c.Close()
done := make(chan struct{})
go func() {
defer close(done)
for {
messageType, message, err := c.ReadMessage()
if err != nil {
return
}
if messageType != websocket.TextMessage {
continue
}
var data map[string]interface{}
err = json.Unmarshal(message, &data)
if err != nil {
panic(err)
}
if data["type"] == "ping" {
c.WriteJSON(map[string]interface{}{
"type": "pong",
})
} else if data["type"] == "trade" {
for _, trade := range data["data"].([]interface{}) {
serialized, err := json.Marshal(trade)
if err != nil {
panic(err)
}
os.Stdout.Write(append(serialized, '\r', '\n'))
}
}
if _, ok := data[""]; ok {
continue
}
}
}()
go func() {
ticker := time.NewTicker(time.Second * 60)
for _, symbol := range ctx.StringSlice("symbol") {
c.WriteJSON(map[string]interface{}{
"type": "subscribe",
"symbol": symbol,
})
}
for {
select {
case <-done:
return
case <-ticker.C:
c.WriteMessage(websocket.PingMessage, nil)
}
}
}()
<-done
return nil
}
func main() {
app := &cli.App{
Name: "finnhub-trade-tail",
Usage: "tail trade data from the finnhub streaming api",
Action: run,
Flags: []cli.Flag{
&cli.StringSliceFlag{
Name: "symbol",
Usage: "a symbol to subscribe too",
},
&cli.StringFlag{
Name: "token",
Usage: "finnhub api token",
EnvVar: "FINNHUB_TOKEN",
},
},
}
err := app.Run(os.Args)
if err != nil {
fmt.Printf("error: %v\n", err)
}
}