forked from thrasher-corp/gocryptotrader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kline.go
568 lines (517 loc) · 15.7 KB
/
kline.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
package kline
import (
"errors"
"fmt"
"sort"
"strings"
"time"
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/currency"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
)
// CreateKline creates candles out of trade history data for a set time interval
func CreateKline(trades []order.TradeHistory, interval Interval, p currency.Pair, a asset.Item, exchange string) (Item, error) {
if interval.Duration() < time.Minute {
return Item{}, fmt.Errorf("invalid time interval: [%s]", interval)
}
if err := validateData(trades); err != nil {
return Item{}, err
}
timeIntervalStart := trades[0].Timestamp.Truncate(interval.Duration())
timeIntervalEnd := trades[len(trades)-1].Timestamp
// Adds time interval buffer zones
var timeIntervalCache [][]order.TradeHistory
var candleStart []time.Time
for t := timeIntervalStart; t.Before(timeIntervalEnd); t = t.Add(interval.Duration()) {
timeBufferEnd := t.Add(interval.Duration())
insertionCount := 0
var zonedTradeHistory []order.TradeHistory
for i := 0; i < len(trades); i++ {
if (trades[i].Timestamp.After(t) ||
trades[i].Timestamp.Equal(t)) &&
(trades[i].Timestamp.Before(timeBufferEnd) ||
trades[i].Timestamp.Equal(timeBufferEnd)) {
zonedTradeHistory = append(zonedTradeHistory, trades[i])
insertionCount++
continue
}
trades = trades[i:]
break
}
candleStart = append(candleStart, t)
// Insert dummy in time period when there is no price action
if insertionCount == 0 {
timeIntervalCache = append(timeIntervalCache, []order.TradeHistory{})
continue
}
timeIntervalCache = append(timeIntervalCache, zonedTradeHistory)
}
if candleStart == nil {
return Item{}, errors.New("candle start cannot be nil")
}
var candles = Item{
Exchange: exchange,
Pair: p,
Asset: a,
Interval: interval,
}
var closePriceOfLast float64
for x := range timeIntervalCache {
if len(timeIntervalCache[x]) == 0 {
candles.Candles = append(candles.Candles, Candle{
Time: candleStart[x],
High: closePriceOfLast,
Low: closePriceOfLast,
Close: closePriceOfLast,
Open: closePriceOfLast})
continue
}
var newCandle = Candle{
Open: timeIntervalCache[x][0].Price,
Time: candleStart[x],
}
for y := range timeIntervalCache[x] {
if y == len(timeIntervalCache[x])-1 {
newCandle.Close = timeIntervalCache[x][y].Price
closePriceOfLast = timeIntervalCache[x][y].Price
}
if newCandle.High < timeIntervalCache[x][y].Price {
newCandle.High = timeIntervalCache[x][y].Price
}
if newCandle.Low > timeIntervalCache[x][y].Price || newCandle.Low == 0 {
newCandle.Low = timeIntervalCache[x][y].Price
}
newCandle.Volume += timeIntervalCache[x][y].Amount
}
candles.Candles = append(candles.Candles, newCandle)
}
return candles, nil
}
// validateData checks for zero values on data and sorts before turning
// converting into OHLC
func validateData(trades []order.TradeHistory) error {
if len(trades) < 2 {
return errors.New("insufficient data")
}
for i := range trades {
if trades[i].Timestamp.IsZero() ||
trades[i].Timestamp.Unix() == 0 {
return fmt.Errorf("timestamp not set for element %d", i)
}
if trades[i].Amount == 0 {
return fmt.Errorf("amount not set for element %d", i)
}
if trades[i].Price == 0 {
return fmt.Errorf("price not set for element %d", i)
}
}
sort.Slice(trades, func(i, j int) bool {
return trades[i].Timestamp.Before(trades[j].Timestamp)
})
return nil
}
// String returns numeric string
func (i Interval) String() string {
return i.Duration().String()
}
// Word returns text version of Interval
func (i Interval) Word() string {
return durationToWord(i)
}
// Duration returns interval casted as time.Duration for compatibility
func (i Interval) Duration() time.Duration {
return time.Duration(i)
}
// Short returns short string version of interval
func (i Interval) Short() string {
s := i.String()
if strings.HasSuffix(s, "m0s") {
s = s[:len(s)-2]
}
if strings.HasSuffix(s, "h0m") {
s = s[:len(s)-2]
}
return s
}
// FillMissingDataWithEmptyEntries amends a kline item to have candle entries
// for every interval between its start and end dates derived from ranges
func (k *Item) FillMissingDataWithEmptyEntries(i *IntervalRangeHolder) {
var anyChanges bool
for x := range i.Ranges {
for y := range i.Ranges[x].Intervals {
if !i.Ranges[x].Intervals[y].HasData {
for z := range k.Candles {
if i.Ranges[x].Intervals[y].Start.Equal(k.Candles[z].Time) {
break
}
}
anyChanges = true
k.Candles = append(k.Candles, Candle{
Time: i.Ranges[x].Intervals[y].Start.Time,
})
}
}
}
if anyChanges {
k.SortCandlesByTimestamp(false)
}
}
// RemoveDuplicates removes any duplicate candles
func (k *Item) RemoveDuplicates() {
var newCandles []Candle
for x := range k.Candles {
if x == 0 {
newCandles = append(newCandles, k.Candles[x])
continue
}
if !k.Candles[x].Time.Equal(k.Candles[x-1].Time) {
// don't add duplicate
newCandles = append(newCandles, k.Candles[x])
}
}
k.Candles = newCandles
}
// RemoveOutsideRange removes any candles outside the start and end date
func (k *Item) RemoveOutsideRange(start, end time.Time) {
var newCandles []Candle
for i := range k.Candles {
if k.Candles[i].Time.Equal(start) ||
(k.Candles[i].Time.After(start) && k.Candles[i].Time.Before(end)) {
newCandles = append(newCandles, k.Candles[i])
}
}
k.Candles = newCandles
}
// SortCandlesByTimestamp sorts candles by timestamp
func (k *Item) SortCandlesByTimestamp(desc bool) {
sort.Slice(k.Candles, func(i, j int) bool {
if desc {
return k.Candles[i].Time.After(k.Candles[j].Time)
}
return k.Candles[i].Time.Before(k.Candles[j].Time)
})
}
// FormatDates converts all dates to UTC time
func (k *Item) FormatDates() {
for x := range k.Candles {
k.Candles[x].Time = k.Candles[x].Time.UTC()
}
}
// durationToWord returns english version of interval
func durationToWord(in Interval) string {
switch in {
case FifteenSecond:
return "fifteensecond"
case OneMin:
return "onemin"
case ThreeMin:
return "threemin"
case FiveMin:
return "fivemin"
case TenMin:
return "tenmin"
case FifteenMin:
return "fifteenmin"
case ThirtyMin:
return "thirtymin"
case OneHour:
return "onehour"
case TwoHour:
return "twohour"
case FourHour:
return "fourhour"
case SixHour:
return "sixhour"
case EightHour:
return "eighthour"
case TwelveHour:
return "twelvehour"
case OneDay:
return "oneday"
case ThreeDay:
return "threeday"
case FifteenDay:
return "fifteenday"
case OneWeek:
return "oneweek"
case TwoWeek:
return "twoweek"
case OneMonth:
return "onemonth"
case OneYear:
return "oneyear"
default:
return "notfound"
}
}
// TotalCandlesPerInterval turns total candles per period for interval
func TotalCandlesPerInterval(start, end time.Time, interval Interval) (out float64) {
switch interval {
case FifteenSecond:
return end.Sub(start).Seconds() / 15
case OneMin:
return end.Sub(start).Minutes()
case ThreeMin:
return end.Sub(start).Minutes() / 3
case FiveMin:
return end.Sub(start).Minutes() / 5
case TenMin:
return end.Sub(start).Minutes() / 10
case FifteenMin:
return end.Sub(start).Minutes() / 15
case ThirtyMin:
return end.Sub(start).Minutes() / 30
case OneHour:
return end.Sub(start).Hours()
case TwoHour:
return end.Sub(start).Hours() / 2
case FourHour:
return end.Sub(start).Hours() / 4
case SixHour:
return end.Sub(start).Hours() / 6
case EightHour:
return end.Sub(start).Hours() / 8
case TwelveHour:
return end.Sub(start).Hours() / 12
case OneDay:
return end.Sub(start).Hours() / 24
case ThreeDay:
return end.Sub(start).Hours() / 72
case FifteenDay:
return end.Sub(start).Hours() / (24 * 15)
case OneWeek:
return end.Sub(start).Hours() / (24 * 7)
case TwoWeek:
return end.Sub(start).Hours() / (24 * 14)
case OneMonth:
return end.Sub(start).Hours() / (24 * 30)
case OneYear:
return end.Sub(start).Hours() / 8760
}
return -1
}
var oneYearDurationInNano = float64(OneYear.Duration().Nanoseconds())
// IntervalsPerYear helps determine the number of intervals in a year
// used in CAGR calculation to know the amount of time of an interval in a year
func (i *Interval) IntervalsPerYear() float64 {
if i.Duration() == 0 {
return 0
}
return oneYearDurationInNano / float64(i.Duration().Nanoseconds())
}
// ConvertToNewInterval allows the scaling of candles to larger candles
// eg convert OneDay candles to ThreeDay candles, if there are adequate candles
// incomplete candles are NOT converted
// eg an 4 OneDay candles will convert to one ThreeDay candle, skipping the fourth
func ConvertToNewInterval(item *Item, newInterval Interval) (*Item, error) {
if item == nil {
return nil, errNilKline
}
if newInterval <= 0 {
return nil, ErrUnsetInterval
}
if newInterval.Duration() <= item.Interval.Duration() {
return nil, ErrCanOnlyDownscaleCandles
}
if newInterval.Duration()%item.Interval.Duration() != 0 {
return nil, ErrWholeNumberScaling
}
oldIntervalsPerNewCandle := int64(newInterval / item.Interval)
var candleBundles [][]Candle
candles := make([]Candle, 0, oldIntervalsPerNewCandle)
for i := range item.Candles {
candles = append(candles, item.Candles[i])
intervalCount := int64(i + 1)
if oldIntervalsPerNewCandle == intervalCount {
candleBundles = append(candleBundles, candles)
candles = candles[:0]
}
}
responseCandle := &Item{
Exchange: item.Exchange,
Pair: item.Pair,
Asset: item.Asset,
Interval: newInterval,
}
for i := range candleBundles {
var lowest, highest, volume float64
lowest = candleBundles[i][0].Low
highest = candleBundles[i][0].High
for j := range candleBundles[i] {
volume += candleBundles[i][j].Volume
if candleBundles[i][j].Low < lowest {
lowest = candleBundles[i][j].Low
}
if candleBundles[i][j].High > highest {
lowest = candleBundles[i][j].High
}
volume += candleBundles[i][j].Volume
}
responseCandle.Candles = append(responseCandle.Candles, Candle{
Time: candleBundles[i][0].Time,
Open: candleBundles[i][0].Open,
High: highest,
Low: lowest,
Close: candleBundles[i][len(candleBundles[i])-1].Close,
Volume: volume,
})
}
return responseCandle, nil
}
// CalculateCandleDateRanges will calculate the expected candle data in intervals in a date range
// If an API is limited in the amount of candles it can make in a request, it will automatically separate
// ranges into the limit
func CalculateCandleDateRanges(start, end time.Time, interval Interval, limit uint32) (*IntervalRangeHolder, error) {
if err := common.StartEndTimeCheck(start, end); err != nil && !errors.Is(err, common.ErrStartAfterTimeNow) {
return nil, err
}
if interval <= 0 {
return nil, ErrUnsetInterval
}
start = start.Round(interval.Duration())
end = end.Round(interval.Duration())
resp := &IntervalRangeHolder{
Start: CreateIntervalTime(start),
End: CreateIntervalTime(end),
}
var intervalsInWholePeriod []IntervalData
for i := start; i.Before(end) && !i.Equal(end); i = i.Add(interval.Duration()) {
intervalsInWholePeriod = append(intervalsInWholePeriod, IntervalData{
Start: CreateIntervalTime(i.Round(interval.Duration())),
End: CreateIntervalTime(i.Round(interval.Duration()).Add(interval.Duration())),
})
}
if len(intervalsInWholePeriod) < int(limit) || limit == 0 {
resp.Ranges = []IntervalRange{{
Start: CreateIntervalTime(start),
End: CreateIntervalTime(end),
Intervals: intervalsInWholePeriod,
}}
return resp, nil
}
var intervals []IntervalData
splitIntervalsByLimit := make([][]IntervalData, 0, len(intervalsInWholePeriod)/int(limit)+1)
for len(intervalsInWholePeriod) >= int(limit) {
intervals, intervalsInWholePeriod = intervalsInWholePeriod[:limit], intervalsInWholePeriod[limit:]
splitIntervalsByLimit = append(splitIntervalsByLimit, intervals)
}
if len(intervalsInWholePeriod) > 0 {
splitIntervalsByLimit = append(splitIntervalsByLimit, intervalsInWholePeriod)
}
for x := range splitIntervalsByLimit {
resp.Ranges = append(resp.Ranges, IntervalRange{
Start: splitIntervalsByLimit[x][0].Start,
End: splitIntervalsByLimit[x][len(splitIntervalsByLimit[x])-1].End,
Intervals: splitIntervalsByLimit[x],
})
}
return resp, nil
}
// HasDataAtDate determines whether a there is any data at a set
// date inside the existing limits
func (h *IntervalRangeHolder) HasDataAtDate(t time.Time) bool {
tu := t.Unix()
if tu < h.Start.Ticks || tu > h.End.Ticks {
return false
}
for i := range h.Ranges {
if tu >= h.Ranges[i].Start.Ticks && tu <= h.Ranges[i].End.Ticks {
for j := range h.Ranges[i].Intervals {
if tu >= h.Ranges[i].Intervals[j].Start.Ticks && tu < h.Ranges[i].Intervals[j].End.Ticks {
return h.Ranges[i].Intervals[j].HasData
}
if j == len(h.Ranges[i].Intervals)-1 {
if tu == h.Ranges[i].Start.Ticks {
return h.Ranges[i].Intervals[j].HasData
}
}
}
}
}
return false
}
// GetClosePriceAtTime returns the close price of a candle
// at a given time
func (k *Item) GetClosePriceAtTime(t time.Time) (float64, error) {
for i := range k.Candles {
if k.Candles[i].Time.Equal(t) {
return k.Candles[i].Close, nil
}
}
return -1, fmt.Errorf("%w at %v", ErrNotFoundAtTime, t)
}
// SetHasDataFromCandles will calculate whether there is data in each candle
// allowing any missing data from an API request to be highlighted
func (h *IntervalRangeHolder) SetHasDataFromCandles(c []Candle) {
for x := range h.Ranges {
intervals:
for y := range h.Ranges[x].Intervals {
for z := range c {
cu := c[z].Time.Unix()
if cu >= h.Ranges[x].Intervals[y].Start.Ticks && cu < h.Ranges[x].Intervals[y].End.Ticks {
h.Ranges[x].Intervals[y].HasData = true
continue intervals
}
}
h.Ranges[x].Intervals[y].HasData = false
}
}
}
// DataSummary returns a summary of a data range to highlight where data is missing
func (h *IntervalRangeHolder) DataSummary(includeHasData bool) []string {
var (
rangeStart, rangeEnd, prevStart, prevEnd time.Time
rangeHasData bool
rangeTexts []string
)
rangeStart = h.Start.Time
for i := range h.Ranges {
for j := range h.Ranges[i].Intervals {
if h.Ranges[i].Intervals[j].HasData {
if !rangeHasData && !rangeEnd.IsZero() {
rangeTexts = append(rangeTexts, h.createDateSummaryRange(rangeStart, rangeEnd, rangeHasData))
prevStart = rangeStart
prevEnd = rangeEnd
rangeStart = h.Ranges[i].Intervals[j].Start.Time
}
rangeHasData = true
} else {
if rangeHasData && !rangeEnd.IsZero() {
if includeHasData {
rangeTexts = append(rangeTexts, h.createDateSummaryRange(rangeStart, rangeEnd, rangeHasData))
}
prevStart = rangeStart
prevEnd = rangeEnd
rangeStart = h.Ranges[i].Intervals[j].Start.Time
}
rangeHasData = false
}
rangeEnd = h.Ranges[i].Intervals[j].End.Time
}
}
if !rangeStart.Equal(prevStart) || !rangeEnd.Equal(prevEnd) {
if (rangeHasData && includeHasData) || !rangeHasData {
rangeTexts = append(rangeTexts, h.createDateSummaryRange(rangeStart, rangeEnd, rangeHasData))
}
}
return rangeTexts
}
func (h *IntervalRangeHolder) createDateSummaryRange(start, end time.Time, hasData bool) string {
dataString := "missing"
if hasData {
dataString = "has"
}
return fmt.Sprintf("%s data between %s and %s",
dataString,
start.Format(common.SimpleTimeFormat),
end.Format(common.SimpleTimeFormat))
}
// CreateIntervalTime is a simple helper function to set the time twice
func CreateIntervalTime(tt time.Time) IntervalTime {
return IntervalTime{Time: tt, Ticks: tt.Unix()}
}
// Equal allows for easier unix comparison
func (i *IntervalTime) Equal(tt time.Time) bool {
return tt.Unix() == i.Ticks
}