-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjanitor.go
91 lines (79 loc) · 2.12 KB
/
janitor.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
package main
import (
"os"
"os/signal"
"time"
"github.com/sinisterminister/coinfactory"
"github.com/spf13/viper"
log "github.com/sirupsen/logrus"
)
func startJanitor(p *SpreadPlayerProcessor) {
log.Info("Order janitor started successfully")
timer := time.NewTicker(15 * time.Second)
// Intercept the interrupt signal and pass it along
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
// Start the loop
for {
select {
case <-timer.C:
p.openOrdersMux.Lock()
pruneOpenOrders(p)
cancelExpiredStaleOrders(p)
p.openOrdersMux.Unlock()
case <-interrupt:
p.janitorQuitChannel <- true
case <-p.janitorQuitChannel:
return
}
}
}
func pruneOpenOrders(p *SpreadPlayerProcessor) {
log.Debug("Pruning open orders")
openOrders := []*coinfactory.Order{}
for _, o := range p.openOrders {
// Remove any closed orders
switch o.GetStatus().Status {
// Skip this cases
case "NEW":
case "PARTIALLY_FILLED":
case "PENDING_CANCEL":
case "":
// Delete the rest
default:
log.WithField("order", o).Debug("Removing closed order")
continue
}
// Remove stale orders
if o.GetAge().Nanoseconds() > viper.GetDuration("spreadprocessor.markOrderAsStaleAfter").Nanoseconds() {
log.WithField("order", o).Debug("Marking order as stale")
p.staleOrders = append(p.staleOrders, o)
continue
}
openOrders = append(openOrders, o)
}
p.openOrders = openOrders
}
func cancelExpiredStaleOrders(p *SpreadPlayerProcessor) {
staleOrders := []*coinfactory.Order{}
for _, o := range p.staleOrders {
// Cancel expired orders
if o.GetAge().Nanoseconds() > viper.GetDuration("spreadprocessor.cancelOrderAfter").Nanoseconds() {
log.WithField("order", o).Warn("Cancelling expired order")
go cancelOrder(o)
continue
}
staleOrders = append(staleOrders, o)
}
p.staleOrders = staleOrders
}
func cancelOrder(o *coinfactory.Order) {
err := cf.GetOrderManager().CancelOrder(o)
if err != nil {
if o.GetStatus().Status != "CANCELED" {
log.WithError(err).Error("Could not cancel expired order")
// Try again but bail if it fail
cf.GetOrderManager().CancelOrder(o)
}
}
}