-
Notifications
You must be signed in to change notification settings - Fork 0
/
actions_prices_history.go
105 lines (91 loc) · 2.45 KB
/
actions_prices_history.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
package horizon
import (
"time"
"gitlab.com/tokend/horizon/db2/history"
"gitlab.com/tokend/horizon/render/hal"
"gitlab.com/tokend/horizon/render/problem"
"gitlab.com/tokend/horizon/render/sse"
"gitlab.com/tokend/horizon/resource"
)
type PricesHistoryAction struct {
Action
BaseAsset string
QuoteAsset string
Since time.Time
Records []history.PricePoint
Resource resource.PriceHistory
}
func (action *PricesHistoryAction) JSON() {
action.Do(
action.loadParams,
action.loadRecords,
action.addPadding,
action.loadResource,
func() {
hal.Render(action.W, action.Resource)
},
)
}
func (action *PricesHistoryAction) SSE(stream sse.Stream) {
action.Setup(
action.loadParams,
)
action.Do(
func() {
// we will reuse this variable in sse, so re-initializing is required
action.Records = []history.PricePoint{}
},
action.loadRecords,
func() {
records := action.Records[:]
for _, record := range records {
stream.Send(sse.Event{
ID: record.Timestamp.Format(time.RFC3339),
Data: record.Price,
})
action.Since = record.Timestamp
}
})
}
func (action *PricesHistoryAction) loadRecords() {
points, err := action.HistoryQ().PriceHistory(action.BaseAsset, action.QuoteAsset, action.Since)
if err != nil {
action.Log.WithError(err).Error("failed to get price history")
action.Err = &problem.ServerError
return
}
action.Records = points
}
func (action *PricesHistoryAction) loadParams() {
var err error
action.BaseAsset = action.GetNonEmptyString("base_asset")
action.QuoteAsset = action.GetNonEmptyString("quote_asset")
since := action.GetString("since")
if action.Err == nil {
if since != "" {
action.Since, err = time.Parse(time.RFC3339, since)
if err != nil {
action.SetInvalidField("since", err)
return
}
} else {
action.Since = time.Unix(0, 0)
}
}
}
func (action *PricesHistoryAction) addPadding() {
nilPointsCount := 360 - len(action.Records)
if nilPointsCount >= 0 {
if action.Records == nil || len(action.Records) < 2 {
action.Err = &problem.BeforeHistory
return
}
diff := action.Records[len(action.Records)-2].Timestamp.Sub(action.Records[len(action.Records)-1].Timestamp)
for i := 0; i < nilPointsCount; i++ {
action.Records = append(action.Records, history.PricePoint{Price: 0, Timestamp: action.Records[len(action.Records)-1].Timestamp.Add(diff)})
}
}
}
func (action *PricesHistoryAction) loadResource() {
action.Resource.Prices = action.Records
}