-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmain.go
324 lines (278 loc) · 7.14 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
// Downloads market data from IQFeed into CSV or TSV files
package main
import (
"fmt"
"github.com/apex/log"
clilog "github.com/apex/log/handlers/cli"
"github.com/apex/log/handlers/text"
"gopkg.in/urfave/cli.v1"
"io/ioutil"
"os"
"strconv"
"strings"
"sync"
)
type Config struct {
protocol string
command string
startDate string
endDate string
outDirectory string
timeZone string
intervalType string
intervalLength int
parallelism int
tsv bool
detailedLogging bool
gzip bool
endTimestamp bool
useLabels bool
}
var (
newProtocol = "6.0"
config = Config{
protocol: "5.1",
command: "",
startDate: "",
endDate: "",
outDirectory: "data",
timeZone: "ET",
intervalType: "",
intervalLength: 0,
parallelism: 8,
tsv: false,
detailedLogging: false,
gzip: false,
endTimestamp: false,
useLabels: false,
}
)
func detailedLoggingEnabled(args []string) bool {
for _, arg := range args {
if arg == "-d" || arg == "--detailed-logging" {
return true
}
}
return false
}
func main() {
detailedLogging := detailedLoggingEnabled(os.Args)
setupLogging(detailedLogging)
app := cli.NewApp()
app.Name = "qdownload"
app.Usage = "downloads historic market data from IQFeed"
app.Version = "1.0.0"
app.HideVersion = true
app.ArgsUsage = "<symbols or symbols file>"
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "start, s",
Value: "",
Usage: "start date filter: yyyymmdd",
Destination: &config.startDate,
},
cli.StringFlag{
Name: "end, e",
Value: "",
Usage: "end date filter: yyyymmdd",
Destination: &config.endDate,
},
cli.StringFlag{
Name: "out, o",
Value: "data",
Usage: "output directory",
Destination: &config.outDirectory,
},
cli.StringFlag{
Name: "timezone, z",
Value: "ET",
Usage: "timestamps time zone",
Destination: &config.timeZone,
},
cli.IntFlag{
Name: "parallelism, p",
Value: 8,
Usage: "number of parallel downloads",
Destination: &config.parallelism,
},
cli.BoolFlag{
Name: "tsv, t",
Usage: "use tab separator instead of comma",
Destination: &config.tsv,
},
cli.BoolFlag{
Name: "detailed-logging, d",
Usage: "detailed log output",
Destination: &config.detailedLogging,
},
cli.BoolFlag{
Name: "gzip, g",
Usage: "compress files with gzip",
Destination: &config.gzip,
},
cli.BoolFlag{
Name: "end-timestamp, m",
Usage: "use end of bar timestamps instead of start",
Destination: &config.endTimestamp,
},
}
app.Commands = []cli.Command{
{
Name: "eod",
Usage: "Download EOD bars",
Action: runCommand,
},
{
Name: "minute",
Usage: "Download minute bars",
Action: runCommand,
},
{
Name: "tick",
Usage: "Download tick data",
Action: runCommand,
},
{
Name: "interval",
Usage: "Download interval bars: <length> <seconds|volume|ticks>",
Action: runCommand,
ArgsUsage: "<length> <type>",
Before: func(c *cli.Context) error {
if len(c.Args()) < 3 {
return fmt.Errorf("incorrect number of interval parameters: %d", len(c.Args()))
}
config.intervalType = c.Args()[1]
intervalLength, err := strconv.Atoi(c.Args()[0])
config.intervalLength = intervalLength
if config.intervalLength <= 0 {
err = fmt.Errorf("incorrect interval length: %s", c.Args()[0])
} else {
err = mapIntervalType(config.intervalType, &config.intervalType)
}
if !config.endTimestamp {
log.Infof("Using newer protocol required for bar start timestamps, "+
"requiring at least IQFeed %s", newProtocol)
config.protocol = newProtocol
config.useLabels = true
}
return err
},
},
}
app.Action = showUsageWhenMissingCommand
err := app.Run(os.Args)
if err != nil {
log.WithError(err).Error("Application error")
}
}
func mapIntervalType(argument string, intervalType *string) error {
arg := strings.ToUpper(argument)
if strings.HasPrefix(arg, "S") {
*intervalType = "S"
} else if strings.HasPrefix(arg, "V") {
*intervalType = "V"
} else if strings.HasPrefix(arg, "T") {
*intervalType = "T"
} else {
return fmt.Errorf("incorrect interval type: %s", argument)
}
return nil
}
func showUsageWhenMissingCommand(c *cli.Context) error {
return showUsageWithError(c, "Command argument is missing")
}
func showUsageWithError(c *cli.Context, message string) error {
_ = cli.ShowAppHelp(c)
fmt.Println("")
return cli.NewExitError(fmt.Sprintf("ERROR: %s", message), 2)
}
func runCommand(c *cli.Context) error {
if c.NArg() == 0 {
return showUsageWithError(c, "Comma separated symbols or symbols filename argument missing")
}
config.command = c.Command.Name
createOutDirectory(config.outDirectory)
symbols, err := getSymbols(c.Args()[len(c.Args())-1])
if err != nil {
return err
}
wg := start(symbols, &config)
wg.Wait()
return nil
}
func setupLogging(detailedLogging bool) {
if detailedLogging {
log.SetHandler(text.New(os.Stderr))
log.SetLevel(log.DebugLevel)
} else {
log.SetHandler(clilog.New(os.Stderr))
}
}
func createOutDirectory(outDirectory string) {
err := os.MkdirAll(outDirectory, os.ModePerm)
if err != nil {
panic(err)
}
}
func getSymbols(symbolsOrSymbolsFile string) ([]string, error) {
var symbols []string
if strings.Contains(symbolsOrSymbolsFile, ",") || !fileExists(symbolsOrSymbolsFile) {
symbols = strings.Split(symbolsOrSymbolsFile, ",")
} else {
content, err := ioutil.ReadFile(symbolsOrSymbolsFile)
if err != nil {
return nil, err
}
textContent := string(content)
symbols = strings.Split(string(textContent), "\n")
}
var sanitizedSymbols []string
for _, symbol := range symbols {
symbol = strings.Trim(symbol, " \r")
if symbol != "" {
sanitizedSymbols = append(sanitizedSymbols, symbol)
}
}
log.WithFields(log.Fields{"symbols": len(sanitizedSymbols)}).Info("Read symbols")
return sanitizedSymbols, nil
}
func start(symbols []string, config *Config) *sync.WaitGroup {
symbolsQueue := make(chan string, len(symbols))
for _, symbol := range symbols {
symbolsQueue <- symbol
}
close(symbolsQueue)
downloadFunc := getDownloadCommandFunction()
wg := sync.WaitGroup{}
log.Debug("Starting downloaders")
for i := 0; i < config.parallelism; i++ {
go downloader(symbolsQueue, &wg, config, downloadFunc)
wg.Add(1)
}
return &wg
}
func getDownloadCommandFunction() DownloadFunc {
switch strings.ToLower(config.command) {
case "eod":
return DownloadEod
case "minute":
return DownloadMinute
case "tick":
return DownloadTicks
case "interval":
return DownloadInterval
}
log.Fatalf("Unsupported download function: %s", config.command)
return nil
}
func downloader(symbolsQueue <-chan string, wg *sync.WaitGroup, config *Config, downloadFunc DownloadFunc) {
log.Debug("Downloader started")
for symbol := range symbolsQueue {
downloadFunc(symbol, config)
}
wg.Done()
}
func fileExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}