-
Notifications
You must be signed in to change notification settings - Fork 19
/
stock_candles.go
85 lines (75 loc) · 1.73 KB
/
stock_candles.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
package traderdb
import (
"context"
"github.com/jackc/pgx/v4"
"time"
)
type Candle struct {
OpenedAt time.Time
OpenMicros int64
HighMicros int64
LowMicros int64
CloseMicros int64
Volume int64
}
const stockCandlesQuery = `
SELECT opened_at, open_micros, high_micros, low_micros, close_micros, volume FROM stock_candles
WHERE stock_id = $1
ORDER BY opened_at
`
func GetTradingHourStockCandles(conn *pgx.Conn, symbol string) (candles []Candle, err error) {
var stockId int
err = conn.QueryRow(
context.Background(),
"SELECT id FROM stocks WHERE symbol = $1",
symbol,
).Scan(&stockId)
if err != nil {
return candles, err
}
location, err := time.LoadLocation("America/New_York")
if err != nil {
return candles, err
}
rows, err := conn.Query(context.Background(), stockCandlesQuery, stockId)
if err != nil {
return candles, err
}
defer rows.Close()
for rows.Next() {
var openMicros int64
var highMicros int64
var lowMicros int64
var closeMicros int64
var volume int64
var openedAt time.Time
if err = rows.Scan(
&openedAt, &openMicros, &highMicros, &lowMicros, &closeMicros, &volume,
); err != nil {
return candles, err
}
openedAt = openedAt.In(location)
if IsWithinNATradingHours(openedAt) {
candles = append(candles, Candle{
OpenedAt: openedAt,
OpenMicros: openMicros,
HighMicros: highMicros,
LowMicros: lowMicros,
CloseMicros: closeMicros,
Volume: volume,
})
}
}
if err = rows.Err(); err != nil {
return candles, err
}
return candles, nil
}
// Assuming location = "America/New_York"
func IsWithinNATradingHours(moment time.Time) bool {
hour, minute, _ := moment.Clock()
if hour == 9 {
return minute >= 30
}
return hour > 9 && hour < 16
}