-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
220 lines (191 loc) · 6.29 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
// Copyright (c) 2024 Neomantra Corp
//
// NOTE: this incurs billing, handle with care!
//
package main
import (
"fmt"
"io"
"os"
"strings"
"time"
dbn "github.com/NimbleMarkets/dbn-go"
dbn_live "github.com/NimbleMarkets/dbn-go/live"
"github.com/klauspost/compress/zstd"
"github.com/relvacode/iso8601"
"github.com/spf13/pflag"
)
///////////////////////////////////////////////////////////////////////////////
type Config struct {
OutFilename string
ApiKey string
Dataset string
STypeIn dbn.SType
Encoding dbn.Encoding
Schemas []string
Symbols []string
StartTime time.Time
Verbose bool
}
///////////////////////////////////////////////////////////////////////////////
func main() {
var err error
var config Config
var startTimeArg string
var showHelp bool
config.STypeIn = dbn.SType_RawSymbol
pflag.StringVarP(&config.Dataset, "dataset", "d", "", "Dataset to subscribe to ")
pflag.StringArrayVarP(&config.Schemas, "schema", "s", []string{}, "Schema to subscribe to (multiple allowed)")
pflag.StringVarP(&config.ApiKey, "key", "k", "", "Databento API key (or set 'DATABENTO_API_KEY' envvar)")
pflag.StringVarP(&config.OutFilename, "out", "o", "", "Output filename for DBN stream ('-' for stdout)")
pflag.VarP(&config.STypeIn, "sin", "i", "Input SType of the symbols. One of instrument_id, id, instr, raw_symbol, raw, smart, continuous, parent, nasdaq, cms")
pflag.VarP(&config.Encoding, "encoding", "e", "Encoding of the output ('dbn', 'csv', 'json')")
pflag.StringVarP(&startTimeArg, "start", "t", "", "Start time to request as ISO 8601 format (default: now)")
pflag.BoolVarP(&config.Verbose, "verbose", "v", false, "Verbose logging")
pflag.BoolVarP(&showHelp, "help", "h", false, "Show help")
pflag.Parse()
config.Symbols = pflag.Args()
if showHelp {
fmt.Fprintf(os.Stdout, "usage: %s -d <dataset> -s <schema> [opts] symbol1 symbol2 ...\n\n", os.Args[0])
pflag.PrintDefaults()
os.Exit(0)
}
if startTimeArg != "" {
config.StartTime, err = iso8601.ParseString(startTimeArg)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to parse --start as ISO 8601 time: %s\n", err.Error())
os.Exit(1)
}
}
if config.ApiKey == "" {
config.ApiKey = os.Getenv("DATABENTO_API_KEY")
requireValOrExit(config.ApiKey, "missing DataBento API key, use --key or set DATABENTO_API_KEY envvar\n")
}
if len(config.Schemas) == 0 {
fmt.Fprintf(os.Stderr, "requires at least --schema argument\n")
os.Exit(1)
}
if len(config.Symbols) == 0 {
fmt.Fprintf(os.Stderr, "requires at least one symbol argument\n")
os.Exit(1)
}
requireValOrExit(config.Dataset, "missing required --dataset")
requireValOrExit(config.OutFilename, "missing required --out")
if err := run(config); err != nil {
fmt.Fprintf(os.Stderr, "error: %s\n", err.Error())
os.Exit(1)
}
}
// requireValOrExit exits with an error message if `val` is empty.
func requireValOrExit(val string, errstr string) {
if val == "" {
fmt.Fprintf(os.Stderr, "%s\n", errstr)
os.Exit(1)
}
}
///////////////////////////////////////////////////////////////////////////////
func run(config Config) error {
// Create output file before connecting
outWriter, outCloser, err := makeCompressedWriter(config.OutFilename)
if err != nil {
return fmt.Errorf("failed to create output file: %w", err)
}
defer outCloser()
// Create and connect LiveClient
client, err := dbn_live.NewLiveClient(dbn_live.LiveConfig{
ApiKey: config.ApiKey,
Dataset: config.Dataset,
Encoding: config.Encoding,
SendTsOut: false,
VersionUpgradePolicy: dbn.VersionUpgradePolicy_AsIs,
Verbose: config.Verbose,
})
if err != nil {
return fmt.Errorf("failed to create LiveClient: %w", err)
}
defer client.Stop()
// Authenticate to server
if _, err = client.Authenticate(config.ApiKey); err != nil {
return fmt.Errorf("failed to authenticate LiveClient: %w", err)
}
// Subscribe
for _, schema := range config.Schemas {
subRequest := dbn_live.SubscriptionRequestMsg{
Schema: schema,
StypeIn: config.STypeIn,
Symbols: config.Symbols,
Start: config.StartTime,
Snapshot: false,
}
if err = client.Subscribe(subRequest); err != nil {
return fmt.Errorf("failed to subscribe LiveClient: %w", err)
}
}
// Start session
if _, err = client.Start(); err != nil {
return fmt.Errorf("failed to start LiveClient: %w", err)
}
// Write metadata to file
dbnScanner := client.GetDbnScanner()
if dbnScanner == nil {
return fmt.Errorf("failed to get DbnScanner from LiveClient")
}
metadata, err := dbnScanner.Metadata()
if err != nil {
return fmt.Errorf("failed to get metadata from LiveClient: %w", err)
}
if err = metadata.Write(outWriter); err != nil {
return fmt.Errorf("failed to write metadata from LiveClient: %w", err)
}
// Follow the DBN stream, writing DBN messages to the file
for dbnScanner.Next() {
recordBytes := dbnScanner.GetLastRecord()[:dbnScanner.GetLastSize()]
_, err := outWriter.Write(recordBytes)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to write record: %s\n", err.Error())
return err
}
}
if err := dbnScanner.Error(); err != nil && err != io.EOF {
fmt.Fprintf(os.Stderr, "scanner err: %s\n", err.Error())
return err
}
return nil
}
///////////////////////////////////////////////////////////////////////////////
// Compression helpers
// https://gist.github.com/neomantra/691a6028cdf2ac3fc6ec97d00e8ea802
// Returns an io.Writer for the given filename, or os.Stdout if filename is "-". Also returns a closing function to defer and any error.
// If the filename ends in ".zst" or ".zstd", the writer will zstd-compress the output.
func makeCompressedWriter(filename string) (io.Writer, func(), error) {
var writer io.Writer
var closer io.Closer
fileCloser := func() {
if closer != nil {
closer.Close()
}
}
if filename != "-" {
if file, err := os.Create(filename); err == nil {
writer, closer = file, file
} else {
return nil, nil, err
}
} else {
writer, closer = os.Stdout, nil
}
if strings.HasSuffix(filename, ".zst") || strings.HasSuffix(filename, ".zstd") {
zstdWriter, err := zstd.NewWriter(writer)
if err != nil {
fileCloser()
return nil, nil, err
}
zstdCloser := func() {
zstdWriter.Close()
fileCloser()
}
return zstdWriter, zstdCloser, nil
} else {
return writer, fileCloser, nil
}
}